text:
Q: Image at center of ImageView inside Nested LinearLayout I am trying to get the image at center of the imageviews named divider1,divider2 and divider3. But all I am getting is this:-

As you can see between the score and comment the image is little bit upwards shifted. The image is a 5x5 pixel 'dot'.
My XML file:-
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:background="#d3d3d3"
    android:padding="10dp" >
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical"
        android:background="@drawable/rounded">

        <TextView
            android:id="@+id/list_title"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:textAppearance="?android:attr/textAppearanceLarge"
            android:textColor="#ffffff"
            android:padding="2dp"/>
        <LinearLayout
            android:id="@+id/ll"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="horizontal"
            android:padding="2dp">
            <TextView
            android:id="@+id/list_author"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textAppearance="?android:attr/textAppearanceSmall"
            android:textColor="#ffffff"
            android:padding="2dp" />
            <ImageView
                android:id="@+id/divider1"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:src="@drawable/divider"
                android:scaleType="centerInside"
                android:padding="2dp"/>
            <TextView
            android:id="@+id/list_domain"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textAppearance="?android:attr/textAppearanceSmall"
            android:textColor="#ffffff"
            android:padding="2dp" />
            <ImageView
                android:id="@+id/divider2"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:src="@drawable/divider"
                android:scaleType="centerInside"
                android:padding="2dp"/>
            <TextView
            android:id="@+id/list_time"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textAppearance="?android:attr/textAppearanceSmall"
            android:textColor="#ffffff"
            android:padding="2dp"/>
            </LinearLayout>
            <ImageView
                android:id="@+id/list_image"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                />
            <LinearLayout
                android:id="@+id/ll2"
               android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="horizontal"
            android:padding="2dp" >
                <TextView
            android:id="@+id/list_score"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textAppearance="?android:attr/textAppearanceSmall"
            android:textColor="#ffffff"
            android:padding="2dp" />
            <ImageView
                android:id="@+id/divider3"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:src="@drawable/divider"
                android:scaleType="centerInside"
                android:padding="2dp"/>
            <TextView
            android:id="@+id/list_comments"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textAppearance="?android:attr/textAppearanceSmall"
            android:textColor="#ffffff"
            android:padding="2dp" />
            </LinearLayout>
    </LinearLayout>

</LinearLayout>

Any Ideas what is wrong?

A: The image view is wrapping depend on it's content
android:layout_width="wrap_content"

Set the image view height to match the container. and then you centre the image inside:
<ImageView
    android:id="@+id/divider3"
    android:layout_width="wrap_content"
    android:layout_height="match_parent"
    android:scaleType="center"
    android:src="@drawable/divider"
    android:padding="2dp"/>

Set those in your imageView.


text:
Q: Objects with and In a daily I read (name has been changed):
Mr X takes a holiday with his divorced wife and daughter.
Is this correct? Here, doesn't divorced qualify both wife and daughter here?

A: No, it doesn't, because you can't divorce your daughter.

A: Possibly it could qualify both, if we were saying Mr X takes a holdiday with his divorced wife, and his daughter who is also divorced (as opposed to some other daughter). But one wouldn't normally mean that by the phrase.
Another objection would be that Mr X couldn't take a holiday with his divorced wife, as if he is divorced from her, she isn't his wife. It could, at a pinch, mean he is taking a holiday with his wife who is divorced from someone else, as opposed to a different wife, if he had more than one.

A: This is a horrible sentence really.
"Mr X takes a holiday with his divorced wife and daughter."
It has so many possible meanings, none of which are well stated.
"Mr. X takes a holiday with his ex-wife and their daughter"
"Mr. X takes a holiday with his wife and daughter, both themselves divorcees"
"Mr X takes a holiday with his wife, a divorcee, and their daughter"
"Mr X takes a holiday with his wife, a divorcee, and her daughter"
and I'm sure even more oblique versions are possible.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to allow HTTP-connections (not HTTPS) in WebView on Android? I have a WebView application on Android and I want to fetch data from a resource which uses HTTP only. To do so, I use XMLHttpRequest API in JavaScript.
When I fetch data from any other HTTPS-resource, everything is OK. But HTTP never works. How can I fix that?
Is there any way to allow HTTP-connections using JavaScript?

A: android:usesCleartextTrafficThe default value for apps that target API level 27 or lower is true. Apps that target API level 28 or higher default to false. here
<?xml version="1.0" encoding="utf-8"?>
<manifest ...>
   <uses-permission android:name="android.permission.INTERNET" />
   <application
     ...
     android:usesCleartextTraffic="true"
     ...>
     ...
   </application>
</manifest>


text:
Q: Get time stamp via Boost.Chrono in resolution of nanoseconds Does boost chrono provides time stamp with nanoseconds resolution?? If yes how to get the time stamp?

A: Nanoseconds resolution ? On which hardware do you want to run your program ?
On my PC, my performance counter has a frequency of approx. 4 Mhz, so a tick last 250 ns.
As answered here, boost chrono can give you the nanosecond resolution, but you will not be sure of the measure's accuracy.

A: In order to easily get time stamps with boost chrono for different measurements you can use boost CPU Timers. A table about the timer accuracy is also given on this site.
To measure the resolution yourself on your specific hardware use boost's cpu_timer_info.cpp.


text:
Q: onEnter Transitions with React Router and Redux Simple Router Dont Render New Route's Component I have an app using react @0.14, redux @3.05, react-router @1.0.3, and redux-simple-router @2.0.2. I'm trying to configure onEnter transitions for some of my routes based on store state. The transition hooks successfully fire and push new state to my store, which changes the url. However, the actual component that is rendered on the page is the original component handler from the route match, not the new component handler for the new url.
Here is what my routes.js file looks like
export default function configRoutes(store) {
  const authTransition = function authTransition(location, replaceWith) {
    const state = store.getState()
    const user = state.user

    if (!user.isAuthenticated) {
      store.dispatch(routeActions.push('/login'))
    }
  }

  return (
    <Route component={App}>
      <Route path="/" component={Home}/>
      <Route path="/login" component={Login}/>
      <Route path="/dashboard" component={Dashboard} onEnter={authTransition}/>
      <Route path="/workouts" component={Workout} onEnter={authTransition}>
        <IndexRoute component={WorkoutsView}/>
        <Route path="/workouts/create" component={WorkoutCreate}/>
      </Route>
    </Route>
  )
}

Here is my Root.js component that gets inserted into the DOM
export default class Root extends React.Component {
  render() {
    const { store, history } = this.props
    const routes = configRoutes(store)

    return (
      <Provider store={store}>
        <div>
          {isDev ? <DevTools /> : null}
          <Router history={history} children={routes} />
        </div>
      </Provider>
    )
  }
}

To clarify, if I go to '/workouts', it will fire the onEnter authTransition hook, dispatch the redux-simple-router push action, change the url to '/login', but will display the Workout component on the page. Looking in Redux DevTools shows that state -> router -> location -> pathname is '/login'.
The state flow is

*

*@@INIT

*@@ROUTER/UPDATE_LOCATION (/workouts)

*@@ROUTER/UPDATE_LOCATION (/login)

Am I passing the store to the routes incorrectly? I can't figure out why the next Router/Update_Location doesn't work

A: Turns out you want to use the react-router api (replace), not the redux-simple-router to control your transitions.
const authTransition = function authTransition(nextState, replace, callback) {
  const state = store.getState()
  const user = state.user

  // todo: in react-router 2.0, you can pass a single object to replace :)
  if (!user.isAuthenticated) {
    replace({ nextPathname: nextState.location.pathname }, '/login', nextState.location.query)
  }

  callback()
}

Also, be careful. I saw a lot of documentation out there for the react-router replace where you pass a single object. That's for react-router 2.0-rc*. If you're using react-router 1.0, you're going to want to pass replace 3 separate arguments.


text:
Q: Admob Crashing App when final Ads are implemented - SwiftUI Trying to implement AdMob on my iOS/SwiftUI app. Chose the BannerAd style, implemented it in a few screens. Have been using the test ads, as per admob guidelines, for a while, with no issues. However, now that I want to implement the real ads and I change the unitID for the AdMob key, my app crashes in Testflight. This is weird, because it works in XCode's test devices and my device in test mode. When I search the internet, most solutions are either for Android or Interstitial Ads...
Banner Ad Backend
import SwiftUI
import GoogleMobileAds

struct BannerAd: UIViewRepresentable {
    var unitID: String
    func makeCoordinator() -> Coordinator {
        return Coordinator()
    }
    func makeUIView(context: Context) -> GADBannerView{
        let adView = GADBannerView(adSize: GADAdSizeBanner)
        adView.adUnitID = unitID
        adView.rootViewController = UIApplication.shared.getRootViewController()
        adView.delegate = context.coordinator
        adView.load(GADRequest())
        return adView
    }
    func updateUIView(_ uiView: GADBannerView, context: Context) {
    }
    class Coordinator: NSObject,GADBannerViewDelegate{
        func bannerViewDidReceiveAd(_ bannerView: GADBannerView) {
          print("bannerViewDidReceiveAd")
        }

        func bannerView(_ bannerView: GADBannerView, didFailToReceiveAdWithError error: Error) {
          print("bannerView:didFailToReceiveAdWithError: \(error.localizedDescription)")
        }

        func bannerViewDidRecordImpression(_ bannerView: GADBannerView) {
          print("bannerViewDidRecordImpression")
        }

        func bannerViewWillPresentScreen(_ bannerView: GADBannerView) {
          print("bannerViewWillPresentScreen")
        }

        func bannerViewWillDismissScreen(_ bannerView: GADBannerView) {
          print("bannerViewWillDIsmissScreen")
        }

        func bannerViewDidDismissScreen(_ bannerView: GADBannerView) {
          print("bannerViewDidDismissScreen")
        }
    }

}
extension UIApplication{
    func getRootViewController()->UIViewController{
        guard let screen = self.connectedScenes.first as? UIWindowScene else{
            return .init()
        }

        guard let root = screen.windows.first?.rootViewController else{
            return .init()
        }

        return root
    }
}

The Banner Ad implementation Example:
import SwiftUI
import MessageUI
import AppTrackingTransparency

struct PatientsView: View {

    [...]
            ScrollView(){
            BannerAd(unitID: "ca-app-pub-numbers")
                    .frame(maxHeight: 50)
                VStack(alignment:.leading){
                    [...]
                }
                    Spacer()
                    Spacer()
                }
                .padding(.top, 30.0)
            }

        }
}


text:
Q: How to (completely) uninstall Code Contracts Tool extension? I'm trying to get rid of Code Contracts Tools extension on my system. I've uninstalled it from "programs and functionalities" yet it still appears as an installed extension inside Visual Studio.
Any help would be appreciated.

A: The uninstaller does not remove all files that are no longer needed. In particular, the actual VSIX files are never deleted:

*

*codecontracts_project.png

*codecontracts_SM.png

*extension.vsixmanifest

*license.rtf

These files seem to be a source of trouble when upgrading the tools to a newer version.
To completely uninstall the tools:

*

*Close all instances of Visual Studio to prevent file locks

*Remove the tools using the uninstaller listed under "Programs and Features"

*Delete the extension folder:
<Visual Studio installation folder>\Common7\IDE\Extensions\Microsoft\CodeContracts

A: I know this is an old post, but if you stumble in here looking for a way to remove Code Contracts, this is what finally worked for me:
BEFORE DOING ANYTHING: Make sure all instances of Visual studio have been closed on the PC.
1) Uninstall Code Contracts using the Control Panel.
2) Delete the folder C:\Program Files (x86)\Microsoft Visual Studio 12.0\Common7\IDE\Extensions\Microsoft\CodeContracts.
3) Open the file C:\Program Files (x86)\Microsoft Visual Studio 12.0\Common7\IDE\Extensions\extensions.configurationchanged with windows note pad, and then click file > Save. Make sure you don't actually make any changes to the file. VS is looking for a change in the last modified date to refresh the extensions.
Now start Visual Studio and make sure the Code Contracts extension is gone from the extensions screen. Like others here I'd done step 1 and 2, and it wasn't working. I gleaned step 3  from from the following post on MSDN:
https://social.msdn.microsoft.com/Forums/en-US/17d132a3-d2e7-48be-bdca-b0b6421e544a/may-21-2014-release?forum=codecontracts


text:
Q: Angular 2 shows two components for one route For a little project I experience strange behaviour for Angular CLI: 1.7.4 and Node: 9.11.1. The main Problem is that the app shows two different pages (Overview + Detail) upon double-click, but for contextmenu > click it works as expected (only showing Detail) although they use the same method for redirect.
The image shows the expected DOM (=works for contextmenu > click) and the actual result for double-click:

app-routing.module.ts: (my main routing file)
const routes: Routes = [
  { path: 'overview', component: OverviewComponent, canActivate: [AuthGuardService], data: { title: 'Produktionskette' } },
  { path: 'options', component: OptionComponent, canActivate: [AuthGuardService], data: { title: 'Optionen' } },
  { path: 'login', component: LoginComponent, data: { title: 'Anmelden' } },
  { path: 'details/:id', component: DetailComponent, canActivate: [AuthGuardService], data: { title: 'Details' } },
  { path: '', redirectTo: '/overview', pathMatch: 'full' },
  { path: '**', redirectTo: '/overview' }
];

@NgModule({
  exports: [ RouterModule ],
  imports: [ RouterModule.forRoot(routes) ]
})
export class AppRoutingModule { }

The components are very basic and interact with vanilla-JS together with jQuery. In the diagram the context menu is initialized as:
context.find(".contextView").click(event => {
    event.preventDefault();
    context.hide();
    if (selectedDevice) {
        showDeviceDetails(selectedDevice);
    }
});

The double-click is initialized inside every device (for each device):
object.dblclick(() => diagram.showDeviceDetails(_this));

The Angular 2 components are defined as follows:
overview.component.ts: (/overview)
@Component({
  selector: 'app-overview',
  templateUrl: './overview.component.html',
  styleUrls: ['./overview.component.css']
})

export class OverviewComponent implements OnInit {
  // does not do very much, just loading etc
}

detail.component.ts: (details/:id)
Component({
  selector: 'app-detail',
  templateUrl: './detail.component.html',
  styleUrls: ['./detail.component.css']
})
export class DetailComponent implements OnInit {
  // also works as intended
}

Could this be a routing problem? As said both doubleclick and contextmenu>click use the same method and both execution types work inside the detail-component.


text:
Q: User Resizing of Row and Columns in TableLayoutPanel At Runtime I'm working on a WinForm project and "trying" to create a TableLayoutPanel that the user can resize at runtime like the behavior of the SplitContainer. I've found some code that partially does this but it's incomplete. Can someone please help me out here?
Thanks in advance,
-DA
This is the code I have so far that comes from a thread I found on CodeProject. The only thing different that I've done in my own is create a customTableLayoutPanel that inherits from TableLayoutPanel.
public partial class Form1 : Form
{
    bool resizing = false;
    TableLayoutRowStyleCollection rowStyles;
    TableLayoutColumnStyleCollection columnStyles;

    public Form1()
    {
        InitializeComponent();
    }

    private void Form1_Load(object sender, EventArgs e)
    {
        rowStyles = tableLayoutPanel1.RowStyles;
        columnStyles = tableLayoutPanel1.ColumnStyles;
    }

    private void tableLayoutPanel1_MouseDown(object sender, MouseEventArgs e)
    {
        if (e.Button == System.Windows.Forms.MouseButtons.Left)
        {
            resizing = true;
        }
    }

    private void tableLayoutPanel1_MouseMove(object sender, MouseEventArgs e)
    {
        if (resizing)
        {
            columnStyles[0].SizeType = SizeType.Absolute;
            rowStyles[0].SizeType = SizeType.Absolute;
            rowStyles[0].Height = e.Y;
            columnStyles[0].Width = e.X;
        }
    }

    private void tableLayoutPanel1_MouseUp(object sender, MouseEventArgs e)
    {
        if (e.Button == System.Windows.Forms.MouseButtons.Left)
        {
            resizing = false;
        }
    }
}

A: Set Column SizeType and Row SizeType property as Absolute and CellBorderStyle as which ever you want rather than none after that in code write as below
public partial class Form1 : Form
{
    bool resizing = false;
    TableLayoutRowStyleCollection rowStyles;
    TableLayoutColumnStyleCollection columnStyles;
    int colindex = -1;
    int rowindex = -1;
    public Form1()
    {
        InitializeComponent();
    }

    private void Form1_Load(object sender, EventArgs e)
    {
        rowStyles = tableLayoutPanel1.RowStyles;
        columnStyles = tableLayoutPanel1.ColumnStyles;
    }
    private void tableLayoutPanel1_MouseDown(object sender, MouseEventArgs e)
    {
        if (e.Button == System.Windows.Forms.MouseButtons.Left)
        {
            rowStyles = tableLayoutPanel1.RowStyles;
            columnStyles = tableLayoutPanel1.ColumnStyles;
            resizing = true;
        }
    }

    private void tableLayoutPanel1_MouseMove(object sender, MouseEventArgs e)
    {
        if (!resizing)
        {
            float width = 0;
            float height = 0;
            //for rows
            for (int i = 0; i < rowStyles.Count; i++)
            {
                height += rowStyles[i].Height;
                if (e.Y > height - 3 && e.Y < height + 3)
                {
                    rowindex = i;
                    tableLayoutPanel1.Cursor = Cursors.HSplit;
                    break;
                }
                else
                {
                    rowindex = -1;
                    tableLayoutPanel1.Cursor = Cursors.Default;
                }
            }
            //for columns
            for (int i = 0; i < columnStyles.Count; i++)
            {
                width += columnStyles[i].Width;
                if (e.X > width - 3 && e.X < width + 3)
                {
                    colindex = i;
                    if (rowindex > -1)
                        tableLayoutPanel1.Cursor = Cursors.Cross;
                    else
                        tableLayoutPanel1.Cursor = Cursors.VSplit;
                    break;
                }
                else
                {
                    colindex = -1;
                    if (rowindex == -1)
                        tableLayoutPanel1.Cursor = Cursors.Default;
                }
            }
        }
        if (resizing && (colindex>-1 || rowindex > -1))
        {
            float width = e.X;
            float height = e.Y;
            if (colindex > -1)
            {
                for (int i = 0; i < colindex; i++)
                {
                    width -= columnStyles[i].Width;
                }
                columnStyles[colindex].SizeType = SizeType.Absolute;
                columnStyles[colindex].Width = width;
            }
            if (rowindex > -1)
            {
                for (int i = 0; i < rowindex; i++)
                {
                    height -= rowStyles[i].Height;
                }

                rowStyles[rowindex].SizeType = SizeType.Absolute;
                rowStyles[rowindex].Height = height;
            }
        }
    }

    private void tableLayoutPanel1_MouseUp(object sender, MouseEventArgs e)
    {
        if (e.Button == System.Windows.Forms.MouseButtons.Left)
        {
            resizing = false;
            tableLayoutPanel1.Cursor = Cursors.Default;
        }
    }
}

A: I improved the code of MD's answer.
Instead of listening to MouseEvents of the TableLayoutPanel I listen to those of the Controls. Here is the code for resizable rows:
    TableLayoutPanel tlp;
    bool resizing;
    int rowindex = -1;
    int nextHeight;

    private void control_MouseDown(object sender, MouseEventArgs e)
    {
        if (e.Button == MouseButtons.Left)
        {
            resizing = true;
        }
    }

    private void control_MouseMove(object sender, MouseEventArgs e)
    {
        Control c = (Control)sender;
        if (!resizing)
        {
            rowindex = -1;
            tlp.Cursor = Cursors.Default;

            if (e.Y <= 3)
            {
                rowindex = tlp.GetPositionFromControl(c).Row - 1;
                if (rowindex >= 0)
                    tlp.Cursor = Cursors.HSplit;
            }
            if (c.Height - e.Y <= 3)
            {
                rowindex = tlp.GetPositionFromControl(c).Row;
                if (rowindex < tlp.RowStyles.Count)
                    tlp.Cursor = Cursors.HSplit;
            }
        }
        if (resizing && rowindex > -1)
        {
            nextHeight = e.Y;
        }
    }

    private void control_MouseUp(object sender, MouseEventArgs e)
    {
        if (e.Button == System.Windows.Forms.MouseButtons.Left)
        {
            if (nextHeight > 0)
                tlp.RowStyles[rowindex].Height = nextHeight;
            resizing = false;
        }
    }

A: My answer is for using the mouse to resize only the columns of the tablelayoutpanel but can be easily updated to do the same for rows. I'd rather use a splitpanel for the rows of course, but still. In the code I cater for 4 columns but extending it to more or less is easy enough. The cursurToDefault event will be added to the mousemove-event of the container controls inside the tablelayoutpanel.
 private int beamMoving;
 private void tableLayoutPanel1_MouseMove(object sender, MouseEventArgs e)
    {
        this.Cursor = Cursors.VSplit;
        if (e.Button == System.Windows.Forms.MouseButtons.Left)
        {
            int beam0 = (int)tableLayoutPanel1.ColumnStyles[0].Width;
            int beam1 = (int)tableLayoutPanel1.ColumnStyles[0].Width + (int)tableLayoutPanel1.ColumnStyles[1].Width;
            int beam2 = (int)tableLayoutPanel1.ColumnStyles[0].Width + (int)tableLayoutPanel1.ColumnStyles[1].Width + (int)tableLayoutPanel1.ColumnStyles[2].Width;

            switch (beamMoving)
            {
                case 0:
                    {
                        if (e.X > 0)
                        {
                            tableLayoutPanel1.ColumnStyles[0].Width = e.X;
                        }
                        break;
                    }
                case 1:
                    {
                        if (e.X - beam0 > 0)
                        {
                            tableLayoutPanel1.ColumnStyles[1].Width = e.X - beam0;
                        }
                        break;
                    }
                case 2:
                    {
                        if (e.X - beam1 > 0)
                        {
                            tableLayoutPanel1.ColumnStyles[2].Width = e.X - beam1;
                        }
                        break;
                    }
            }
        }
    }
    private void cursorToDefault(object sender, MouseEventArgs e)
    {
        this.Cursor = Cursors.Default;
    }

    private void tableLayoutPanel1_MouseDown(object sender, MouseEventArgs e)
    {
        int beam0 = (int)tableLayoutPanel1.ColumnStyles[0].Width;
        int beam1 = (int)tableLayoutPanel1.ColumnStyles[0].Width + (int)tableLayoutPanel1.ColumnStyles[1].Width;
        int beam2 = (int)tableLayoutPanel1.ColumnStyles[0].Width + (int)tableLayoutPanel1.ColumnStyles[1].Width + (int)tableLayoutPanel1.ColumnStyles[2].Width;
        if (e.X + 20 > beam0 && e.X - 20 < beam1)
        {
            beamMoving = 0;
        }
        if (e.X + 20 > beam1 && e.X - 20 < beam2)
        {
            beamMoving = 1;
        }
        if (e.X + 20 > beam2 && e.X - 20 < tableLayoutPanel1.Width)
        {
            beamMoving = 2;
        }
    }

A: Wrote A Module based on the original code
This uses a dictionary and 4 event handlers for multiple tablelayoutpanel to have their rows and columns re-sized.
There is some code in there for catching moving things off the screen but not much.
Read the comments in the code for more information
Module modResizeableTableLayoutPanel

Private otlpdic As Dictionary(Of String, Integer()) = Nothing

 ''' <summary>
 ''' Adds the needed handlers for resizing the rows and columns of multiple
 ''' tablelayoutpanel uses the tag property
 ''' also requires primary controls in the cells to have a margin of 6... this is
 ''' a hack to detect when the mouse
 ''' is no longer over a divider and not over a control in the cell
 ''' All rows and columns require absolute positioning
 ''' </summary>
 ''' <param name="otlp">tablelayoutpanel</param>
 ''' <remarks></remarks>
Public Sub InitializeResizeableTableLayOutPanel(ByRef otlp As TableLayoutPanel)
    'create has if needed
    Call CreateTableLayoutPanelHash()

    'creat hash entry for TableLayoutPanel
    Call CreateHashEntryForTableLayoutPanel(otlp)

    'sets the border style to something that helps the mouse cursor detect.
    otlp.CellBorderStyle = TableLayoutPanelCellBorderStyle.Single

    'hack to set margins on sub controls
    For Each con In otlp.Controls
        Select Case con.GetType
            Case GetType(FlowLayoutPanel)
                Dim obj As FlowLayoutPanel = DirectCast(con, FlowLayoutPanel)
                obj.Margin = New Padding(6)
            Case GetType(DataGridView)
                Dim obj As DataGridView = DirectCast(con, DataGridView)
                obj.Margin = New Padding(6)
            Case GetType(Button)
                Dim obj As Button = DirectCast(con, Button)
                obj.Margin = New Padding(6)
            Case GetType(GroupBox)
                Dim obj As GroupBox = DirectCast(con, GroupBox)
                obj.Margin = New Padding(6)
        End Select
    Next

    'add event handlers
    AddHandler otlp.MouseDown, AddressOf tlp_MouseDown
    AddHandler otlp.MouseUp, AddressOf tlp_MouseUp
    AddHandler otlp.MouseMove, AddressOf tlp_MouseMove
    AddHandler otlp.MouseLeave, AddressOf tlp_MouseLeave
End Sub

''' <summary>
''' Clear the dictionary/hashtable that keeps track of needed variables to control the resizing
''' </summary>
''' <remarks></remarks>
Public Sub ResetResizeableTableLayOutPanelData()
    otlpdic.Clear()
    otlpdic = Nothing
    Call CreateTableLayoutPanelHash()
End Sub

Private Sub CreateTableLayoutPanelHash()
    If otlpdic Is Nothing Then
         otlpdic = New Dictionary(Of String, Integer())
    End If
End Sub

Private Sub CreateHashEntryForTableLayoutPanel(ByRef otlp As TableLayoutPanel)
    If Not otlp.Tag Is Nothing AndAlso otlpdic.ContainsKey(otlp.Tag) Then

    Else
        Dim tmpguid As Guid = Guid.NewGuid

        otlp.Tag = tmpguid.ToString

        otlpdic.Add(otlp.Tag, {0, -1, -1})
    End If
End Sub

Public Sub tlp_MouseDown(sender As Object, e As System.Windows.Forms.MouseEventArgs)
    If e.Button = System.Windows.Forms.MouseButtons.Left Then
        Dim otlp As TableLayoutPanel = DirectCast(sender, TableLayoutPanel)
        Call CreateHashEntryForTableLayoutPanel(otlp)
        Dim tmpdata As Integer() = otlpdic.Item(otlp.Tag)
        tmpdata(0) = -1

    End If
End Sub

Public Sub tlp_MouseMove(sender As Object, e As System.Windows.Forms.MouseEventArgs)
    Dim otlp As TableLayoutPanel = DirectCast(sender, TableLayoutPanel)
    Call CreateHashEntryForTableLayoutPanel(otlp)
    Dim tmpdata As Integer() = otlpdic.Item(otlp.Tag)

    'Dim rowStyles =
        'columnStyles = TableLayoutPanel1.ColumnStyles

    If Not tmpdata(0) Then

        Dim width As Double = 0
        Dim height As Double = 0
        'for rows
        For i As Integer = 0 To otlp.RowStyles.Count - 1

            height += otlp.RowStyles(i).Height

            If (e.Y > height - 2 And e.Y < height + 2) Then

                tmpdata(1) = i
                otlp.Parent.Cursor = Cursors.HSplit
                Exit For
            Else
                tmpdata(1) = -1
                otlp.Parent.Cursor = Cursors.Default
            End If
        Next
        'for columns
        For i As Integer = 0 To otlp.ColumnStyles.Count - 1

            width += otlp.ColumnStyles(i).Width
            If e.X > width - 2 And e.X < width + 2 Then

                tmpdata(2) = i
                If (tmpdata(1) > -1) Then
                    otlp.Parent.Cursor = Cursors.Cross
                Else
                    otlp.Parent.Cursor = Cursors.VSplit
                    Exit For
                End If
            Else

                tmpdata(2) = -1
                If (tmpdata(1) = -1) Then
                    otlp.Parent.Cursor = Cursors.Default
                End If
            End If
        Next
    End If
    If (tmpdata(0) And (tmpdata(2) > -1 Or tmpdata(1) > -1)) Then

        Dim Width As Double = e.X
        Dim Height As Double = e.Y

        If e.X > otlp.Width - 100 Then
            Exit Sub
        End If

        If e.Y > otlp.Height - 100 Then
            Exit Sub
        End If

        If (tmpdata(2) > -1) Then
            For i As Integer = 0 To tmpdata(2) - 1

                Width -= otlp.ColumnStyles(i).Width
            Next
            otlp.ColumnStyles(tmpdata(2)).SizeType = SizeType.Absolute

            If Width < 10 Then
                Width = 10
            End If

            If Width > otlp.Width - 100 Then
                Width = otlp.Width - 100
            End If

            otlp.ColumnStyles(tmpdata(2)).Width = Width
        End If
        If (tmpdata(1) > -1) Then

            For i As Integer = 0 To tmpdata(1) - 1

                Height -= otlp.RowStyles(i).Height
            Next
            otlp.RowStyles(tmpdata(1)).SizeType = SizeType.Absolute

            If Height < 10 Then
                Height = 10
            End If

            If Height > otlp.Height - 100 Then
                Height = otlp.Height - 100
            End If

            otlp.RowStyles(tmpdata(1)).Height = Height
        End If
    End If
End Sub

Public Sub tlp_MouseLeave(sender As Object, e As System.EventArgs)
    Dim otlp As TableLayoutPanel = DirectCast(sender, TableLayoutPanel)
    otlp.Parent.Cursor = Cursors.Default
End Sub

Public Sub tlp_MouseUp(sender As Object, e As System.Windows.Forms.MouseEventArgs)
    If e.Button = System.Windows.Forms.MouseButtons.Left Then
        Dim otlp As TableLayoutPanel = DirectCast(sender, TableLayoutPanel)
        Dim tmpdata As Integer() = otlpdic.Item(otlp.Tag)
        tmpdata(0) = 0
        otlp.Parent.Cursor = Cursors.Default
    End If
End Sub
End Module

A: I modified this a little bit, the original code was not lining up with the borders. I also wanted my columns to auto size by default when the application loads. I used tableLayoutPanel1.GetRowHeights() and tableLayoutPanel1.GetColumnWidths() which I found from https://stackoverflow.com/a/51993386/13729116 which Jazimov explained that this is hidden from Intellisense because it is not suppose to work with controls that span columns. I tested this and it does work with a weird bit that you can move the column hidden by the spanned control in the padding areas around the control. I am sure you could work around this if you wanted to.
 private void tableLayoutPanel1_MouseMove(object sender, MouseEventArgs e)
    {
        if (!resizing)
        {
            float width = 0;
            float height = 0;
            int[] rowHeights = tableLayoutPanel1.GetRowHeights();
            int[] colWidths = tableLayoutPanel1.GetColumnWidths();
            //for rows
            for (int i = 0; i < rowHeights.Count(); i++)
            {
                height += rowHeights[i];
                if (e.Y > height - 3 && e.Y < height + 3)
                {
                    rowindex = i;
                    tableLayoutPanel1.Cursor = Cursors.HSplit;
                    break;
                }
                else
                {
                    rowindex = -1;
                    tableLayoutPanel1.Cursor = Cursors.Default;
                }
            }
            //for columns
            for (int i = 0; i < colWidths.Count(); i++)
            {
                width += colWidths[i];
                if (e.X > width - 3 && e.X < width + 3)
                {
                    colindex = i;
                    if (rowindex > -1)
                        tableLayoutPanel1.Cursor = Cursors.Cross;
                    else
                        tableLayoutPanel1.Cursor = Cursors.VSplit;
                    break;
                }
                else
                {
                    colindex = -1;
                    if (rowindex == -1)
                        tableLayoutPanel1.Cursor = Cursors.Default;
                }
            }
        }
        if (resizing && (colindex > -1 || rowindex > -1))
        {
            float width = e.X;
            float height = e.Y;
            int[] rowHeights = tableLayoutPanel1.GetRowHeights();
            int[] colWidths = tableLayoutPanel1.GetColumnWidths();
            if (colindex > -1)
            {
                for (int i = 0; i < colindex; i++)
                {
                    width -= colWidths[i];
                }
                columnStyles[colindex].SizeType = SizeType.Absolute;
                columnStyles[colindex].Width = width;
            }
            if (rowindex > -1)
            {
                for (int i = 0; i < rowindex; i++)
                {
                    height -= rowHeights[i];
                }

                rowStyles[rowindex].SizeType = SizeType.Absolute;
                rowStyles[rowindex].Height = height;
            }
        }
    }


text:
Q: Creating Jira issues through Python script: trouble with component, duedate and fixversion field EDITED I'm currently writing a simple Python script which reads data from an Excel sheet and creates Jira tasks based on that data. I've got the Excel data-reading part working and the Jira task creation mostly as well, but am struggling with a couple of fields.
The following fields are mandatory for our Jira tasks:

*

*project

*issue type

*summary

*parent watcher (custom field)

*priority

*external bid (custom field)

*fix version/s

*component

*due date

I got the first six working with the following line of code in Python:
issue = jira.create_issue(project=pro, summary=sum, issuetype=type, customfield_13700 = { "name": parent }, priority = {'name': priority}, customfield_12501 = external_bid )

However, I am not sure how to fill in the other parameters of the jira.create_issue function for the fix versions/s, component and due date bid fields.
I've tried many different things:
For the fix version field:
issue = jira.create_issue(fixversion=fixversion )
issue = jira.create_issue(fixversion = {'name': fixversion})
issue = jira.create_issue(fixversion = {'value': fixversion})

which all results in the following error:
"errors":{"fixversion":"Field 'fixversion' cannot be set. It is not on the appropriate screen, or unknown."}}
For the component field:
issue = jira.create_issue(component = component )
issue = jira.create_issue(component = {'name': component} )
issue = jira.create_issue(fixversion = {'value': component})

Which again all results in the following error:
errors":{"component":"Field 'component' cannot be set. It is not on the appropriate screen, or unknown."}}
For the due date:
issue = jira.create_issue(duedate = duedate)
issue = jira.create_issue(duedate = {'name': duedate} )
issue = jira.create_issue(duedate = {'value': duedate} )

Which gives the following error:
TypeError: Object of type 'datetime' is not JSON serializable
At this point, I've tried a host of different things and looked a bunch of stuff up, most of which point to this page:
JIRA projects may contain many different issue types. Some issue screens have different requirements for fields in a new issue. This information is available through the 'createmeta' method. Further examples are available here.
Which isn't really helpful for me. Anybody have any idea how to best proceed from here?

A: The error TypeError: Object of type 'datetime' is not JSON serializable is issued when you try to serialize a datetime object into a JSON object.
The duedate value you use is a datetime object. Whenever you try to dump a dictionary containing a datetime object to a JSON object, you will encounter this error. Example below:
import datetime
test = {}
test['date'] = datetime.datetime.now()
import json
json.dumps(test)

To avoid this error, convert your datetime object to an object that is accepted by the Javascript Object Notation (JSON) standard. Such as a string.
test['date'] = str(datetime.datetime.now())
json.dumps(test)

Do note that direct conversion from your datetime object might not fit the JIRA format for accepted dates. Use the correct format when casting to string (give the datetime documentation a look)


text:
Q: Is it possible to run unit test classes in a certain order on visual studio? I have a number of classes which contain unit tests for example
 Test class 1(){
   test method 1
   test method 2
   }
Test class 2(){
   test method 1
   test method 2
   }
 Test class 3(){
   test method 1
   test method 2
   }

I want to be able to run class 1 first then class 2 then class 3 etc. However when I run all tests it's completely random so class 1 method 1 runs first then class 3 method 2. This causes my tests to fail.
I tried using ordered test class in visual studio however I get the following message- MStest V2 based tests cannot be used in an ordered test.
Is there a way for me to order classes so they run in the ordered I need instead of randomly running a test within a class?


text:
Q: Use of "algorithm = 'port' and control lower limit in nlsList I am using the data from How can I get the coefficients from nlsList into a dataframe?
library(nlme)
dat<-read.table(text="time gluc starch solka
1 6.32 7.51 1.95
2 20.11 25.49 6.43
3 36.03 47.53 10.39
6 107.52 166.31 27.01
12 259.28 305.19 113.72
24 283.40 342.56 251.14
48 297.55 353.66 314.22", header = TRUE)
long <- tidyr::pivot_longer(dat, -1, values_to = "y")
long$name <- factor(long$name)
st0 <- list(Max = 200, k = 0.1, Lag = 0.5)
nlsList(y ~ (time > Lag) * Max * (1-exp(-k * (time - Lag))) | name,
 long,
algorithm="port",
lower=c(k = 0.1, Max =-Inf, Lag = -Inf),
start = st0)

What I need differently is to not have k lower than 0.1, so I used algorithm="port", lower=c(k = 0.1, Max =-Inf, Lag = -Inf) as in nls() Prevent a nls-fit from falling below zero.  It doesn't look like nlsList is taking those 2 commands.
Error in nlsList(y ~ (time > Lag) * Max * (1-exp(-k * (time - Lag))) | name,  :
  unused arguments (algorithm = "port", lower=c(k = 0.1, Max =-Inf, Lag = -Inf))

How do I work around this issue?

A: It looks like nlsList doesn't take those additional arguments — as far as I can tell that's just an oversight on the part of the authors. (This might be worth a feature/enhancement request on the R bug tracker ...)
In the meantime you can use tidyverse as here to split-apply-modify-combine ...
Note that the values in the lower argument must be specified in the same order as start: names are silently ignored ... (Submitted to the R bug tracker here ...).
models <- (long
    |> group_by(name)
    |> nest()
    |> mutate(fit = map(data,
                        nls,
                        form = y ~ (time > Lag) * Max * (1-exp(-k * (time - Lag))),
                        algorithm="port",
                        lower=c(Max =-Inf, k = 0.1,  Lag = -Inf),
                        start = st0))
)

coefs <- (models
    |> mutate(cc = map(fit, broom::tidy))
    |> select(name, cc)
    |> unnest(cols = cc)
)

  name   term  estimate std.error statistic    p.value
  <fct>  <chr>    <dbl>     <dbl>     <dbl>      <dbl>
1 gluc   Max    300.      16.7        18.0  0.0000561
2 gluc   k        0.162    0.0382      4.23 0.0134
3 gluc   Lag      2.43     0.515       4.71 0.00924
4 starch Max    357.      11.8        30.1  0.00000722
5 starch k        0.161    0.0211      7.64 0.00157
6 starch Lag      1.80     0.234       7.70 0.00153
7 solka  Max    317.      20.0        15.8  0.0000929
8 solka  k        0.1      0.0321      3.12 0.0356
9 solka  Lag      7.61     1.53        4.98 0.00758

A: One suggestion is to use nlsLMList in package nlraa. It will use the algorithm in 'minpack.lm::nlsLM'. Notice that I reorder the names in the lower argument. (You need the latest version from github for this to work).
library(nlme)
library(nlraa)
dat<-read.table(text="time gluc starch solka
1 6.32 7.51 1.95
2 20.11 25.49 6.43
3 36.03 47.53 10.39
6 107.52 166.31 27.01
12 259.28 305.19 113.72
24 283.40 342.56 251.14
48 297.55 353.66 314.22", header = TRUE)
long <- tidyr::pivot_longer(dat, -1, values_to = "y")
long$name <- factor(long$name)
st0 <- list(Max = 200, k = 0.1, Lag = 0.5)
nlsLMList(y ~ (time > Lag) * Max * (1-exp(-k * (time - Lag))) | name,
 long,
algorithm="port",
lower=c(Max =-Inf, k = 0.1, Lag = -Inf),
start = st0)

However, a better approach is to fit an NLME
longG <- groupedData(y ~ time | name, data = long)

fitL <- nlsLMList(y ~ (time > Lag) * Max * (1-exp(-k * (time - Lag))),
                  longG,
                  start = st0)

fm <- nlme(fitL, random = pdDiag(Lag + Max + k ~ 1))

plot(augPred(fm, level = 0:1))

coef(fm)

If a fixed-effects only model is preferred then this might work
fgm <- gnls(y ~ (time > Lag) * Max * (1-exp(-k * (time - Lag))),
            data = long,
            params = Lag + Max + k ~ name,
            start = c(Lag = 2.4, 0, 0, Max = 336, 0, 0, k = 0.12, 0, 0))


text:
Q: Excel 2016 VBA - Creating Dashboard with greater efficiency I'm currently in the process of building a dashboard in excel 2016 using VBA and macros. It basically involves selecting buttons on a single sheet to show/hide different chart elements whose data sources will be linked to another sheet. Its going well so far, but I've run into efficiency issues. The first issue has to do with grouping objects and the second to do with repetition of vba code.
1) Is there any way to cross-group shape objects? Right now it seems that I have to create duplicates for objects which will not be visible, and for which each parent group of objects will be hidden. Unfortunately, I cannot find a way for Excel to cross group. So if I want a group A and B and a group A and C, I can only apparently have one group (A&B or A&C, but not both). This forces me to duplicate objects so I have one pair for A&B and another for A&C. The problem is this can get quite tedious and a nightmare in organizing my objects properly when I get several dashboard buttons and sub-sections.
2) Could anyone advise on how I can make the following code more efficient so there is no repeating of code? It basically highlights a group of shapes that must show and hide with respect to what button is pressed. But right now, I have to write all the groups that must stay visible and hidden. Below is a sample of the code. Please see the True and False arguments below to get an idea of what the issue is:
   Sub Pic_1_SA_click()
   ActiveSheet.Shapes("Group 23").Visible = True
   ActiveSheet.Shapes("Group 71").Visible = False
   ActiveSheet.Shapes("Group 19").Visible = False
   ActiveSheet.Shapes("Group 20").Visible = False
   End Sub

   Sub Pic_1_SB_click()
   ActiveSheet.Shapes("Group 23").Visible = False
   ActiveSheet.Shapes("Group 71").Visible = True
   ActiveSheet.Shapes("Group 19").Visible = False
   ActiveSheet.Shapes("Group 20").Visible = False
   End Sub

   Sub Pic_2_SA_click()
   ActiveSheet.Shapes("Group 23").Visible = False
   ActiveSheet.Shapes("Group 71").Visible = False
   ActiveSheet.Shapes("Group 19").Visible = True
   ActiveSheet.Shapes("Group 20").Visible = False
   End Sub

   Sub Pic_2_SB_click()
   ActiveSheet.Shapes("Group 23").Visible = False
   ActiveSheet.Shapes("Group 71").Visible = False
   ActiveSheet.Shapes("Group 19").Visible = False
   ActiveSheet.Shapes("Group 20").Visible = True
   End Sub

Any guidance on these two issues will be greatly appreciated. Thanks!

A: I simple code refactoring should do it
Sub Pic_SA_click(ByVal sShapeName As String)
    If (sShapeName = vbNullString) Then Exit Sub

    Dim oShp As Shape, s As Shape
    Set oShp = ActiveSheet.Shapes(sShapeName)
    If (oShp Is Nothing) Then Exit Sub
    oShp.Visible = True
    With ActiveSheet
        For Each s In .Shapes
            If (s.Name <> oShp.Name) Then
                s.Visible = False
            End If
        Next s
    End With
End Sub

Sub Pic_1_SA_click()
    call Pic_SA_click("Group 23")
end sub

Sub Pic_1_SB_click()
    call Pic_SA_click("Group 71")
End Sub

Sub Pic_2_SA_click()
    call Pic_SA_click("Group 19")
End Sub

Sub Pic_2_SB_click()
    call Pic_SA_click("Group 20")
End Sub


text:
Q: Is there disk based file system with dedicated memory caching for Linux? We have two (or more sometimes) applications battling for the OS page cache. In particular ElasticSearch is very dependent on the OS page cache. To the point that cache misses can make or break performance in low latency cases. ES is the only low latency application on the nodes so it needs the OS page cache. Since the entire index can't fit into RAM warmers are used to prime the cache but after a few hours, those caches are trashed by other applications.
Some thoughts and ideas I've had:

*

*RAMFS (but the index doesn't fit into RAM so no go there)

*TMPFS (but it's not persisted through reboots and uses swap)

*Caching at the Lucene/ES level (simply doesn't seem to exist, OS page cache is their caching strategy)

*Dedicated hardware (this would be hard to justify since the machine have plenty of RAM and CPU, just need to make better use of it; plus we would need a lot of nodes).

*VMTouch with locking (no way to really detect when ES is going to merge new segments and need to unlock the old files and map the new)

*Full VM (performance cost and extra administration/management)

A dedicated file system that could carve out a predefined chunk of RAM for caching would be ideal. But I'm open to just about anything at this point short of buying dedicated nodes due to a design limitation in ES/Lucene.


text:
Q: How to change the text color which is in a different widget on switch with a flutter provider? How to change the text color which is in a different widget on switch with a flutter provider?
When switch is on change text color to red else change to green. Bu don't merge first and second widgets.
When clicked switch button change  other widget's text.
`
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';

void main() => runApp(const SwitchApp());

class SwitchApp extends StatelessWidget {
  const SwitchApp({super.key});

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(title: const Text('Switch Sample')),
        body: const Center(
          child: SwitchExample(),
        ),
      ),
    );
  }
}

class SwitchExample extends StatefulWidget {
  const SwitchExample({super.key});

  @override
  State<SwitchExample> createState() => _SwitchExampleState();
}

class _SwitchExampleState extends State<SwitchExample> {
  bool light = false;

  @override
  Widget build(BuildContext context) {
    return Column(
      children: [
        Switch(
          // This bool value toggles the switch.
          value: light,
          activeColor: Colors.red,
          onChanged: (bool value) {
            // This is called when the user toggles the switch.
            setState(() {
              light = value;
            });
          },
        ),
        MyText()
      ],
    );
  }
}

class MyText extends StatelessWidget {
  const MyText({super.key});

  @override
  Widget build(BuildContext context) {
    return const Text('Change my color',
        style: TextStyle(color: Colors.green));
  }
}

`

A: The easiest way would be to pass the color down into the constructor of MyText widget, since MyText widget is being built as a child of SwitchExample which is handling the switch state.
import 'package:provider/provider.dart';

void main() => runApp(const SwitchApp());

class SwitchApp extends StatelessWidget {
  const SwitchApp({super.key});

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(title: const Text('Switch Sample')),
        body: const Center(
          child: SwitchExample(),
        ),
      ),
    );
  }
}

class SwitchExample extends StatefulWidget {
  const SwitchExample({super.key});

  @override
  State<SwitchExample> createState() => _SwitchExampleState();
}

class _SwitchExampleState extends State<SwitchExample> {
  bool light = false;

  @override
  Widget build(BuildContext context) {
    return Column(
      children: [
        Switch(
          // This bool value toggles the switch.
          value: light,
          activeColor: Colors.red,
          onChanged: (bool value) {
            // This is called when the user toggles the switch.
            setState(() {
              light = value;
            });
          },
        ),
        MyText(light ? Colors.green : Colors.blue)
      ],
    );
  }
}

class MyText extends StatelessWidget {
  final Color color;
  const MyText(this.color, {super.key});

  @override
  Widget build(BuildContext context) {
    return Text('Change my color',
        style: TextStyle(color: color));
  }
}

But, if you wanted to use provider so that MyText could be a child widget anywhere below the provider widget in the tree you could use Provider with a ChangeNotifier:
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';

void main() => runApp(const SwitchApp());

class ColorModel extends ChangeNotifier {
  Color color = Colors.green;
  void setColor(Color color) {
    this.color = color;
    notifyListeners();
  }
}

class SwitchApp extends StatelessWidget {
  const SwitchApp({super.key});

  @override
  Widget build(BuildContext context) {
    return ChangeNotifierProvider<ColorModel>(
      create: (context) => ColorModel(),
      child: MaterialApp(
        home: Scaffold(
          appBar: AppBar(title: const Text('Switch Sample')),
          body: const Center(
            child: SwitchExample(),
          ),
        ),
      ),
    );
  }
}

class SwitchExample extends StatefulWidget {
  const SwitchExample({super.key});

  @override
  State<SwitchExample> createState() => _SwitchExampleState();
}

class _SwitchExampleState extends State<SwitchExample> {
  bool light = false;

  @override
  Widget build(BuildContext context) {
    return Column(
      children: [
        Switch(
          // This bool value toggles the switch.
          value: light,
          activeColor: Colors.red,
          onChanged: (bool value) {
            // This is called when the user toggles the switch.
            setState(() {
              light = value;
            });
            Provider.of<ColorModel>(context, listen: false)
                .setColor(value ? Colors.green : Colors.blue);
          },
        ),
        MyText()
      ],
    );
  }
}

class MyText extends StatelessWidget {
  const MyText({super.key});

  @override
  Widget build(BuildContext context) {
    return Consumer<ColorModel>(builder: (context, state, _) {
      return Text('Change my color', style: TextStyle(color: state.color));
    });
  }
}

Check out flutter's docs for more info: https://docs.flutter.dev/development/data-and-backend/state-mgmt/simple


text:
Q: Facebook not correctly pulling "og:image" Starting about a week ago, Facebook no longer correctly pulls my "og:image" unless I use the Facebook debug tool and click on "scape again" several times.
I receive the following error message :
The provided 'og:image' properties are not yet available because new images are processed asynchronously. To ensure shares of new URLs include an image, specify the dimensions using 'og:image:width' and 'og:image:height' tags.
My code has been working perfectly for over a year and I have made no modifications to it.
Here is my code :
<meta property="og:image" content="http://www.example.com/images/example.png" />
<meta property="og:image:width" content="220" />
<meta property="og:image:height" content="220" />
<meta property="og:type" content="article" />
<meta property="og:title" content="<Article Title>" />
<meta property="og:description" content="<Article Desc>" />
<meta property="og:url" content="<Article URL>" />
<meta property="og:see_also" content="<Article Alt URL>" />
<meta property="og:site_name" content="example.com" />
<meta property="og:locale" content="en_US" />

I've removed the real meta content, but I assure you all the meta tags are filled out correctly.
After hitting the "scape again" button a couple times, Facebook is finally able to pull the image.
There is 0.00 server load on my dedicated server so that's not the issue.
Any ideas?

A: It appears this was a Facebook issue, as everything magically started to work again without me making any changes.


text:
Q: Find limit $ \lim_{n \to \infty}\left(1-\frac{1}{n}\right)\left(1 - \frac{2}{n}\right) \dots \left(1 - \frac{ \lfloor xn \rfloor -1}{n}\right). $ Let $x >0$. Evaluate the limit:
$$
\lim_{n \to \infty}\left(1-\frac{1}{n}\right)\left(1 - \frac{2}{n}\right) \dots \left(1 - \frac{   \lfloor xn \rfloor -1}{n}\right).
$$
I am not sure how to show this since $(1-1/n)(1-2/n)$ seem to approach $1$ while $1-(\lfloor xn \rfloor-1)/n$ seems too approach $x$. Does the limit somewhat involve $e$ or even exist?

A: Hint:
Let $m:=\lfloor nx\rfloor$. The product is
$$\frac{(n-1)!}{(n-m)!n^{m-1}}.$$
By Stirling,
$$\sim\frac{\sqrt{n-1}\left(\dfrac{n-1}e\right)^{n-1}}{\sqrt{n-m}\left(\dfrac{n-m}e\right)^{n-m}n^{m-1}}
\\\sim\frac{\sqrt{n-1}\left(\dfrac{n-1}n\right)^{n-1}e^{m-1}}{\sqrt{n}\sqrt{1-x}(1-x)^{n-m}}
\\\sim\frac1{e^2\sqrt{1-x}}\left(\frac{e^x}{(1-x)^{1-x}}\right)^n.$$

A: *

*For $\ x=1\ $ the product is $\ \displaystyle\frac{(n-1)!}{n^{n-1}}= \frac{n!}{n^n}\ $. Now $\ \displaystyle\lim_{n\rightarrow\infty}\frac{(n!)^\frac{1}{n}}{n}=\frac{1}{e}\ $, so $\ \displaystyle\lim_{n\rightarrow\infty} \frac{n!}{n^n}=0\ $

*For $\ 1<x\ $, and sufficiently large $\ n\ $, $\ \lfloor xn\rfloor\ge n+1\ $ and the product will include the factor $\ \left(1-\frac{n+1-1}{n}\right)=0\ $. So in this case too, $\ \displaystyle \lim_{n\rightarrow\infty}\prod_{i=1}^{\lfloor xn\rfloor-1}\left(1-\frac{i}{n}\right)=0\ $.

*If $\ 0<x\le1\ $, let  $\ 0<\alpha<\frac{x}{2(1-x)}\ $ and $\ m\ $ be any positive integer greater than $\ \frac{
 \alpha x(1-x)}{x-2\alpha(1-x)}\ $. Then $\
   1<\frac{m(x-2\alpha(1-x))}{\alpha x(1-x)}=$$\left(\frac{m}{\alpha(1-x)}-\frac{2m}{x}\right)\ $. Thus the interval $\ \left(\frac{2m}{x}, \frac{m}{\alpha(1-x)}\right)\ $ must contain at least one integer. Therefore let $\ n\ $ be such an integer: $\ \frac{2m}{x}<n< \frac{m}{\alpha(1-x)}\ $.
Now for $\ i\ge m\ $, $\ 1-\frac{i}{n}\le$$1-\frac{m}{n}<1-\alpha(1-x)\ $, so
\begin{align}
\prod_{i=1}^{\lfloor nx\rfloor-1} \left(1-\frac{i}{n}\right)&\le\prod_{i=m}^{2m-1} \left(1-\frac{i}{n}\right)\\
&<(1-\alpha(1-x))^{m-1}\ .
\end{align}
Since $\ 0< 1-\alpha(1-x)<1\ $, and $\ m\ $ can be arbitrarily large, it follows that $\ \displaystyle \lim_{n\rightarrow\infty}\prod_{i=1}^{\lfloor xn\rfloor-1}\left(1-\frac{i}{n}\right)=0\ $ in this case also.


text:
Q: Evaluating Hard Limit (L'Hopital; modified CRRA Utility) I am trying to find
$\lim_{R \to 1} \frac{R^R x^{1-R}-1}{1-R}$, and the question explicitly states to use L'Hopital to find it. My current attempt is:
$\lim_{R \to 1} \frac{R^R x^{1-R}-1}{1-R} = \lim_{R \to 1} \frac{R^R(\ln R+1) x^{-R}(1-R)}{-1} = \lim_{R \to 1} \frac{R^R(\ln R+1) (R-1)}{x^R}$ (by L'Hopital)
I feel like I should now take logs, which yields:
$\lim_{R \to 1} \ln\left(\frac{R^R(\ln R+1) (R-1)}{x^R}\right) = \lim_{R \to 1} R \ln (R) + \ln(\ln R + 1) + \ln (R-1) - R \ln x = -\infty$.
So: $\lim_{R \to 1} \exp(-\infty) = 0$.
Is this correct? If not, where am I going wrong? (Hints appreciated maybe even more than answers!)
Thanks a million,
Best wishes,
Leon

A: Just
$$
\lim_{R\to 1}\frac{R^R(\ln R+1)(R-1)}{x^R}=\lim_{R\to 1}\frac{1^1(\ln 1+1)(1-1)}{x^1}=0.
$$
(your idea is correct but needless)


text:
Q: Understanding a macro for drawing (irregular) circles I'm trying to understand the code in an answer regarding drawing closed paths so that I might be able to manipulate it further. Here is a small portion of it:
\documentclass[border=2pt]{standalone}
\usepackage{tikz}
\usetikzlibrary{intersections,calc}
\usetikzlibrary{decorations.pathreplacing,decorations.markings}

% decorating every segment of a path
% https://tex.stackexchange.com/a/69225
\tikzset{
  % style to apply some styles to each segment of a path
  on each segment/.style={
    decorate,
    decoration={
      show path construction,
      moveto code={},
      lineto code={
        \path [#1]
        (\tikzinputsegmentfirst) -- (\tikzinputsegmentlast);
      },
      curveto code={
        \path [#1] (\tikzinputsegmentfirst)
        .. controls
        (\tikzinputsegmentsupporta) and (\tikzinputsegmentsupportb)
        ..
        (\tikzinputsegmentlast);
      },
      closepath code={
        \path [#1]
        (\tikzinputsegmentfirst) -- (\tikzinputsegmentlast);
      },
    },
  },
  % style to add an arrow in the middle of a path
  mid arrow/.style={postaction={decorate,decoration={
        markings,
        mark=at position .5 with {\arrow[#1]{stealth}}
      }}},
}

\newcommand\irregularcircle[2]{% radius, irregularity
  \pgfextra {\pgfmathsetmacro\len{(#1)+rand*(#2)}}
  +(0:\len pt)
  \foreach \a in {10,20,...,350}{
    \pgfextra {\pgfmathsetmacro\len{(#1)+rand*(#2)}}
    -- +(\a:\len pt)
  } -- cycle
}

\begin{document}
\begin{tikzpicture}
  % Set the seed for the random function to a fixed value to get
  % the same picture at every run
  \pgfmathsetseed{12345}
  \coordinate (c) at (0,0);
  \draw[blue,rounded corners=1mm] (c) \irregularcircle{3cm}{1.5mm};
  \draw[red,rounded corners=1mm] (c) \irregularcircle{1cm}{1.5mm};

\end{tikzpicture}
\end{document}

I get stuck with understanding the following macro:
\newcommand\irregularcircle[2]{% radius, irregularity
  \pgfextra {\pgfmathsetmacro\len{(#1)+rand*(#2)}}
  +(0:\len pt)
  \foreach \a in {10,20,...,350}{
    \pgfextra {\pgfmathsetmacro\len{(#1)+rand*(#2)}}
    -- +(\a:\len pt)
  } -- cycle
}

This Tikz-pfg manual says that

... this operation (\pgfextra) should only be used by real experts and should only be used deep inside clever macros, not on normal paths.

Would anybody explain how each line in the definition of the macro \irregularcircle works?

A: The \irregularcircle macro assumes that the current point is the center of the irregular circle. The points calculated by the macro are relative to this center thanks to the notation +(...).
The \pgfextra macro (or operation) allows to interrupt momentarily the current path to evaluate any code (or, as said in pgfmanual, to "do some calculations or some other stuff").
In this particular case and with the current version of TikZ/pgf, the \pgfextra operation is not really necessary. I could have written the following macro:
\newcommand\irregularcircle[2]{% radius, irregularity
  +(0:{(#1)+rand*(#2)})
  \foreach \a in {10,20,...,350}{
    -- +(\a:{(#1)+rand*(#2)})
  } -- cycle
}

The braces {...} around a calculation included in a coordinate allows to use parenthesis in this calculation.
An even simpler version could be:
\newcommand\irregularcircle[2]{% radius, irregularity
  +(0:#1+rand*#2)
  \foreach \a in {10,20,...,350}{
    -- +(\a:#1+rand*#2)
  } -- cycle
}

But in this case, the values of the two parameters can no longer be any calculations but just simple values.


text:
Q: Interpreting a "Traceback (most recent call last):" error I realize this issue has been explained many times before so I understand if this is closed as a duplicate, but I have some more theoretic questions to ask that may justify this as a new question. I'm new to Python (and SO), so bear with me.
I'm trying to read in a .csv file that has 16 columns and 30,000ish rows, populated with values from 0 to 17. There are no empty cells. What I would like to do is iterate through each of the rows, doing entry-wise subtraction with the cells from each other row. Currently, I'm attempting to do this using a Pandas DataFrame. So my first question is: Should I be using a different data structure? I've read that DataFrame's are bad for iterating through rows.
Next, for the title question, I need help interpreting my error. Thusfar, I've only written code to try this subtraction on a small subset of the data. Here's my code:
import numpy as np
import pandas as pd

scrambles = pd.read_csv('scrambles.csv')
df = pd.DataFrame(scrambles)
#print(df)
columns = list(df)

for i in columns:
    print (df[i][0]-df[i][1])

This all works as anticipated. However, when I change the last piece of code to the following, I get an error:
for i in range(15):
    print (df[i][0]-df[i][1])

I'll post a transcript of the error below. The reason I'm trying to do it this way even though I have a working code is because when I write the full script, I'm iterating over a known amount of rows. For what it's worth, I'm doing this on Jupyter online.

KeyError                                  Traceback (most recent call last)
/srv/conda/envs/notebook/lib/python3.6/site-packages/pandas/core/indexes/base.py in get_loc(self, key, method, tolerance)
   2889             try:
-> 2890                 return self._engine.get_loc(key)
   2891             except KeyError:

pandas/_libs/index.pyx in pandas._libs.index.IndexEngine.get_loc()

pandas/_libs/index.pyx in pandas._libs.index.IndexEngine.get_loc()

pandas/_libs/hashtable_class_helper.pxi in pandas._libs.hashtable.PyObjectHashTable.get_item()

pandas/_libs/hashtable_class_helper.pxi in pandas._libs.hashtable.PyObjectHashTable.get_item()

KeyError: 0

During handling of the above exception, another exception occurred:

KeyError                                  Traceback (most recent call last)
<ipython-input-6-0faa876fbe56> in <module>
      1 for i in range(15):
----> 2     print (df[i][0]-df[i][1])

/srv/conda/envs/notebook/lib/python3.6/site-packages/pandas/core/frame.py in __getitem__(self, key)
   2973             if self.columns.nlevels > 1:
   2974                 return self._getitem_multilevel(key)
-> 2975             indexer = self.columns.get_loc(key)
   2976             if is_integer(indexer):
   2977                 indexer = [indexer]

/srv/conda/envs/notebook/lib/python3.6/site-packages/pandas/core/indexes/base.py in get_loc(self, key, method, tolerance)
   2890                 return self._engine.get_loc(key)
   2891             except KeyError:
-> 2892                 return self._engine.get_loc(self._maybe_cast_indexer(key))
   2893         indexer = self.get_indexer([key], method=method, tolerance=tolerance)
   2894         if indexer.ndim > 1 or indexer.size > 1:

pandas/_libs/index.pyx in pandas._libs.index.IndexEngine.get_loc()

pandas/_libs/index.pyx in pandas._libs.index.IndexEngine.get_loc()

pandas/_libs/hashtable_class_helper.pxi in pandas._libs.hashtable.PyObjectHashTable.get_item()

pandas/_libs/hashtable_class_helper.pxi in pandas._libs.hashtable.PyObjectHashTable.get_item()

KeyError: 0

A: I'll expand on my comment to answer the original question - interpreting the exception.

The cause for the error is because your dataframe most likely is not using integers for its column names, so the integers 0 through 15 will cause the KeyError you're seeing, which is the final line of both Exceptions: KeyError: 0

In the Traceback, Python is giving you additional context to the error that is happening.
When you make the attempt to access column 0 of your dataframe, the processing code reaches line 2890 of base.py in the function get_loc().
In that code, the KeyError that occurs is handled by the containing try/except. However, the handling call also raises a KeyError which is not handled (this call is also unfortunately not included in the Traceback). This is where the "During handling of the above exception, another exception occurred:" message comes in.
To illustrate using the code itself:
            ...
            try:
                return self._engine.get_loc(key) # <- KeyError raised here
            except KeyError:                     # <- Caught by except
                return self._engine.get_loc(self._maybe_cast_indexer(key)) # <- 2nd KeyError
            ...

Finally, as I said in the comment, the final line of the Traceback reveals the error:
KeyError: 0


text:
Q: Vaadin - How to open BrowserWindowOpener from a SINGLE BUTTON In the Vaadin example of how to print a dynamically generated PDF they have a two step approach, first you click on the OkButton and then the PrintButton. The problem is that their code to open the PDF relies on creating a new BrowserWindowOpener which then extends the Print button in the ClickListener for the OKButton. In other words they have:
okButton.addClickListener(new ClickListener()
 {
    @Override
    public void buttonClick(ClickEvent event)
    {
        // Dynamically generate PDF - this is greatly simplified.
        StreamResource pdfResource = new PdfStreamResource();
        BrowserWindowOpener opener = new BrowserWindowOpener(pdfResource);
        opener.extend(printButton);
    }
}

This is great because the Print button is now linked to BrowserWindowOpener and will immediately open the window/tab when you click on the PrintButton.
The problem I have is that I don't want an OkButton, I just want to have a PrintButton. In this case I can't add
printButton.addClickListener(new ClickListener()
 {
    @Override
    public void buttonClick(ClickEvent event)
    {
        // Dynamically generate PDF - this is greatly simplified.
        StreamResource pdfResource = new PdfStreamResource();
        BrowserWindowOpener opener = new BrowserWindowOpener(pdfResource);
        opener.extend(printButton);
    }
}

In the ClickListener FOR THE PrintButton because the first time you click it wont work. I then thought what if I had BrowserWindowOpener declared outside of the ClickListener, in the class that links the PrintButton and ClickListener, using something a dummy resource:
BrowserWindowOpener opener = new BrowserWindowOpener("");
opener.extend(printButton);
PrintClickListener printClickListener = new PrintClickListener(opener);
printButton.addClickListener(printClickListener);

And then pass the opener to the ClickListener so that I could do something like:
printButton.addClickListener(new ClickListener()
 {
    @Override
    public void buttonClick(ClickEvent event)
    {
        // Dynamically generate PDF - this is greatly simplified.
        StreamResource pdfResource = new PdfStreamResource();
        opener.setResource(pdfResource);
    }
}

However the issue here is that the first click generates a blank page.
My question is how can I get the example working where the dynamically generated PDF is pushed to the browser window with just a SINGLE BUTTON. All the examples for BrowserWindowOpener seem to always use two buttons. And the examples that declare it higher in the class hierarchy don't work for me, it's always an initial blank page.
Lastly, I would love to be able to do all this within the ClickListener, that is totally decoupled from everything else.

A: Get rid of BrowserWindowOpener and use UI.getPage().open() to view your pdf file.
getUI().getPage().open(resource, "_blank", false);

Notice that this method is deprecated.

As of Vaadin 7.0.0, the functionality for opening a Resource in a Page has been replaced with similar methods based on a String URL. This is because the usage of Resource is problematic with memory management and with security features in some browsers. Is is recommended to instead use Link for starting downloads.

Don't think it is possible to use BrowserWindowOpener in one button only without hacking in JavaScript.
EDIT:
I've achieved desired effect using BrowserWindowOpener. I've extended the class and added pdf generation every time when BrowserWindowOpenerState is requested. The thing is that I've searched for a method that is invoked after the click and before BrowserWindowOpener opens up new tab. The only method I could find is getState() - and only when the state of the component is dirty. I had to also add a flag in overriden getState method because:

*

*setResource method invoke getState() method too, so I had infinite loop

*to generate pdf only when its really needed
public class BrowserWindowOpenerWithBeforeClick extends BrowserWindowOpener
{

private boolean pdfGenerated = false;

public BrowserWindowOpenerWithBeforeClick(String url)
{
    super(url);
}

@Override
protected BrowserWindowOpenerState getState(boolean markAsDirty) {
    if(!pdfGenerated){
        StreamResource resource = ((RfgUI) UI.getCurrent()).getResource();
        pdfGenerated = true;
        this.setResource("url",resource);
    }
    return (BrowserWindowOpenerState) super.getState(markAsDirty);
}

public void setPdfGenerated(boolean generated){
    this.pdfGenerated = generated;
}
}

And pdf generation in your main UI class:
void pdfgeneration(final VerticalLayout layout)
{
    name.setValue("Slartibartfast");
    final Button ok = new Button("OK");
    ok.setId("ok-button");
    final BrowserWindowOpenerWithBeforeClick bwo = new BrowserWindowOpenerWithBeforeClick("");
    bwo.extend(ok);
    name.addValueChangeListener(new ValueChangeListener()
    {
        @Override
        public void valueChange(ValueChangeEvent event)
        {
            bwo.setPdfGenerated(false);
            bwo.markAsDirty();
        }
    });
    layout.addComponent(name);
    layout.addComponent(ok);
}

And getResource method:
public StreamResource getResource()
{
    StreamSource source = new MyPdfSource((String) name.getValue());
    String filename = new Random().nextInt() + "pdf_printing_example.pdf";
    StreamResource resource = new StreamResource(source, filename);
    resource.setMIMEType("application/pdf");
    resource.setCacheTime(0);
    resource.getStream().setParameter("Content-Disposition", "attachment; filename=" + filename);
    return resource;
}

Notice that I had to change the filename everytime I generate new pdf file to avoid caching problems.

A: This solution worked for me:

*

*Vaadin 8

*Dynamic StreamSource

Double solution; at the occurence, generate a link and start to download client side. Also work only generated link to click for download, or start download client side after event server side, or click button.
Vaadin 8 generate for dynamic stream resource this url:

http://localhost:8080/{warPath}/APP/connector/{uiID}/{componentID}/url/{fileName}

This snippet do: when click a button, a StreamSource was created, but the InputStream non generated at time. Then, a Link or Button component was created and attached to any component outside the click button listener. Also a BrowserWindowOpener was created and that extends Link or Button. A listener on the BrowserWindowOpener, when attached, generate the StreamSource dynamic link and open in new window (remember, in vaadin 8 the method Page.getCurrent().open(Resource, WindowName, openAsPopuo) is deprecated).
Finally, the strem (getStream()) was called only when the generated link is request.
    VerticalLayout vlay = new VerticalLayout();
    setCompositionRoot(vlay);

    Button butt = new Button("Click");
    vlay.addComponent(butt);
    butt.addClickListener(evt->{

        StreamSource ss = new StreamResource.StreamSource() {

            private static final long serialVersionUID = 1L;

            @Override
            public InputStream getStream() {

                return new ByteArrayInputStream("Qualsiasi byte array".getBytes());
            }
        };

        StreamResource sr = new StreamResource(ss,"testo.txt");
        sr.setMIMEType("application/octet-stream");
        sr.setCacheTime(1l);
        //Button downlButt = new Button("Download");
        Link lnk = new Link("Download",null);

        BrowserWindowOpener bwo = new BrowserWindowOpener(sr);
        //bwo.extend(downlButt);
        bwo.extend(lnk);

        bwo.addAttachListener(attevt->{
            String generatedURL = ApplicationConstants.APP_PATH+"/"+ConnectorResource.CONNECTOR_PATH+"/"+
                                  UI.getCurrent().getUIId()+"/"+attevt.getConnector().getConnectorId()+"/"+
                                  BrowserWindowOpenerState.locationResource+"/"+sr.getFilename();
            Page.getCurrent().open(generatedURL, "_blank");
        });

        vlay.addComponent(lnk);

    });


text:
Q: Passing an array name to a function, then populating it I would like to call a function that takes data and then populates an array I name in one of the function parameters. Example of what I'm looking for:
function readSaveFile(saveFileName, arrayName)
    if love.filesystem.exists(saveFileName) then
        arrayName = Tserial.unpack(love.filesystem.read(saveFileName))
    end
end

The issue is that instead of creating an array with the string under arrayName, it replaces the parameter with an array explicitly called "arrayName". Is there any way I could populate the array name specified instead?

A: You can always insert the data into given array (provided it is not nil). For example:
function readSaveFile(saveFile, arrayName)
  if love.filestystem.exists(saveFileName) then
    for k, v in pairs(love.filesystem.read(saveFileName)) do
      arrayName[k] = v
    end
  end
end


text:
Q: CodeIgniter dynamic hook I am using CI 3.0 to call a script in display_override hook that will replace tokens such as [[templatedata:head]] which will include all the scripts and CSS associated with a template's head section, thus it will inject the relevant < script > as < link > tags in the template, but since different templates may have different scripts, this needs to be dynamically determined at injection time. The source of the script is an array in a configuration file with the template name as the array key.
Is there a way that I can set a regular variable or session variable to hold that template name to be accessible by the hook script in order to call the right array sub section of scripts?

A: The problem was resolved by changing the hook that did the script and link replacement to run post_controller as opposed to pre_controller, and set a static variable in the main index.php file, which then gets updated where the template is called, and thus do the necessary replacement for the template.


text:
Q: better way to write "in Apple's iMac's common MacOS" I was looking at a better way to write the following while emphasizing Apple in the beginning. But it seems like too many possessive s usages.
What could be a substitute?

"The software that runs on Apple's iMac's commonly used MacOS"

A: The best way to reduce the number of apostrophe S's in your sentence is to 1) attach the definite article to Apple, and 2) dispense with the apostrophe S that follows it:

The software that runs on the Apple iMac's commonly-used MacOS [is....]


text:
Q: How to avoid sending notifications to 'Miscellaneous' channel at Firebase? I want to show my notifications in a channel that I create so I can fully customize my channel with my preferences. I'm using a Firebase function to send notifications (messages) from user to user:
const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp(functions.config().firebase);

exports.pushNotification = functions.firestore.document('/devices/{tokenId}/notifications/{notificationId}')
    .onWrite((change, context) => {
        console.log('Push notification event triggered');

        const tokenId = context.params.tokenId;
        const document = change.after.exists ? change.after.data() : null;

        if (document == null) {
            return console.log('A notification has been deleted from database');
        }

        const payload = {
            notification: {
                title: document.username,
                body: document.message,
                sound: "default"
            },
            data: {
                sender: document.sender
            }
        };
        const options = {
            priority: "high",
            timeToLive: 60 * 60 * 24 //24 hours
        };

        return admin.messaging().sendToDevice(tokenId, payload, options).then(result => {
            console.log('A notification sent to device with tokenId: ', tokenId);
        });
    });

I have implemented my FirebaseMessagingService service:
@Override
public void onMessageReceived(@NonNull RemoteMessage remoteMessage) {
    showNotification(remoteMessage);
}

private void showNotification(RemoteMessage remoteMessage) {
    NotificationManagerCompat notificationManager = NotificationManagerCompat.from(this);
    RemoteMessage.Notification remoteNotification = remoteMessage.getNotification();
    if (remoteNotification == null) return;
    String title = remoteNotification.getTitle();
    String message = remoteNotification.getBody();

    Notification notification;
    Notification.Builder builder = android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O ?
            new Notification.Builder(this, CH_MESSAGE) : new Notification.Builder(this);

    notification = builder
            .setContentTitle(title)
            .setContentText(message)
            .setCategory(CATEGORY_MESSAGE)
            .build();

    notificationManager.notify(0, notification);
}

And created my own notification channel at my Application class:
@Override
public void onCreate() {
    super.onCreate();
    createNotificationChannels();
}

private void createNotificationChannels() {
    NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
    if (notificationManager == null) return;

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
        NotificationChannel notificationChannel = new NotificationChannel(CH_MESSAGE,
                getString(R.string.messages), NotificationManager.IMPORTANCE_HIGH);

        notificationChannel.setDescription(getString(R.string.message_channel_description));

        notificationManager.createNotificationChannel(notificationChannel);
    }
}

I can successfully send notifications, but notifications are going to Miscellaneous channel.

I tried to remove the channel by using its channel ID with notificationManager.deleteNotificationChannel("fcm_fallback_notification_channel");, but it still recreates the channel and sends the notification there. How can I remove Miscellaneous channel permanently and handle my notifications with my own channels?

A: I have found the problem I am facing, my message payload contains both notification and data fields. According to this documentation my messages were not calling onMessageReceived method when app is in background. Now I'm using only data payload which calls the method when app is at both background and foreground.
const payload = {
    data: {
        sender: document.sender,
        username: document.username,
        message: document.message
    }
};

And in my onMessageReceived method:
Map<String, String> remoteMap = remoteMessage.getData();
String senderUid = remoteMap.get("sender");
String senderUsername = remoteMap.get("username");
String message = remoteMap.get("message");

Notification.Builder builder = android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O ?
        new Notification.Builder(this, CH_MESSAGE) : new Notification.Builder(this);

Notification notification = builder
        .setContentTitle(senderUsername)
        .setContentText(message)
        .setSmallIcon(R.drawable.ic_notif_message)
        .build();

notificationManager.notify(0, notification);


text:
Q: Electric generator Is there a way to power a single light bulb using a generator, and then with the same power source light 10 light bulbs? So basically, can I use say 5V of input to light 10 bulbs, and then use the same input to light a single bulb without blowing it? Assuming all bulbs are the same and at least 2V.

A:
Is there a way to power a single light bulb using a generator, and then with the same power source light 10 light bulbs?

My house is powered from the Irish national grid. The power comes from generators. The voltage is maintained closely to 230 V.
I can switch all the lights off, switch one, two or all of them on. The voltage remains at 230 V. If I switch on a large load (cooker or water heater) the voltage will droop a little due to the resistance of the cable between my local transformer and my house but it's only a couple of percent.

So basically, can I use say 5V of input to light 10 bulbs, and then use the same input to light a single bulb without blowing it?

*

*You need to make sure the bulbs are rated for 5 V.

*You need to make sure that the total current drawn does not exceed the current capacity of the generator or power supply.

Assuming all bulbs are the same and at least 2V.

Bulb voltage must match the supply voltage unless you want to series connect them. You mentioned 5 V supply so you would need to connect 3 x 2 V bulbs in series to make a 6 V string. You could then connect multiple 6 V strings in parallel.

A: You can perform both the jobs with the same power source. The only thing that you have to keep in mind is that:
1. The voltage across all the bulbs should be the same (use a parallel connection for this).
2. The current rating for each bulb should not be exceeded otherwise the bulb may blow-up. For this, you can go for a Zener diode (in reverse breakdown region).
If there is something which needs to be kept in mind other than this in your case, just comment and let me know.


text:
Q: Errors running Coldfusion 9 under Liferay 5.2 to serve portlets So this all began in trying to get Coldfusion9 portlets to run under Liferay, just like examples that I've seen running JBOSS:
http://help.adobe.com/en_US/ColdFusion/9.0/Developing/WSC00E3E9C-DC24-4488-930D-AEED19172CC5.html
I followed those steps, but my application server would be TomCat 5.5 (bundled w Liferay 5.2.3).
I wanted to create a portlet (just a hello world one to start with) from coldfusion.
Installation of cfusion went well, I create the WAR file, and tossed it into the Liferay 'hot depoly' directory, it was copied, and integrated without error into the Liferay install.
I followed the steps from the JBOSS example, and restarted the Liferay server (after copying the .cfc file into the proper location.
After I started Liferay however I got this error during startup:
21:04:33,648 INFO  [PluginPackageUtil:1153] Reloading repositories
21:06:06,510 INFO  [PortletHotDeployListener:227] Registering portlets for cfusion
javax.portlet.PortletException: javax.servlet.ServletException: ClassloaderHelper not initialized properly. Call ClassloaderHelper.init
(ServletContext) before using this class
        at coldfusion.portlet.ColdFusionPortlet.invokeCFC(ColdFusionPortlet.java:123)
        at coldfusion.portlet.ColdFusionPortlet.init(ColdFusionPortlet.java:67)
        at com.liferay.portlet.InvokerPortletImpl.init(InvokerPortletImpl.java:250)
        at com.liferay.portlet.PortletInstanceFactoryImpl.init(PortletInstanceFactoryImpl.java:245)
        at com.liferay.portlet.PortletInstanceFactoryImpl.create(PortletInstanceFactoryImpl.java:135)
        at com.liferay.portlet.PortletInstanceFactoryUtil.create(PortletInstanceFactoryUtil.java:47)
        at com.liferay.portal.deploy.hot.PortletHotDeployListener.initPortlet(PortletHotDeployListener.java:660)
        at com.liferay.portal.deploy.hot.PortletHotDeployListener.doInvokeDeploy(PortletHotDeployListener.java:250)
        at com.liferay.portal.deploy.hot.PortletHotDeployListener.invokeDeploy(PortletHotDeployListener.java:127)
        at com.liferay.portal.kernel.deploy.hot.HotDeployUtil._doFireDeployEvent(HotDeployUtil.java:108)
        at com.liferay.portal.kernel.deploy.hot.HotDeployUtil._fireDeployEvent(HotDeployUtil.java:153)
        at com.liferay.portal.kernel.deploy.hot.HotDeployUtil.fireDeployEvent(HotDeployUtil.java:43)
        at com.liferay.portal.kernel.servlet.PortletContextListener.portalInit(PortletContextListener.java:113)
        at com.liferay.portal.kernel.util.PortalInitableUtil.init(PortalInitableUtil.java:48)
        at com.liferay.portal.kernel.servlet.PortletContextListener.contextInitialized(PortletContextListener.java:109)
        at org.apache.catalina.core.StandardContext.listenerStart(StandardContext.java:3764)
        at org.apache.catalina.core.StandardContext.start(StandardContext.java:4216)
        at org.apache.catalina.core.ContainerBase.addChildInternal(ContainerBase.java:760)
        at org.apache.catalina.core.ContainerBase.addChild(ContainerBase.java:740)
        at org.apache.catalina.core.StandardHost.addChild(StandardHost.java:544)
        at org.apache.catalina.startup.HostConfig.deployDirectory(HostConfig.java:927)
        at org.apache.catalina.startup.HostConfig.deployDirectories(HostConfig.java:890)
        at org.apache.catalina.startup.HostConfig.deployApps(HostConfig.java:492)
        at org.apache.catalina.startup.HostConfig.start(HostConfig.java:1150)
        at org.apache.catalina.startup.HostConfig.lifecycleEvent(HostConfig.java:311)
        at org.apache.catalina.util.LifecycleSupport.fireLifecycleEvent(LifecycleSupport.java:120)
        at org.apache.catalina.core.ContainerBase.start(ContainerBase.java:1022)
        at org.apache.catalina.core.StandardHost.start(StandardHost.java:736)
        at org.apache.catalina.core.ContainerBase.start(ContainerBase.java:1014)
        at org.apache.catalina.core.StandardEngine.start(StandardEngine.java:443)
        at org.apache.catalina.core.StandardService.start(StandardService.java:448)
        at org.apache.catalina.core.StandardServer.start(StandardServer.java:700)
        at org.apache.catalina.startup.Catalina.start(Catalina.java:552)
        at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
        at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
        at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
        at java.lang.reflect.Method.invoke(Method.java:585)
        at org.apache.catalina.startup.Bootstrap.start(Bootstrap.java:295)
        at org.apache.catalina.startup.Bootstrap.main(Bootstrap.java:433)
Caused by: javax.servlet.ServletException: ClassloaderHelper not initialized properly. Call ClassloaderHelper.init(ServletContext) befo
re using this class
        at coldfusion.bootstrap.ClassloaderHelper.testInit(ClassloaderHelper.java:73)
        at coldfusion.bootstrap.ClassloaderHelper.getClassLoader(ClassloaderHelper.java:178)
        at coldfusion.portlet.ColdFusionPortlet.invokeCFC(ColdFusionPortlet.java:120)
        ... 38 more
21:06:07,135 INFO  [PortletHotDeployListener:346] 1 portlet for cfusion is available for use
11/16 21:06:07 INFO License Service: Flex 1.5 CF Edition enabled
11/16 21:06:07 INFO Starting Flex 1.5 CF Edition
11/16 21:06:08 Information [main] - C:\chicago\liferay-portal-tomcat-5.5-5.2.3\tomcat-5.5.27\temp\0-cfusion\WEB-INF\cfusion\logs\server
.log initialized
11/16 21:06:08 Information [main] - Starting logging...
11/16 21:06:08 Information [main] - Starting license...
11/16 21:06:09 Information [main] - Invalid ColdFusion 9 license.

Now, just for sh*ts and giggles I tried setting up a portlet on Liferay (the portlet showed up! yay!).  However only the title of the portlet would show up, the body was an error message:
The requested resource (/cfusion/ColdFusionPortlet/invoke) is not available
Now I can't seem to find a solution for this...
I've googled, and looked through quite a few documents, and none mention this type of error.  Of course Liferay.com community is quiet, no coldfusion talk on the forums there. So I figured I would check with everyone at SO.
Anyone? Thoughts?

A: As I have had 0 feedback on my question, I have decided to update it myself on what I have found.
If you need to get this setup running get the JBOSS/TOMCAT version of Liferay, as Coldfusion 9 was intended to run under JBOSS (serve portlets that way).
I also posted this question on Liferay.com, here is the link reference to it, I had one user update me which helped me solve the portlet issue, and using JBOSS got me the last step of the way.
Liferay.com Reference:
http://www.liferay.com/web/guest/community/forums/-/message_boards/message/4369312#_19_message_4287472
Liferay.com JBOSS bundle download:
http://www.liferay.com/web/guest/downloads/portal
Hope that helps someone in the future if they decide to go the Coldfusion 9 + Liferay route. Enjoy!


text:
Q: Cypress - calendar change month, until specific month is found I have a calendar. This calendar shows one month per time. Here it is: https://react-dates.github.io/react-dates/?path=/story/drp-calendar-props--single-month
My calendar automatically shows a date 3 years old. In this case November 2019.
I want to test April 2020.
I need the calendar to click the next arrows, until cy.contains('April 2020').
I wrote the following:
cy.get('.CalendarMonth').then($calendarPopover => {
  if ($calendarPopover.text().includes('February 2020')) {
    cy.contains('February 2020')
  } else {
    cy.get('.calendar-arrow-right')
      .click()
      .then(el => {
        if (!$calendarPopover.text().includes('February 2020')) {
          el.click()
        }
      })
  }
})

But it stops after the first month change.
How can I make it continue until the IF condition will be met?
Thank you

A: This is an example test using the Storybook demo page you mentioned.
It starts with the current month and doesn't have the classes you are using, but you will be able to apply the principle from this working example.
There is an <iframe> on the page set up by Storybook, so for this test Cypress needs to go inside that. I used cypress-iframe to do so.
import 'cypress-iframe'

it('moves calendar month back three years', () => {

  cy.visit('https://react-dates.github.io/react-dates/?path=/story/drp-calendar-props--single-month');

  // move inside Storybook iframe
  cy.iframe().within(() => {

    const monthSelector = '[aria-label="Calendar"] [data-visible="true"] strong'
    const backSelector = '[aria-label^="Move backward"]'

    cy.get(monthSelector).should('contain', 'November 2022')

    for (let index = 0; index < 36; index++) {             // want 3 years of clicks

      cy.get(monthSelector).invoke('text')
        .then(previous => {
          cy.get(backSelector).click()
          cy.wait(100, {log:false})
          cy.get(monthSelector).should('not.have.text', previous)
        })
    }
    cy.get(monthSelector).should('contain', 'November 2019')
  })
})

Note
Checking the month text has changed should be enough to wait for each transition, but in practice I found the test to be flaky with that check alone.
Adding a cy.wait(100) solved the flakiness. There could be something else to check instead, but without diving in to source code it's difficult to see what it is. The wait is pragmatic in this scenario to get the test working.


text:
Q: NHibernate object references an unsaved transient instance save the transient instance before flushing I am trying to save a complex object which has many referenced elements inside and it works perfectly most of the time.
However in some cases we are getting the below exception,

object references an unsaved transient instance - save the transient instance before flushing or set cascade action for the property to something that would make it autosave. Type: Namespace.Core.Client.ClientDetails, Entity: Namespace.Core.Client.ClientDetails

The problem is, there are around 12 ClientDetails elements inside my complex object which we are trying to save.Is there a way to identify which object instance caused this issue?
through NHibernate logging or some other way?
My code sample used for save as below,
_repository.Save<SuperParent>(obj);
_repository.Flush();

Please note when i set the Nhibernate show_sql to true i am able to see all the queries properly generated, but when the flush is called, the exception is thrown.
Please help to resolve the issue.

A: If you read carefully:

...he transient instance before flushing or set cascade action for the property to something that would make it autosave

So, maybe you can add Cascade to the Reference, like this:
References(x => x.ClientDetails).Cascade.All().Column("ClientDetailsId")
                  .Not.Nullable();  //Or nullable, this depends on your schedule

A: The exception means that there is an unsaved instance of ClientDetails referenced by this object. You have to either save it manually before saving the parent
session.Save(Parent.SomeDetail);

or set Cascade.SaveOrUpdate on the reference-mappings in the parent mapping.

A: Edit your mapping to cascade all changes.If you have a Client Class that have many ClientDetails , your xml mapping would be like this
In Client.hbm.xml file you should have :
<set name = "ClientDetails" table = "`ClientDetail`" cascade = "all-delete-orphan" inverse="true">
         <key column = "ClientId"/>
         <one-to-many class = "ClientDetail"/>
</set>

In ClientDetail.hbm.xml file you should have :
<many-to-one name = "Client" class = "Client" column = "ClientId " />

A: This error also happens when you have a complex object that includes children that are reference data (think ClientType class).
If the child has a version element in it's mapping file that maps to an int column in your database, the version number for an existing row should never be set to 0.  Nhibernate interprets this as an object to be inserted on a cascade update and will fail as it's attempting to insert a row that already exists.