text:
Q: Highlight duplicate value in a comma based string If I have values in cell c3= 2,4,6,8,12,14,18,23,35,78,101,38,30,205,2,101
In This two values are duplicate which is { 2,101 }
I want notification as and when enter any value twice, three-time , forth time, etc in that cell i should come to know which value is repeated. Duplicate values can be shown in adjacent cell D3,

A: This does not meet your request of trapping duplicates while typing. However to process a comma-separated string (once entered) consider the following user defined function:
Public Function duplist(s As String) As String
    Dim s2 As String, arr
    Dim kount As Long, i As Long, j As Long
    arr = Split(s, ",")

    For i = 0 To UBound(arr)
        kount = 0
        v = arr(i)
        For j = 0 To i
            If v = arr(j) Then kount = kount + 1
        Next j
        If kount = 2 Then s2 = s2 & "," & v
    Next i
    duplist = Mid(s2, 2)
End Function

A: Try this
Sub Test_CheckDups_UDF()
With Range("A1")
    .Value = "2,4,6,8,12,14,18,23,35,78,101,38,30,205,2,101"
    .Offset(, 1).Value = CheckDups(.Value)
End With
End Sub

Function CheckDups(s As String) As String
Dim a, dic As Object, i As Long

Set dic = CreateObject("scripting.dictionary")
a = Split(s, ",")

For i = LBound(a) To UBound(a)
    If dic.Exists(a(i)) = True Then CheckDups = CheckDups & IIf(CheckDups = Empty, "", ",") & a(i) Else dic.Add a(i), 1
Next i
End Function

Here's a code that will highlight the duplicates within the same cell. Tweak it so as to suit your needs
Sub Highlight_Duplicates_Within_Cell()
Dim s, sp, k, c As Range, t As String, f As Boolean, n As Long

For Each c In Range("C3:C13")
    c.Font.Color = vbBlack

    With CreateObject("Scripting.Dictionary")
        .CompareMode = vbTextCompare
        sp = Split(c.Value, ",")
        For Each s In sp
            If Not .Exists(s) Then .Add s, 1 Else .Item(s) = .Item(s) + 1
        Next s

        For Each k In .Keys
            t = "," & k & ","
            f = False
            n = InStr(1, "," & c.Value & ",", t, vbTextCompare)
            Do While n And .Item(k) > 1
                If f Then
                    c.Characters(n, Len(t) - 2).Font.Color = vbRed
                End If
                n = InStr(n + Len(k), "," & c.Value & ",", t, vbTextCompare)
                f = True
            Loop
        Next k
    End With
Next c
End Sub

Try this version too using Regex
Sub Highlight_Duplicates2()
Dim mtch As Object, mtch2 As Object, m As Object, mm As Object, c As Range, txt As String, i As Long

For Each c In Range("C3:C13")
    With CreateObject("VBScript.RegExp")
        .Global = True
        txt = c.Value
        .Pattern = " *(\w+)"
        Set mtch = .Execute(txt)

        For Each m In mtch
            .Pattern = "\b" & m.submatches(0) & "\b"
            Set mtch2 = .Execute(txt)

            If mtch2.Count > 1 Then
                For i = 1 To .Execute(txt).Count - 1
                    Set mm = mtch2(i)
                    With c.Characters(mm.firstindex + 1, mm.length).Font
                        .Color = vbRed: .Bold = True
                    End With
                    Mid$(txt, mm.firstindex + 1, mm.length) = Space(mm.length)
                Next i
            End If
        Next m
    End With
Next c
End Sub


text:
Q: What's the correct term for when a small problem becomes a big problem? What's the correct term for when a small problem becomes a big problem?  An example would be what happens to Larry David on "Curb Your Enthusiasm"...

A: Perhaps escalation would cover it. This can describe many things, such as an argument, become more serious:

to increase in extent, volume, number, amount, intensity, or scope
a little war threatens to escalate into a huge ugly one

Merriam-Webster

A: I'd rather suggest the word Intensify.
Intensify (Verb)

to become greater, more serious, or more extreme, or to make something do this

When industrial restructuring accelerated in the 1980s, labor-management relations problems intensified.

A: Get out of hand is an idiomatic expression that may be of help here:

if a problem/situation get out of hand they become difficult or impossible to control.

*

*The student teacher saw that the class was getting completely out of hand, so he asked for help.

(The Free Dictionary)

redpajama_set_name: RedPajamaStackExchange


text:
Q: Support Landscape and Portrait using StoryBoard in iOS Interface Builder I am developed an application which supports both Portrait and Landscape orientation with the GPOrientationKit. I followed following link to do all the pages of the app to support both the orientations.
http://logisian.blogspot.in/
I did that app with XIB or NIB file. Now, I am currently working on an app with the storyboard. I don't know how to do the app which support both the orientations with the storyboard. GPOrientationKit worked well for XIB files. But I am struggling with storyboard.I need the functionality like GPOrientationKit with the storyboard.  Please help me to do that.
Thanks in Advance.

A: Just add two subview to your mainView of your controller such as portraitView and landscape View, and toggle between those to as and when your orientation changes..I had something like this
In your viewWillAppear method add this
-(void)viewDidAppear:(BOOL)animated{

        if(UIDeviceOrientationIsPortrait(self.interfaceOrientation))
    {

//Keep LAndscape View Hidden
    self.portraitVIew.frame=self.view.frame;
    [self.view addSubview:self.portraitVIew];
    }else{

//Keep portrait View Hidden

    self.landscapeView.frame=self.view.frame;
    [self.view addSubview:self.landscapeView];
    }
    self.view.autoresizesSubviews = YES;

     }
    [[NSNotificationCenter defaultCenter]
     addObserver:self
     selector:@selector(deviceOrientationDidChangeNotification:)
     name:UIDeviceOrientationDidChangeNotification
     object:nil];

}

and then implement the method deviceOrientationDidChangeNotification such as
- (void)deviceOrientationDidChangeNotification:(NSNotification*)note
{

        UIDeviceOrientation orientation = [[UIDevice currentDevice] orientation];
        if(UIDeviceOrientationIsLandscape(self.interfaceOrientation))
        {
//Keep portrait View Hidden

            NSLog(@"YUP THIS IS LANDSCAPE");
            self.landscapeView.hidden=NO;
            self.landscapeView.frame=self.view.frame;
            [self.portraitVIew removeFromSuperview];
            ///self.landscapeView.frame=CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height);

            [self.view addSubview:self.landscapeView];
        }else {
//Keep LAndscape View Hidden

            self.landscapeView.hidden=YES;
            self.portraitVIew.frame=self.view.frame;
            NSLog(@"Portrait");

            [self.view addSubview:self.portraitVIew];
        }
}

A: you click to project>select target > General you set the device Orientation.


text:
Q: Angular re-initiate Class I have an API service in angular that I would like to reload when backend data is upadted (graphQL API addresses). More specifically, in the code below, I would like for the OnCreateReportListener to refresh as the API.graphql function will have new routes (that are contained in the API import.

import { Injectable } from "@angular/core";
import API, { graphqlOperation, GraphQLResult } from "@aws-amplify/api-graphql";
import { Observable } from "zen-observable-ts";

export class APIService {

      async CreateReport(
          input: CreateReportInput,
          condition?: ModelReportConditionInput
          ): Promise<CreateReportMutation> {
          const statement = `mutation CreateReport($input: CreateReportInput!, $condition:
          ModelReportConditionInput) {
              createReport(input: $input, condition: $condition) {
                __typename
                id
                report
                user
                client
                timeStamp
              }
            }`;
          const gqlAPIServiceArguments: any = {
            input
          };
          if (condition) {
            gqlAPIServiceArguments.condition = condition;
          }
          const response = (await API.graphql(
            graphqlOperation(statement, gqlAPIServiceArguments)
          )) as any;
          return <CreateReportMutation>response.data.createReport;
        }

         OnCreateReportListener: Observable<
          SubscriptionResponse<OnCreateReportSubscription>
        > = API.graphql(
          graphqlOperation(
            `subscription onCreateReport {
              onCreateReport {
                __typename
                id
                report
                user
                client
                timeStamp
              }
            }`
          )
        ) as Observable<SubscriptionResponse<OnCreateReportSubscription>>;

}


text:
Q: MongoDB, java.lang.NoSuchFieldError Program is failing on line 1
    MongoClient mongoClient = new MongoClient("localhost", 27017);

With
java.lang.NoSuchFieldError: ACKNOWLEDGED
    at com.mongodb.MongoClientOptions$Builder.<init>(MongoClientOptions.java:54)
    at com.mongodb.MongoClient.<init>(MongoClient.java:126)
    at com.mongodb.MongoClient.<init>(MongoClient.java:115)

While mongo is,
Tue Nov 27 15:40:13 [initandlisten] waiting for connections on port 27017

What am i doing wrong please?

A: I suspect that you have multiple versions of the mongo-java-driver jar in your classpath.  Try running with -verbose:class to see where the WriteConcern class is being loaded from.

A: use this line.
Mongo mongo= new Mongo("localhost", 27017);

A: I had the same problem and I realized that I have two java libraries for reading Mongo DB. When I removed one of them (com.mongodb-x-x.jar), the error disappeared.


text:
Q: How can I fix a C program that never stops scanning user input for a string? I'm creating a "mad lib" program that scans in four strings input by the user to fill in the "blanks" on the mad lib template (replacing part of the underscores used as placeholders -- just for the length of the word and not replacing the whole thing). This is what I'm trying to replicate.
I have a function with printf and scanf statements that takes in the first 3 strings without issue, but after the 4th string is input, the program just keeps scanning, even after pressing "enter," until I end it. I want to be able to print the completed sentence directly under the 4th printf/scanf line after calling the function in main, but I don't know how to get the rest of the code to execute. Here is a screenshot of the problem I'm having.
Does anyone know what the issue is and how I can fix it?
Here is my code so far (I know I haven't completed the rest of the function after the printf/scanf statements, and I'm probably not doing this in the most efficient way to begin with, so any other tips would be greatly appreciated, but the program runs and I'd like to focus on this issue before I continue):
#include <stdio.h>
#include <string.h>

void create_madlib(char *pmls);

int main() {

    char mls[] = "Star Wars is a ___________ _________ of _________ versus evil in a __________ far far away." ;

    create_madlib(mls);
    printf("%s\n", mls);

    return 0;
}

void create_madlib(char *mls)
{
    char pmls[9][18];

    char word1[15];
    //i15 - i25

    char word2[15];
    //i27 - i35

    char word3[15];
    //i40 - i48

    char word4[15];
    //i67 - i76

    printf("Please enter word 1: ");
    scanf("%s", word1);
    printf("Please enter word 2: ");
    scanf("%s", word2);
    printf("Please enter word 3: ");
    scanf("%s", word3);
    printf("Please enter word 4: ");
    scanf("%s", word4);

    for (int i = 0; i < 90; i++)
    {
        for (int a = 0; a < strlen(word1); a++)
        {
            while (i >= 15 && i <= 25)
            {
                mls[i] = word1[a];
            }
        }
        for (int b = 0; b < strlen(word2); b++)
        {
            while (i >= 27 && i <= 35)
            {
                mls[i] = word2[b];
            }
            break;
        }
    }
}

Thank you


text:
Q: Execute a callback after child component changes its state I have a class component which renders a child component which cannot be modified (comes from a library).
This component has an internal state in which there is a data I want to retrieve and do something with it as soon at it is changed.
I tried using a callback on ref like this:

onRefChange = el => {
  console.log('el state', el.state);
  // prints the initial state of the child component, with the value still to be changed (it changes a little after initialization)
}

<Carousel
  ref={(el) => {
    this.onRefChange(el);
    return this.Carousel = el;
  }}
  //other stuff
/>

Of course I can access the state by reading this.Carousel.state later but I'm trying to do an operation immediately after this data changes, with a callback.
Also apart from changing the behaviour of the child component, the parent component should remain a class componente, so no hooks like useEffect() can be used.
Is it a dead-end or is there a way to achieve this?


text:
Q: facing error : - TypeError: Cannot read property '_id' of null my post timeline system seems failing with this error the code for the same is :
1.
const router = require("express").Router();

const postModel = require("../models/post");
const userModel = require("../models/user");

// catch timeline posts
router.get("/timeline/all", async (req, res) => {
    try {
      const currentUser = await userModel.findById(req.body.userId);
      const userPosts = await postModel.find({ userId: currentUser._id });
      const friendPosts = await Promise.all(
        currentUser.followings.map((friendId) => {
          return Post.find({ userId: friendId });
        })
      );
      res.json(userPosts.concat(...friendPosts))
    } catch (err) {
        console.log(err)
    }
  });

module.exports = router;

and for my schema here :
1 USER SCHEMA
const mongoose = require("mongoose");

const userSchema = new mongoose.Schema({
    username: {
        type: String,
        require: true,
        min: 3,
        max: 20,
        unique: true
    },

    useremail: {
        type: String,
        required: true,
        max: 50,
        unique: true,
    },

    password: {
        type: String,
        required: true,
        min: 6
    },

    profilePicture: {
        type: String,
        default: ""
    },

    coverPicture: {
        type: String,
        default: ""
    },

    followers: {
        type: Array,
        default: []
    },

    following: {
        type: Array,
        default: []
    },

    isAdmin: {
        type: Boolean,
        default: false,
    },

    description: {
        type: String,
        max: 50
    },

    from: {
        type: String,
        max: 50
    },

    relationship: {
        type: Number,
        enum: [1, 2, 3]
    },
},
    { timestamps: true }
);

// exporting for use in other files
module.exports = mongoose.model("user", userSchema);

2 POST SCHEMA
const mongoose = require("mongoose");

const postSchema = new mongoose.Schema({

    userId: {
        type: String,
        required: true
    },

    description: {
        type: String,
        max: 500
    },

    img: {
        type: String
    },

    likes: {
        type: Array,
        default: []
    },
},
    { timestamps: true }
);

// exporting for use in other files
module.exports = mongoose.model("post", postSchema);

I know noone would like such a post and moreover this is spoonfeed,
its just me being a stupid who cant figure out something silly,
Thanks for your help and time really appreciate u ppls effort
once again sry for such a post but thanks for reviewing


text:
Q: Multiple line tool tip in wpf using c# I want to use multiple line tool tip in wpf
but thie is look like
line 1
    line2

but i want to display this miltiple line tool tip in the given format
line 1
line 2

A: Here is a way to do it with a Label as an example:
<Label>
    <Label.ToolTip>
        <StackPanel>
             <TextBlock>Line 1</TextBlock>
             <TextBlock>Line 2</TextBlock>
        </StackPanel>
    </Label.ToolTip>
</Label>

A: That worked for me and I don't see anything similar in the answers:
<[ParentControl].ToolTip>
    <TextBlock>
        Some text here.
        <LineBreak/>
        And more text in a new line.
    </TextBlock>
</[ParentControl].ToolTip>

A: I personally prefer to embed
(new line) into the strings I'll be using as tooltips.
ex. Tooltip="line 1
line 2"
I can then load the strings from resource files and conveniently apply them if I wish without having to go through any additional formatting.


text:
Q: Only disable Embeded PDF print and download options I have a pdf viewer in place and want to disable the download and print options. I know, we can disable the toolbar by the appending the same after the pdf url "path-to-pdf/xyz.pdf#toolbar=0". But this disables all other options such as page numbers, bookmarks.
How to only disable download and print icons. Didn't succeed trying to do by hiding the icons in jquery.
Below is the code snippet for the PDF viewer:

        <object data="{{ file_path }}" type="application/pdf">

                This browser does not support PDF view. Please contact the administrator.

        </object>

A:
How to only disable download and print icons?

You can't. When displaying a PDF using the object or embed tag, you are relying on the native browser or OS level PDF viewer to display the PDF. While Adobe Reader does accept parameters in the URL to control some aspects of the UI, not all viewers respect those parameters and you can no longer expect Adobe Reader to be the viewer that gets used. If you want to control the viewing experience, you'll need to control the viewer. Look at something like pdf.js or one of its equivalents.


text:
Q: /etc/resolv.conf on CentOS7 doesn't seem to honor options # uname -a
Linux myserver 3.10.0-1062.18.1.el7.x86_64 #1 SMP Tue Mar 17 23:49:17 UTC 2020 x86_64 x86_64 x86_64 GNU/Linux

# cat /etc/redhat-release
CentOS Linux release 7.7.1908 (Core)

# cat /etc/resolv.conf

# Generated by NetworkManager
options rotate
options timeout:3
options attempts:6
nameserver one.xxx.xxx.xxx
nameserver two.xxx.xxx.xxx
nameserver thr.xxx.xxx.xxx

# nslookup some.url.ihave
Server:     one.xxx.xxx.xxx
Address:    one.xxx.xxx.xxx#53

** server can't find some.url.ihave: NXDOMAIN

Why does it not try the other two nameservers for DNS lookup that I have entered in resolv.conf ?

A:
** server can't find some.url.ihave: NXDOMAIN

nslookup stops because it has received an answer to its query.  It stops asking once it has an answer, obviously.  That answer was that the domain does not exist.
If you don't want that to be the case, do not list in resolv.conf the IP address of a DNS server that thinks that that domain does not exist.  Otherwise you'll end up sometimes, perhaps always, getting that as the answer.  (There is no fixed universal rule about what order these things are tried in.  Two programs from the same stable, nslookup and the BIND DNS client library from ISC, use different orders; and there are other DNS clients from other people with other behaviours still.)
Further reading

*

*Jonathan de Boyne Pollard (2003). Your fallback proxy DNS servers must provide the same view of the DNS namespace as your principal one..  Frequently Given Answers.

*Jonathan de Boyne Pollard (2003). Why the results from nslookup are different to the operation of ping.  Frequently Given Answers.

*Jonathan de Boyne Pollard (2001). nslookup is a badly flawed tool. Don't use it..  Frequently Given Answers.


text:
Q: Created a subdomain and now my POST data doesn't work My php site with its main domain name works fine. I decided to add a subdomain (mobile) to support mobile devices. I created the subdomain and copied all my php files into the new folder 'mobile'.
I can access the new subdomain using the mobile.mainDomain.com and the files seem to work from a static point of view (no 404's, no error 500 server errors, etc.). All the files are there and display. However, when I try to login (on the index.php page) I enter in my user name but when index.php calls the index_dispatcher.php file to process the login, my index.php form field frm_user_name is empty.
For debugging I put the line
print $frm_user_name;

in the index_dispatcher.php file and it prints nothing (empty).
So there must be something else that needs to be set for the POST data to work with a subdomain?


text:
Q: In Samuel R. Delany's Dhalgren, what catastrophe befell the city of Bellona? Sci-fi grandmaster Samuel R. Delany's Dhalgren became his most commercially successful endeavor.
First published in January, 1975 by Bantam, Dhalgren has sometimes been described as an experimental novel, or a circular novel.
Penguin Random House details this book:

Bellona is a city at the dead center of the United States. Something has happened there … The population has fled. Madmen and criminals wander the streets. Strange portents appear in the cloud-covered sky. Into this disaster zone comes a young man—poet, lover, and adventurer—known only as the Kid.
From https://www.penguinrandomhouse.com/books/38904/dhalgren-by-samuel-r-delany-foreword-by-william-gibson/

"Something has happened there —…"
The disaster, which has included riots and fire, lack of electricity and infrastructure, still intermittently seems to going on in the Kid's present. (or is it? Or will it?) The disaster may have caused something very weird to happen with time, because sometimes burned buildings are back the way they were and sometimes they aren't.
What was it? Looking for either authoritative answer or revelations from the novel regarding how or why the disaster happens to Bellona.

A: I've read Dhalgren three times, cover to cover, without interspersing any other fiction each time (that is, I wasn't reading any other novel while reading Dhalgren), most recently in the 1990s.  I still don't understand it (linguistically clearer than James Joyce, but no simpler, would be my description, and the "clearer" is probably dependent on Delany being American, as am I, where Joyce was unabashedly Irish), but I'm confident the nature of the disaster was very carefully not defined internal to the story.
Various parts of Bellona had electricity, and didn't; had water service, and didn't; had food left in stores, and didn't, were burning or had burnt -- and weren't.  It seems very much as if there are (only) a few paragraphs missing between the last words and the first where the story might wrap around.
As one comment noted, at certain points it seemed as though effects preceded their causes, as if Kid were living backward (not in the meaning of speaking backward or getting younger, but as if what happens today depends heavily on what will happen tomorrow).
Given the situation, especially with time, it seems as if the disaster was both past and present, but at no point was it defined clearly except in terms of its effects: mass flight from the city, and complete disruption of the workings of civilization.

A: As William Gibson famously observed (in his forward to the Vintage Edition), Dhalgren "is not there to be finally understood. I believe its 'riddle' was never meant to be 'solved.'" With that said, I do have my own, unprovable theory on how Bellona is constructed: The entire city is in a closed time loop. (Closed time loops are a favorite of Delany's --he explored one, less successfully, in Empire Star. Compare also Diana Wynne Jones' Tale of Time City.) Events there are cyclical, they happen over and over again --not necessarily identically, and not necessarily with the same cast.  Thus, the events that are in the recent past at the beginning of the book are in the near future at the end of the book. As part of this, the city is self-renewing. It burns, but is not consumed. It is looted, but never exhausted.
The narrator/main-character is one of the archetypal inhabitants of the city. He enters at one point of time, and exits at another, but yet in some sense he, or some other version of him, has always been there. Through the diary entries it is suggested that he experiences the complete loop, and that he is present in the city both before his arrival, and after his exit. Due to his amnesia, it's unknowable how many times he has actually lived through the cycle, or if all the versions of him we follow throughout the book are actually the same person.
So what then is the disaster that has created this time anomaly? I think that too can be discerned by a careful reading between the lines. What can create a singularity capable of warping time in on itself? The crashing together of two celestial objects. In this case, the sun and the moon of Bellona are June, a young sheltered white girl, and George, a crude, powerfully built Black man privately and publicly lusted over by half the population of the city. The two of them circle each other at a distance throughout most of the city's cycle, but the consummation of their sexual attraction is the actual disaster that causes the city to detach from the rest of America. Their pairing appears, at a superficial level, to be the exact scenario used by white supremacists to justify the oppression of Black people, the brutal rape of a young innocent white girl by a brutal, powerful, bestial Black man. However, Delany subverts this by suggesting the young girl has cold-bloodedly murdered her own brother to prevent him from revealing her hidden desires, that the Black man is a quiet humanitarian, and that their coming together is a bit of mutually consensual play-acting for their own sexual pleasures --the white supremacist's worst nightmare. It's the contradictory nature of these two scenarios, and the way they go straight to the heart of the American psyche, and its sustained racial dysfunctions, that tears Bellona right out of time and space. (It's a uniquely Delanian conceit that the disaster is sociological and psychological, not physical.) Subsequently a white sniper shoots at Black protestors, riots ensue and buildings are burned, and the city descends into a repeating set of scenarios that feel as familiar and as inescapably current in the year 2021 as they must have back in 1975. Maybe Delany was onto something.


text:
Q: Is there anyway to assign a default position for the circular button in an ionic range slider? I have an ionic slider, in which I get the value from and assign another scope variable:
<input type="range" min="0" value="0" max="100" step="25" name="lineProgress" ng-model="progress" ng-change=lineProgress(progress)>
When the value of progress changes, it assigns certain text to another $scope variable that is shown under it.
Without sliding the button, however, its default position seems to be in the middle
The $scope variable is not assigned at this point, but I would like the button to be all the way to the left.  I thought by assigning, value = 0, it would do that. Anyone know how to make this work?

A: try assigning value to $scope.progess=0 and remove value filed from input.
<input type="range" min="0" max="100" step="25" name="lineProgress" ng-model="progress" ng-change=lineProgress(progress)>

in controller:
$scope.progress="0";

may be this could help you.it worked for me.

A: Alternatively, you could use ng-init in your HTML to set progress to 0 (i.e. ng-init="progress = 0"). It should accomplish the same thing.


text:
Q: Getting "Method executeQuery cannot be used for update" for NOT update queries I try to retrieve information about databases and tables of a DB2 System.
The kotlin application successfully connects with the database but when I execute a query (see code below) I always get the error message "Method executeQuery cannot be used for update" even though I do not execute an update query.
    connection = DriverManager.getConnection(config.connectionString)
    val statement: Statement = connection!!.createStatement()
    val query = "DISPLAY DATABASE"
    //val query = "LIST TABLES"
    val resultSet: ResultSet = statement.executeQuery(query)

Error message:
com.ibm.db2.jcc.am.SqlException: [jcc][10103][10941][4.29.24] Method executeQuery cannot be used for update. ERRORCODE=-4476, SQLSTATE=null"

Can someone tell me what I'm doing wrong?


text:
Q: Ruby Teaspoon Unknown default suite I run in my rails project
rake teaspoon

and error output is
Teaspoon::UnknownSuite: Unknown suite "default\"

can any one explain me what this problem means?

A: There is an issue with teaspoon on Windows in version 0.8.0.
https://github.com/modeset/teaspoon/issues/271
In lib/teaspoon/drivers/phantomjs_driver.rb you need to change url.shellescape to url


text:
Q: Bootstrap 3 CSS: Thin white gap above navbar only on mobile in production I'm using Django + Bootstrap 3 + Heroku. In production, there's a thin white line above the navbar on the mobile viewport. It's there on all pages. On my local machine, it isn't there. I've done sanity checks to make sure they're in sync.
Production: http://screencast.com/t/3Ukg9Lgu34N
Local: http://screencast.com/t/dNVQVtuWgW
I was able to fix it locally by adding .collapse { border: 0 !important; margin-top: 0 !important; }, but for some reason, it doesn't translate to production.
See below for full navbar css. You can view the production site here: http://goo.gl/mwXfRl
Any idea what's going on?
navbar-static-top.css:
.navbar {
    border: 0 !important;
    margin-top: 0 !important;
}

.navbar-static-top {
    margin-bottom: 0px !important;
    background-color: #11C356; /*#649072; #fafafa;*/
    border-color: #11C356;/* #649072; #fafafa; */
    font-family: 'Source Sans Pro', sans-serif;
    font-weight: 200;
    font-size: 1.2em;
}

.navbar-default .navbar-nav>li>a:hover {
    color: #e4e4e4; /*#0aa647;*/ /*#D5DED9*/
}

.navbar-default .navbar-toggle {
    border-color: transparent !important;
}

.navbar-toggle {
    background-color: #11C356;
    padding-top: 0px;
    padding-bottom: 0px;
    margin-top: 0px;
    margin-bottom: 0px;
    margin-right: 0px;
}

.navbar-toggle:hover {
    background-color: #11C356;
    padding-top: 0px;
    padding-bottom: 0px;
    margin-top: 0px;
    margin-bottom: 0px;
    margin-right: 0px;
}

.navbar-default .navbar-nav>li>a {
    color: #f2f2f2; /*#11C356;*/
    line-height: 30px;
}

.navbar-default .navbar-brand {
    /*font-family: 'Josefin Sans', sans-serif;*/
    font-family: 'Bitter', serif;
    color: #f2f2f2; /*#11C356;*/
    font-size: 28px;
}

.navbar-default .navbar-brand:hover {
    color: #e4e4e4; /*#0aa647; *//*#D5DED9*/
}

.navbar-default .navbar-nav>.open>a,
.navbar-default .navbar-nav>.open>a:focus,
.navbar-default .navbar-nav>.open>a:hover {
    color: #0aa647;
    background-color: #fafafa; /*#11C356*/
}

.navbar-right .dropdown-menu {
    min-width: 0;
}

.dropdown-menu>li>a {
    padding-top: 7px;
    padding-right: 15px;
    padding-bottom: 7px;
    padding-left: 15px;
}

.navbar-collapse.collapse {
display: block!important;
}

.navbar-nav>li, .navbar-nav {
float: left !important;
}

.navbar-nav.navbar-right:last-child {
margin-right: -15px !important;
}

.navbar-right {
float: right!important;
}

.collapse {
    border: 0 !important;
    border-color: #11C356;
    margin-top: 0 !important;
}

A: Just add margin-top: -1px to navbar-static-top like this:
.navbar-static-top {
    margin-bottom: 0px !important;
    margin-top: -1px;
    background-color: #11C356;
    border-color: #11C356;
    /* border-style: solid; */
    font-family: 'Source Sans Pro', sans-serif;
    font-weight: 200;
    font-size: 1.2em;
}

A: Try this
.navbar {
position: relative;
min-height: 50px;
margin-bottom: 20px;
/* border: 1px solid transparent; */ or border:none;
}
.navbar-static-top {
margin-bottom: 0px !important;
background-color: #11C356;
/* border-color: #11C356; */
font-family: 'Source Sans Pro', sans-serif;
font-weight: 200;
font-size: 1.2em;
}

A: I finally fixed this with the following css at the template level:
.navbar-default .navbar-collapse {
    border-style: hidden !important;

It's more of a patch, but it did the trick.


text:
Q: What does Shadowform do to other classes' Hero powers? When Shadowform is cast as a Priest, the Hero Ability changes its name from "Lesser Heal" to "Mind Spike" and does 2 damage or "Mind Shatter" doing 3 damage (depending on how often you cast Shadowform) instead of healing for 2. The icon also changes from a hand held upwards with dominant yellow and orange tones into a hand held towards the player with a bright spot in the center and dominant purple and black tones.
What happens to your Hero Power if you cast Shadowform as a non-Priest? According to the card's text, it also deals 2/3 damage, without anything else specified. So does its name and icon change to the same as the Priest's variant or is there a different name and icon for each class?
Oh, and before anyone asks: Lorewalker Cho.

A: The name and icon remain the same. A warrior for example, loses his Armor Up! and gains Mind Spike just as a priest would. The same applies (if I recall correctly) to an aditional Shadowform. You gain the Mind Shatter ability with the corresponding icon. Just as it says on the card.
Edit: This shows an example of a Warlock gaining Mind Spike by using Lorewalker Cho.


text:
Q: How to publish & Subscribe at server side using SimpleMessagingBroker in Spring I am trying to publish from one class and subscribe from another class using simple messaging broker. Below is the sample code of what i am trying to do.
@Scheduled(fixedDelay=1500) public void Hello() {
    this.messagingTemplate.convertAndSend("/topic/hello",new String("Hello"));
}

@MessageMapping("/topic/hello") public void HelloWorld(String greet) {
    System.out.println(greet);
}


text:
Q: How to set an array in a class in C++ I'd like to store an array of numbers in a private variable of a class using a setter method, but am unsure how to.
The program requires a default constructor, and the other essential methods but for simplicity i've only provided the default constructor.
class numberList{
public:
    numberList()
    {
        numberStore = new int[8];
    } // default constructor

    void setter() // not sure what goes here
    {
        //not sure what goes here
    }

private:
    int* numberStore;
};

int main()
{
    numberList list1;
    list1.setter(1,2,3,4,5,6,7)
}

I'd like for the list1.setter() to take all the values to be put into the array. I think memcpy() could be used here, but am unsure.
I understand there's a concept of operator overloading, but am unsure how utilise this. Any help would be appreciated :-)
EDIT: the assignment requires me not to use standard libraries unfortunately :-(

A: From your comment that you can't use the STL the solution is to use raw C-pointer arithemtics.
To your setter function you can give a int* pointer and the number of elements:
void setter(int* arr, int n) {
    for(int i = 0; i < n; i++)
        numberStore[i] = arr[i]
}

Then you can call your setter function in main() like this:
int main() {
    numberList list1;
    int arr[] = {1,2,3,4,5,6,7};
    list1.setter(arr, 7);
}

A: #include "pch.h"
#include <iostream>
#include <string>

int* my_array = new int[10];

void setter(int* arr, int n)
{
    memcpy(&my_array[0], &arr[0], n * sizeof(int));
}

int main()
{
    int* arry = new int[10];
    for (int i=0; i< 10; i++)
    {
        arry[i] = i;
    }

    setter(arry, 10);

    for (int i = 0; i < 10; i++)
    {
        std::cout<<(std::to_string(my_array[i]));
    }
}


text:
Q: Adding a label to a JComboBox and JTextField Hi I am having trouble adding labels to my combo box and textfield.It compiles fine but only shows the boxes but without labels.
import javax.swing. *;
import java.awt.event. *;
import java.awt.FlowLayout;

public class AreaFrame2
{

   public static void main(String[]args)
   {

      //Create array containing shapes
      String[] shapes ={"(no shape selected)","Circle","Equilateral Triangle","Square"};

      //Use combobox to create drop down menu
      JComboBox comboBox=new JComboBox(shapes);
      JPanel panel1 = new JPanel();
      JLabel label1 = new JLabel("Select shape:");
      panel1.add(label1);
      comboBox.add(panel1);
      JButton button = new JButton("GO");
      JTextField text = new JTextField(20);

      //Create a JFrame that will be use to put JComboBox into it
      JFrame frame=new JFrame("Area Calculator Window");
      frame.setLayout(new FlowLayout()); //set layout
      frame.add(comboBox);//add combobox to JFrame
      text.setLocation(100,100);
      frame.add(text);
      frame.add(button);

      //set default close operation for JFrame
      frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

      //set JFrame ssize
      frame.setSize(250,250);

      //make JFrame visible. So we can see it
      frame.setVisible(true);

   }
}

A: I think the following code will produce more or less what you expect.
    public static void main(String[]args)
{
    //Create array containing shapes
    String[] shapes ={"(no shape selected)","Circle","Equilateral Triangle","Square"};

    //Use combobox to create drop down menu
    JComboBox comboBox=new JComboBox(shapes);
    JPanel panel1 = new JPanel(new FlowLayout());
    JLabel label1 = new JLabel("Select shape:");
    panel1.add(label1);
    panel1.add(comboBox);

    JButton button = new JButton("GO");
    JTextField text = new JTextField(20);
    //Create a JFrame that will be use to put JComboBox into it
    JFrame frame=new JFrame("Area Calculator Window");
    frame.setLayout(new FlowLayout()); //set layout
    frame.add(panel1);
    frame.add(text);
    frame.add(button);
    //set default close operation for JFrame
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    //set JFrame ssize
    frame.setSize(250,250);

    //make JFrame visible. So we can see it
    frame.setVisible(true);
}


text:
Q: Dependencies for Go app aren't installed through godep on Heroku I want to deploy Go application on Heroku, but I got an error like this:
remote: -----> Go app detected
remote: -----> Checking Godeps/Godeps.json file.
remote: -----> Using go1.6.3
remote:  !!    Installing package '.' (default)
remote:  !!
remote:  !!
remote: -----> Running: go install -v -tags heroku .
remote: main.go:9:2: cannot find package "github.com/go-martini/martini" in any of:
remote:     /app/tmp/cache/go1.6.3/go/src/github.com/go-martini/martini (from $GOROOT)
remote:     /tmp/build_3c0222e075a91a3363e590a0169d6fb6/.heroku/go/src/github.com/go-martini/martini (from $GOPATH)

It works on my local environment and I added dependencies to Godeps/Godeps.json with godeps save command. What's the problem? I noticed official go-getting-started repo has vendor folder, so does it mean I have to have all dependencies into my repository?
This is my Godeps/Godeps.json:
{
    "ImportPath": "github.com/mikamikuh/oauth2-server-tester",
    "GoVersion": "go1.6",
    "GodepVersion": "v74",
    "Deps": [
        {
            "ImportPath": "github.com/codegangsta/inject",
            "Comment": "v1.0-rc1-10-g33e0aa1",
            "Rev": "33e0aa1cb7c019ccc3fbe049a8262a6403d30504"
        },
        {
            "ImportPath": "github.com/go-martini/martini",
            "Comment": "v1.0-185-gc257c41",
            "Rev": "c257c412d547ac70fcaf5596c1a50a7cb832c1fc"
        }
    ]
}

A: Yes, You do need to have all dependencies into your repository.
In fact when you run godep save ./... and you are using go 1.5 or greater, Godep will automatically put dependencies in a directory named vendor (inside root directory of your repo). You need to commit both Godep and vendor directory to your repository.
On side note while adding vendor directory use -f flag to add all files in it. It is needed as some files/directory might not be committed depending on your gitignore file and that will cause build failure in heroku. As a standard practice you can exeute following command to after adding dependencies using godep.

git add -f vendor/ Godep/
git commit -a -m "Vendorizing dependencies"


text:
Q: Transactions Log fails to shrink / release vfl The past two nights, our nightly index job has caused our log drive to fill up.   We complete log file backups every 15 minutes, and the log file still grew to 250GB.  This is a SQL Server 2008R2 SP3 instance.
Our DBCC LOGINFO shows 1500 rows, with all but 6 with a status of 2.
There are no open transactions.  (dbcc opentran)
The wait_type_desc = 2 / Backup Log
The database used to replicated, (long ago). Even ran the command to turn off replication.
However, completing a log backup does not seem to clear the VLFs.   The only way I've been able to clear is to convert the database to simple recovery and then shrink the logfile.   Which, obviously, this is not desirable.
I'm not sure where else to look.  Any help would be appreciated.


text:
Q: Change cell background with onEdit() The goal:

*

*Get the edited checkbox

*Get all checkboxes in range (column 2–7, same row as edited checkbox)

*If all checkboxes return "TRUE", set backgrounds on range (column 1–7, same row as edited checkbox)

Seems like the code do nothing.
function onEdit(event) {
  var sheet = event.source.getActiveSheet(), //get edited sheet
      row = event.range.getRow(), // get row needed
      column = 2, // set the starting column
      test,
      userValues = [];

  while (column<=7) {
    if (sheet.getValue(row,column) == "TRUE") {
      test = true
    } else {
      test = false;
      break;
    }

    column++;
  }

  if (test) {
    sheet.getRange(row,1,1,7).setBackgrounds("#b6d7a8");
  }
}

A: I believe your goal is as follows.

*

*You have the checkboxes to the columns "B" to "G".

*When all checkboxes from the columns "B" to "G" are checked, you want to set the background color of the columns "A" to "G" of the same row to #b6d7a8.

*In your situation, I guessed that when all checkboxes are not checked, you might want to set the background color to the default color.

When I saw your script, getValue is used in the loop. In this case, the process cost will be high. And, when you use sheet.getRange(row,1,1,7).setBackgrounds("#b6d7a8"), you can use sheet.getRange(row,1,1,7).setBackground("#b6d7a8").
In this case, how about the following modification?
Modified script:
function onEdit(event) {
  var sheetName = "Sheet1"; // Please set the sheet name.
  var range = event.range;
  var sheet = event.source.getActiveSheet();
  if (sheet.getSheetName() != sheetName || range.columnStart < 2 || range.columnStart > 7) return;
  var r = sheet.getRange(range.rowStart, 1, 1, 7)
  var checks = r.offset(0, 1, 1, 6).getValues()[0].every(e => e === true);
  r.setBackground(checks ? "#b6d7a8" : null);
}

*

*When you use this script, please check the checkboxes the columns "B" to "G". When all checkboxes from the columns "B" to "G" are checked, the background color of columns "A" to "G" is changed to #b6d7a8.

Note:

*

*This script is run by the OnEdit trigger. So please edit the cells of checkboxes from the columns "B" to "G". By this, the script is run. When you directly run this script with the script editor, an error occurs. Please be careful about this.

*When you are not required to check the sheet name, you can also use the following script.
  function onEdit(event) {
    var range = event.range;
    var sheet = event.source.getActiveSheet();
    if (range.columnStart < 2 || range.columnStart > 7) return;
    var r = sheet.getRange(range.rowStart, 1, 1, 7)
    var checks = r.offset(0, 1, 1, 6).getValues()[0].every(e => e === true);
    r.setBackground(checks ? "#b6d7a8" : null);
  }

References:

*

*every()

*setBackground(color)


text:
Q: Changing background based on data I have list of Computers which is source of some listBox [in C# WPF] and I want changing item background color based on some property like:
using System;
using System.Collections.ObjectModel;

namespace My_App
{
    public class Computer
    {
       public int Status {get; private set; } = 1; // 0=bad 1=ok;
       //other stuff...
    }

    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();

            ObservableCollection<Computer> pcList = new ObservableCollection<Computer>();
            foreach(Computer c in pcList.Items)
            {
                if(c.Status == 1)
                {
                    pcListItem.Background == Color.Blue;
                }
                if(c.Status == 0)
                {
                    pcListItem.Background == Color.Red;
                }
            }
        }
    }
}

I wrote it rly simplyfied, but I need somethink like that foreach method. I found many examples but none was based on some data, everythink was general (for all items in list)...


text:
Q: How would I attach self to another module's function/class? I am currently making a module that makes coding databases with sqlite3 easier and one of my functions is as follows:
def fetch(cursor, tableName, target = "*", condition = None, fetchType = "all"): # Fetches data from a table in a database
    "Fetches data from a table in a database\nExecutes 'SELECT {target} FROM {tableName} WHERE {condition}' on the cursor\nExample: user1Name = fetch(cursor, 'tblUser', target = 'userName', condition = 'userId = 1', fetchType = 'one')"

    if condition != None: cursor.execute(f"SELECT {target} FROM {tableName} WHERE {condition}") # Selects values if there is a condition

    else: cursor.execute(f"SELECT {target} FROM {tableName}") # Selects targets if there is not a condition

    if fetchType == "all": return cursor.fetchall() # Fetches all values

    elif fetchType == "one": return cursor.fetchone() # Fetches one value

    else: raise Exception("Invalid fetchType.") # Raises an exception if the user is trying to use an invalid fetchType

I essentially want to find a way to make it so instead of calling var = fetch(cursor... I can call var = cursor.fetch(tableName... for ease of access and because I simply want to know how I would do this in future.

A: This is called monkey-patching, which is very common for dynamic languages.  Find class of cursor (let's call it CursorClass), then monkey patch it in. The first parameter will act as self:
def fetch(cursor, table, ...)
    # cursor will act as self inside this functon
    ...

# Make sure that you do not override an
# existing attribute on CursorClass
CursorClass.fetch = fetch

# Then you can call fetch on the cursor
cursor = CursorClass(...)
cursor.fetch('TableName', ...)


text:
Q: Convert CheckBoxes into On-Off Button using Ajax I've managed to change the status of a product using CheckBox in ASP.NET MVC project with Ajax. Below is the code that I've tried and it worked:
Model:
public class List
{
   [Key]
   public int Id { get; set; }

   [Required(ErrorMessage = "Details can't be blank")]
   [DataType(DataType.Text)]

   public string Details { get; set; }
   public string Date_Posted { get; set; }
   public string Time_Posted { get; set; }
   public string Time_Edited { get; set; }
   public string Date_Edited { get; set; }
   public string Public { get; set; }
   public int User_Id { get; set; }
   public bool Status { get; set; }

   [Display(Name = "Is Public")]
   public string PublicPostDisplayText
   {
      get { return Status ? "Yes" : "No"; }
   }
}

Controller:
[HttpPost]
public JsonResult UpdatePublicPostStatus(int id, bool isPublicPost)
{
    MainDbContext db = new MainDbContext();

    var result = db.Lists.Find(id);
    if (result != null)
    {
       result.Status = isPublicPost;

       db.Entry(result).State = EntityState.Modified;
       db.SaveChanges();
    }

   return Json(true);
}

View:

@for (int i = 0; i < Model.Items.Count; i++)
{

    @Html.DisplayFor(modelItem => Model.Items[i].Id)
    @Html.DisplayFor(modelItem => Model.Items[i].Details)
    @Html.DisplayFor(modelItem => Model.Items[i].Time_Posted)
    @Html.DisplayFor(modelItem => Model.Items[i].Time_Edited)

    @if (@User.Identity.IsAuthenticated)
    {

 @Html.CheckBoxFor(modelItem => Model.Items[i].Status, new { @class = "post-checkbox", data_id = Model.Items[i].Id })
       Model.Items[i].Id)">Edit
       Model.Items[i].Id)">Delete
      @Model.Items[i].PublicPostDisplayText
    }

}

So this is how it looks now as follows:

I am trying to change the CheckBoxes into on-off button. I've tried to use the jQuery toggle plugin replacing the CSS class or id. But seems like I need to do something else. Not sure how to do it. When I click on the button, the value gets changed in the database but unable to show the toggling in the front-end.
Note: I just have to change the status of the product from yes to no or no to yes using CheckBoxes and transform the CheckBoxes into On-Off button similar to the below image:

Again, I've tried to use jQuery based toggle using some plugin like the following but didn't get it worked:

<link href="Content/jquery.btnswitch.min.css" rel="stylesheet" />

A: @Html.CheckBoxFor generates <input type="checkbox">. You can't call the btnSwitch function on that. Instead just use a
 or .


text:
Q: How to control the screen slide by code in the android? I'm trying to writing an app that can help me to control my screen.
For example,I can press a button,and my android phone can help me to slide from left to right by itself.
Please refer to the picture as below.

I saw some of the Transfer beads Game Cheat MAYBE use this method to control the screen slide automatically, but actually I don't know how it does.
For another example, refer form the following video. In this video,he made the phone slide the screen by itself. What I want to do is as same as his work. =)
https://youtu.be/a5quGThvjT4
Thank you all in advance!

A: As it figured out the OP needs a drag/drop on the same screen for his problem and not swiping between activities or fragments:
The keyword is "android drag and drop": https://developer.android.com/guide/topics/ui/drag-drop.html


text:
Q: Requests and webscraping: POST not returning expected results I'm trying to retrieve the search results from this booking website.
I first make a GET request and with BeautifulSoup retrieve the _csrf needed for the POST request data. I then make the POST request passing the relevant data but instead of the search results, the trip selection form is returned again. What am I doing wrong?
token = get_csrf_token()
params = set_params(token)
res = get_request(params)

def get_csrf_token():
    url = 'https://www.booking.alilaurogruson.it/booking/services/datas'
    r = requests.get(url, verify=False, timeout=10)
    csrf = search_csrf_token(r)
    return csrf

def search_csrf_token(r):
    soup = BeautifulSoup(r.content,'html.parser')
    csrf = soup.find('input', attrs={'name': '_csrf'})['value']
    return csrf

def set_params( csrf):
    params = urllib.parse.urlencode({
        "inputSearchFerriesBean.areasGoing": "1002",
        "inputSearchFerriesBean.tradesGoing": "12",
        "inputSearchFerriesBean.ret": "true",
        "inputSearchFerriesBean.areasReturn": "1007",
        "inputSearchFerriesBean.tradesReturn": "18",
        "inputSearchFerriesBean.dateGoing": "24/03/21",
        "inputSearchFerriesBean.dateReturn": "24/03/21",
        "_csrf": csrf
    })
    return params

def get_request(params):
    url = "https://www.booking.alilaurogruson.it/booking/services/search.action"
    r = requests.post(url, data=params, headers=headers, verify=False, timeout=10)
    return r

A: Using session will help you reuse the cookies which play an important role here to fetch the required content. You don't need to encode params as requests module knows how to handle it.
Try this way instead:
import urllib
import urllib3
import requests
from bs4 import BeautifulSoup

urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)

def get_csrf_token(s):
    url = 'https://www.booking.alilaurogruson.it/booking/services/datas'
    r = s.get(url, verify=False, timeout=10)
    csrf = search_csrf_token(r)
    return csrf

def search_csrf_token(r):
    soup = BeautifulSoup(r.content,'html.parser')
    csrf = soup.find('input', attrs={'name': '_csrf'})['value']
    return csrf

def set_params( csrf):
    params = {
        "inputSearchFerriesBean.areasGoing": "1002",
        "inputSearchFerriesBean.tradesGoing": "12",
        "inputSearchFerriesBean.ret": "true",
        "inputSearchFerriesBean.areasReturn": "1007",
        "inputSearchFerriesBean.tradesReturn": "18",
        "inputSearchFerriesBean.dateGoing": "24/03/21",
        "inputSearchFerriesBean.dateReturn": "24/03/21",
        "_csrf": csrf
    }
    return params

def get_request(s,params):
    url = "https://www.booking.alilaurogruson.it/booking/services/search.action"
    r = s.post(url, data=params, verify=False, timeout=10)
    return r

with requests.Session() as s:
    s.headers['User-Agent'] = 'Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/89.0.4389.90 Safari/537.36'
    token = get_csrf_token(s)
    params = set_params(token)
    s.headers['Referer'] = 'https://www.booking.alilaurogruson.it/booking/services/datas'
    res = get_request(s,params)
    soup = BeautifulSoup(res.text,"lxml")
    item = soup.select_one(".sectionTitle > span").text
    print(item)


text:
Q: How does Keras choose the final model if validation data is given? The final training step may not have the lowest loss if the loss fluctuates.
I want to know, if validation is given to training a model in Keras, how does Keras pick the final model?
Does

*

*Keras pick by choosing a model with the lowest loss on validation data from the whole training process?

Or

*Keras pick the final model from the final training step, regardless if the final model gives the minimum loss on validation data?

Thank you.

A: Yes, by default Keras return the final model from the final training step, regardless if the final model gives the minimum loss on validation data.
If you want to use a model with the lowest loss on validation data, you need to use the ModelCheckpoint callback with parameter save_best_only. After training is done, you need to load saved model. It will be the best model in terms of loss on validation data.
save_best_model = ModelCheckpoint(best_model_path, monitor='val_loss',
                                  save_best_only=True, save_weights_only=True)

# fit model
model.fit(X_train, y_train,
              batch_size=64,
              epochs=35,
              validation_data=(X_val, y_val),
              callbacks=[save_best_model])

# select the best model
model.load_weights(best_model_path)


text:
Q: Make Cursor Visible in JTextField within JTable without Left-click I'm trying to edit a JTextField within a JTable without left-clicking the cell. It seems that without left-clicking the cell, focus is not gained and cursor cannot be seen in the JTextField. Right-clicking the cell should make the JTextField editable and the cursor should be visible and blinking ready to type in the JTextField.
I found many examples of people with similar problems, but they were just different enough that I couldn't apply any of the solutions to my code (lack of experience and brain power perhaps?).
The below code is a dirty replica of the real code which I do not have access to at the moment. If my implementation of how to display a JTextField within a JTable is incorrect, please let me know.
Any help or advise would be appreciated. Thanks
import java.awt.Color;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.util.LinkedList;
import java.util.List;
import javax.swing.AbstractCellEditor;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.table.AbstractTableModel;
import javax.swing.table.TableCellEditor;
import javax.swing.table.TableCellRenderer;

public class EditableJTextFieldInJTable implements MouseListener{

 protected List<JTextField> textFields;
 protected JTable table;

    public EditableJTextFieldInJTable(){

        textFields = new LinkedList<JTextField>();

        JTextField tf1 = new JTextField("number 1");
    tf1.setBackground(Color.yellow);
    tf1.setEditable(false);
    textFields.add(tf1);

    JTextField tf2 = new JTextField("number 2");
    tf2.setEditable(false);
    tf2.setBackground(Color.green);
    textFields.add(tf2);

    TableModel tableModel = new TableModel();
    table = new JTable(tableModel);
    table.addMouseListener(this);
    table.setDefaultRenderer(Object.class, new CellRenderer());
    table.setDefaultEditor(Object.class, new CellEditor());
    table.setTableHeader(null);

    JFrame frame = new JFrame("Table Cell Edit Test");
    frame.setPreferredSize(new Dimension(800, 480));
    frame.getContentPane().add(new JScrollPane(table));
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.pack();
    frame.setVisible(true);

}

private class TableModel extends AbstractTableModel{

    @Override
    public int getColumnCount(){
        return 1;
    }

    @Override
    public int getRowCount(){
        return textFields.size();
    }

    @Override
    public Object getValueAt(int row, int col){
        return textFields.get(row);
    }

    @Override
    public boolean isCellEditable(int row, int col){
        return textFields.get(row).isEditable();
    }

}

public class CellRenderer implements TableCellRenderer{

    public Component getTableCellRendererComponent(JTable table, Object value,
        boolean isSelected, boolean hasFocus, int row, int col){
        return textFields.get(row);
    }

}

public class CellEditor extends AbstractCellEditor implements TableCellEditor{

    public Component getTableCellEditorComponent(JTable table, Object value,
          boolean isSelected, int row, int col){
        JTextField textField = textFields.get(row);
        return textField;
    }

    @Override
    public Object getCellEditorValue(){
        return null;
    }

}

@Override
public void mouseClicked(MouseEvent arg0){
    if(arg0.getSource().equals(table)){
        int row = table.rowAtPoint(table.getMousePosition());
        System.out.println("row: " + row + " clicked.");
        JTextField textField = textFields.get(row);
        if(arg0.getButton() == MouseEvent.BUTTON3 && textField != null){
            textField.setEditable(true);
            System.out.println("row: " + row + " set editable. Caret should now be visible in cell.");
        }
    }

}

@Override
public void mouseEntered(MouseEvent arg0) {
    // Empty method.
}

@Override
public void mouseExited(MouseEvent arg0) {
    // Empty method.
}

@Override
public void mousePressed(MouseEvent arg0) {
    // Empty method.
}

@Override
public void mouseReleased(MouseEvent arg0) {
    // Empty method.
    }

    public static void main(String[] args){
        new EditableJTextFieldInJTable();
    }

}

A: So after persisting, it seems I have found an answer. First I have to let the table know that I want to edit the cell, and then request focus for the TextField.
@Override
public void mouseClicked(MouseEvent arg0){
    if(arg0.getSource().equals(table)){
        int row = table.rowAtPoint(table.getMousePosition());
        System.out.println("row: " + row + " clicked.");
        final JTextField textField = textFields.get(row);
        if(arg0.getButton() == MouseEvent.BUTTON3 && textField != null){
            textField.setEditable(true);
            table.editCellAt(row, 0);
            textField.requestFocus(); // 'textField' is the object within the cell.
            textField.setCaretPosition(textField.getText().length());
            System.out.println("row: " + row + " set editable. Caret should now be visible in cell.");
        }
    }
}


text:
Q: Using Multithreading or Multiprocessing to improve computational speed I am iterating through very large file size [mesh]. Since the iteration is independent, I would like to split my mesh into smaller sizes and run them all at the same time in order to lower computation time. Below is a sample code. For example, if mesh is of length=50000, I would like to divide the mesh into 100 and run fun for each mesh/100 at the same time.
import numpy as np
def fnc(data, mesh):
    d = []
    for i, dummy_val in enumerate(mesh):
        d.append(np.sqrt((data[:, 0]-mesh[i, 0])**2.0 + (data[:, 1]-mesh[i, 1])**2.0))
    return d

interpolate = fnc(mydata, mymesh)

I would like to know to achieve this using multiprocessing or multithreading as I'm unable to reconcile it with the execution of my loop.

A: This will give you the general idea. I couldn't test this since I do not have your data. The default constructor for ProcessPoolExecutor will use the number of processors on your computer. But since that determines the level of multiprocessing you can have, it will probably be more efficient to set the N_CHUNKS parameter to the number of simultaneous processes you can support. That is, if you have a processing pool size of 6, then it is better to just divide your array into 6 large chunks and have 6 processes do the work rather than breaking it up into smaller pieces where processes will have to wait to run. So you should probably specify a specific max_workers number to the ProcessPoolExecutor not greater than the number of processors you have and set N_CHUNKS to the same value.
from concurrent.futures import ProcessPoolExecutor, as_completed
import numpy as np

def fnc(data, mesh):
    d = []
    for i, dummy_val in enumerate(mesh):
        d.append(np.sqrt((data[:, 0]-mesh[i, 0])**2.0 + (data[:, 1]-mesh[i, 1])**2.0))
    return d

def main(data, mesh):
    #N_CHUNKS = 100
    N_CHUNKS = 6 # assuming you have 6 processors; see max_workers parameter
    n = len(mesh)
    assert n != 0
    if n <= N_CHUNKS:
        N_CHUNKS = 1
        chunk_size = n
        last_chunk_size = n
    else:
        chunk_size = n // N_CHUNKS
        last_chunk_size = n - chunk_size * (N_CHUNKS - 1)
    with ProcessPoolExcutor(max_workers=N_CHUNKS) as executor: # assuming you have 6 processors
        the_futures = {}
        start = 0
        for i in range(N_CHUNKS - 1):
            future = executor.submit(fnc, data, mesh[start:start+chunk_size]) # pass slice
            the_futures[future] = (start, start+chunk_size) # map future to request parameters
            start += chunk_size
        if last_chunk_size:
            future = executor.submit(fnc, data, mesh[start:n]) # pass slice
            the_futures[future] = (start, start+n)
    for future in as_completed(the_futures):
        (start, end) = the_futures[future] # the original range
        d = future.result() # do something with the results

if __name__ == '__main__':
    # the call to main must be done in a block governed by if __name__ == '__main__' or you will get into a recursive
    # loop where each subprocess calls main again
    main(data, mesh)


text:
Q: htaccess two folder rewrite rule I already use this htaccess rule already and it works
RewriteRule ^community/profile/([^/]+) community/profile/profile.php?id=$1

So, when I'm on a profile page for example website.com/community/profile/example-user, I will be able to extract the user from the id=$1 part.
I need to extend this to two folders, where example-user can have 2 sub-folders, like website.com/community/profile/example-user/folder1/ and website.com/community/profile/example-user/folder 2/
I tried the following rule:
RewriteRule ^community/profile/([^/]+)/([^/]+) community/profile/profile.php?id=$1&car=$2

Unfortunately though, this breaks the whole rule and it doesn't work. I got the idea from this post https://webmasters.stackexchange.com/questions/65785/rewrite-up-to-three-folders-into-three-query-string-parameters-to-a-php-script
Also, I tried
RewriteRule ^community/profile/../([^/]+) community/profile/profile?id=$1&car=$2

Also didn't work.
To make things clear, if one only goes to the 'first' folder, in this example it is /example-user/, the car variable should just be empty. How can I write this rule so that it will put that second 'folder' into a second variable so I can extract it later in my php file?

A: *

*Make sure to use anchor $ for precise matching in regex

*Include dot in your character class to avoid matching it again

Rules :
RewriteRule ^community/profile/([^/.]+)/?$ community/profile/profile.php?id=$1 [L,QSA,NC]

RewriteRule ^community/profile/([^/.]+)/([^/.]+)/?$ community/profile/profile.php?id=$1&car=$2 [L,QSA,NC]


text:
Q: There are $3$ boys and $3$ girls. How many ways can they be arranged in a way that two girls won't be together?

*

*There are $3$ boys and $3$ girls. How many ways can they be arranged in a way that two girls won't be together?

Instead of making things harder, I directly write an assumption as illustrated below
$$\text{All permutations = Total possibilities - Two girls are together}$$
We already notice that total possibilities should be $6!$. Let's calculate the permutation of two girls are together. Recall that $K$ represents Girls, $E$ represents boys.
Entity $1$: $K_1K_2 \implies 1$
Entity $2$: $B_1B_2B_3K_3 \implies 4$
Entity $1$ and $2$: $5!$
And girls can be rearranged in $2$, which yields $5!\times 2!$. Plugging into the equation we wrote
$$6!-5!\times 2! = 480$$
However, the final answer I got should be wrong. Can you assist?

A:
In how many ways can three boys and three girls be arranged in a row so that no two girls are adjacent?

Method 1:  We arrange the three boys in a row, then place the girls in the spaces between the boys and at the ends of the row to separate them.
The three boys can be arranged in a row in $3!$ ways.  This creates four spaces, two between successive boys and two at the ends of the row.
$$\square B_1 \square B_2 \square B_3 \square$$
To ensure that no two girls are adjacent, we must choose of these spaces in which to place the girls, which can be done in $\binom{4}{3}$ ways.  The three girls can be arranged in the selected spaces in $3!$ ways.  Hence, the number of admissible arrangements is
$$\binom{4}{3}3!3!$$
Method 2:  We correct your attempt by using the Inclusion-Exclusion Principle.
There are $6!$ ways to arrange the six people.  As you stated, we wanted to exclude those arrangements in which a pair of girls are adjacent.
There are $\binom{3}{2}$ ways to select two girls who are adjacent.  We have five objects to arrange, the block of two girls and the other four children.  The objects can be arranged in $5!$ ways and the girls can be arranged within the block in $2!$ ways.  Hence, there are $$\binom{3}{2}5!2!$$ arrangements in which two girls are adjacent.
If we subtract the number of arrangements in a pair of girls are adjacent from the total, we will have subtracted too much since we will have subtracted each arrangement in which there are two pairs of adjacent girls twice, once for each pair of adjacent girls we could have designated as the pair of adjacent girls.  We only want to subtract those arrangements once, so we have to add the number of arrangements in which there are two pairs of adjacent girls to the total.
To have two pairs of adjacent girls, all three girls must be consecutive.  If we treat the three consecutive girls as a block, we have four objects to arrange, the block of three girls and the three boys.  The objects can be arranged in $4!$ ways.  The girls can be arranged within the block in $3!$ ways.  Hence, the number of arrangements in which there are two pairs of adjacent girls is $4!3!$.
Hence, the number of admissible arrangements is
$$6! - \binom{3}{2}5!2! + \binom{3}{3}4!3!$$

A: You don't state it, but I'm assuming the boys are indistinguishable and the girls are indistinguishable.  Please clarify this point!
Consider three girls.  There must be at least one boy separating pairs:  $GBGBG$.  The only question then remains where the last boy can go:  $\bullet G \bullet B \bullet G \bullet B \bullet G \bullet$.  Note that some of these cases are identical, so you can eliminate them
How many distinguishable places all told?

A: The girls can be in positions $\{1,3,5\}$, $\{1,3,6\}$, $\{1,4,6\}$, or $\{2,4,6\}$. For each of these there are six permutations of the girls, and for each of these there are also six permutations of the boys, so the answer should be $4\cdot 3!\cdot 3! = 144$.

A: All the ways to seat all of the people
$6!$
At least $2$ girls together.
We attach 2 girls, and allocate $5$ objects.  Making for $5!$ allocations
$5!$  But we can swap the order of the girls.  And we have 3 girls who we can make the "odd-man-out"
$5!\cdot 6 = 6!$
But we have double counted all of the cases where we have all 3 girls together.
$4!3!$
$6! - (6! - 4!3!) = 4!3! = 144$


text:
Q: Can I combine two different DOM to combine selector :nth-child with combined indexes? Supposed I have these kind of html

   1
   2
   3

   4
   5
   6

The css code is below
span:nth-child(2),
span:nth-child(4),
span:nth-child(6){
   background-color:red;
}

This is what I want by using css above

   1
   2
   3

   4
   5
   6

Can I combine div with class "one" and "two", then use nth-child with combined indexes between those two classes?

A: You will need to define different selectors for spans in div.one and in div.two to achieve this.
Like this:
.one span:nth-child(2) {
    background-color: red;
}

And
.two span:nth-child(1), .two span:nth-child(3) {
    background-color: red;
}


text:
Q: Animating opacity, opacity in general in IE When IE renders a filter: alpha(opacity=..) whether it's on an image or text. It looks bad.
Is there a way to make IE render normal-browser-like smooth opacity?
If no, how can I easily after a fadeIn (opacity x->1) javascript animation re-render the elements so it doesn't look bad anymore..?

A: Applying a background colour or an opaque background image to the element should fix this problem.  This is due to the way filters work, they're ActiveX components and they're old so they have certain limitations when working with partial transparency.
You can also disable the filter when the animation has completed, using something like:
myElement.filters[0].enabled = false;

A lot of animation libraries use this technique to enable the filter only during the fading so the user will not notice the ugly aliasing as much.
There's another fix (best viewed in IE to understand the point of the post), although it's more of a hack and it's not a good solution in all cases, particularly where you need to alter the size of the image.


text:
Q: Como calcular a distância entre dois pontos de localização? Estou precisando calcular a distância mais curta entre duas localizações obtidas automaticamente através do CoreLocation.
Pra ser mais específico, a ideia é marcar um ponto inicial e depois do usuário "andar" um pouco, preciso calcular a distância percorrida quando chegar em outro local

A: A partir de dois objetos CLLocation você obtém a distância, em metros, atráves do método distanceFromLocation. Exemplo:
CLLocationDistance distance = [location1 distanceFromLocation:location2];


text:
Q: ASP.NET : XML Viewer for website I have a XML file , that I need to show to the users in readable format i.e in formatting.
how this can be done with ASP.net website.
Any Help

A: You can use Xml control to perform XSL transformation.

A: Actipro Software has a great and FREE ASP.NET control that allows you to view XML (and other content) in a syntax highlighted fashion - it's called CodeHighlighter:

(source: actiprosoftware.com)
It's read-only, but if that's good enough for your scenario, it's the best solution around, I think!


text:
Q: Display animation in java? I am very very new at java (as in, I took one beginner course) so please don't get super technical when answering me.
Earlier today I learned how you can load an image in java and display it in an applet.
I found a step-by-step youtube video that helped me do this.
Now I want to know how I can load an animation in java. Is that something that can be done? And can I get step-by-step instructions on how to do it? Basically, I already have a short .wmv file and I would like to display it when I run the program.
It also has audio that I would like to play along with it.
(i'm actually trying to make a video game with an animated character. java can be used to program games, so this should be doable, right? i don't care about making a game the "right" way or the way game developers usually do it, right now i just want to figure out the simple task of displaying an animation in java.)
thanks!

A: First of all, the wmv extension stands for video, and an animation is not a video. Its either a spritesheet, a gif image ect. In order to create a even simple animation, you must first learn some basic object oriented programming, become comfortable in creating and using classes, than you can advance to making your own class for taking care of sprites and cutting an image in a way that you can use it ect.
Example of a simple spriteshet:

This spritesheet is an simple image showing you one way to implement your 2d animation. You just have to cut the image parts from it using some rectangles. For 3d, you must use some other software and you must know that they use different kinds of extensions.
I wont dive into code, for the simple reason that I do not have time right now, but if you want further help, give my some contact like skype, facebook ect, I would love to help.

A: You could try the Java Media Framework javax.media.*. (caveat: rather old framework)
It appears you simply need to embed a media file such as video or audio into an applet. This can be achieved through a player embedded into an applet, similar to an individual frame or a .GIF file, that would be able to handle the .WMV extension.
Assuming awareness of the basic structure of a Java program, the main declaration to get an instance of a player is of the generic form, after:
player = Manager.createRealizedPlayer( mediaURL );

or
player = Manager.createPlayer( file.toURL() );

Good idea to go through the JMF documentation.


text:
Q: 24 V solar panel gives half the current of a 12 V panel I look at solar panels for sale and notice that a 12v 250w panel gives 13.9amps while a 24v 250w gives only 6.6amp. which is why I asked if the 24v would charge my batteries as efficiently as the 12v. WHY does the 24v panel give less amps than a 12v? Simple question that nobody seems to understand.
Thanks, j

A: Such is the magic of MPPT:
Since the panel starts to drop its output voltage when it is producing current, there is a magic point - depending on the solar input - where the panel produces the maximum power (voltage times current). The electronics of the MPPT push this power into your battery at the correct voltage for the present state of the battery.
Disregarding losses, the current into the battery times the voltage at the battery should equal the current out of the panel times the panels actual output voltage.
tldr: your battery will still receive 12A at 12V.

A: If your old panel gave 12A at 12V, that is 144W (voltage x current). If the new one gives 6A at 24V, that also is 144W.
For the same size and performance panel, about the same output power is to be expected under similar conditions.


text:
Q: Drop down menu doesn't work after moved the header to another file So I have this drop-down menu which has 7 columns. Everything worked just great till I decided to move all the header to a different file and include it from there.
Almost everything is working now great but one column that refuse to work.
Anyone familiar with the problem? Any ideas what should I check?
Thank you! :)


text:
Q: Matplotlib Plot with Finer tick marks but no labels I am trying to produce a plot where I have customized axis ticks on both x and y axis. But like in a scale, I would like to have the finer tick marks present while the tick markings only on the bigger values. Like shown in the attached plot(which is similar to what I want).
so I tried :
ax.tick_params(labeltop=True, labelright=True)

Because I need the ticks on all 4 sides. and then I would do something like this :
ax.yaxis.set_ticks_position('both')
ax.xaxis.set_ticks_position('both')

and then specify the range :
plt.xticks(np.arange(-1.20, -0.79, 0.04))
plt.yticks(np.arange(-1.0,1.2, 0.1))

But I would like the numerical markings every 5th position (or every 5th tick)

A: Here's My solution : (thanks @Diziet)
from matplotlib.ticker import (MultipleLocator, FormatStrFormatter,AutoMinorLocator)
# Plotting codes go in here
ax.yaxis.set_ticks_position('both')# Ticks on all 4 sides
ax.xaxis.set_ticks_position('both')
plt.xticks(np.arange(-1.21, -0.79, 0.04)) # Axes ranges
plt.yticks(np.arange(-0.9,0.9, 0.1))
ax.xaxis.set_major_locator(MultipleLocator(0.05)) # Intervals for major x-ticks
ax.xaxis.set_minor_locator(AutoMinorLocator()) # Minor ticks : Automatic filling based on the ytick range
ax.yaxis.set_major_locator(MultipleLocator(0.3))  # For y-ticks
ax.yaxis.set_minor_locator(AutoMinorLocator())

Attached is the Final product


text:
Q: Definition of Invertible Matrix In Linear Algebra Done Right, Axler defines, in Chapter 10, an invertible matrix as:

A square matrix $A$ is called invertible if there is a square matrix $B$ of the same size such that $AB=BA=I$, and we call $B$ an inverse of $A$.

Question: Why does he include same size in his definition? Won't it be automatically implied if $AB=BA=I$?
Even Wikipedia mentions of the same size.
I thought that we make mathematical definitions as concise as possible.

A: You need the same size to make sure that $AB$ and $BA$ are actually defined.

A: You are right, this is superfluous, as are the two square qualifiers.

A: Even if it is not necessary to mention in the definition, it does not hurt either. It will make the reader consider the relevant situation (two square matrices of the same size), so why not help the reader?
Do note that non-square matrices can produce an identity matrix when multiplied together in one order only, as in the following example:
$$\begin{bmatrix}-8 & 0 & -9 \\ -7 & 0 & -8\end{bmatrix}
\begin{bmatrix}-8 & 9 \\ 0 & 0 \\ 7 & -8\end{bmatrix}
=\begin{bmatrix}1 & 0 \\ 0 & 1\end{bmatrix}$$
In such cases, when you multiply the matrices in the opposite order, like $\begin{bmatrix}-8 & 9 \\ 0 & 0 \\ 7 & -8\end{bmatrix}\begin{bmatrix}-8 & 0 & -9 \\ -7 & 0 & -8\end{bmatrix}$, the result will not be an identity matrix (you can prove that as an exercise).


text:
Q: Как правильно переназначить методы place, pack и grid в составе класса? как правильно переназначить методы place, pack и grid в составе класса? Нужно сделать так, чтобы параметры которые не заданы применялись те, которые по умолчанию стоят в исходных методах place, pack и grid.
Мой пример (но я не уверен в правильности):
def place(self, x=None, y=None):
    self.canvas.place(x=x, y=y)

def pack(self, fill=None, expand=None, side=None, anchor=None, padx=None, pady=None):
    self.canvas.pack(fill=fill, expand=expand, side=side, anchor=anchor, padx=padx,  pady=pady)

def grid(self, row=None, column=None, columnspan=None, sticky=None, rowspan=None, padx=None, pady=None):
    self.canvas.grid(row=row, column=column, columnspan=columnspan, sticky=sticky, rowspan=rowspan, padx=padx, pady=pady)

Может так лучше?:
def place(self, *args):
    self.canvas.place(*args)

def pack(self,  *args):
    self.canvas.pack(*args)

def grid(self, *args):
    self.canvas.grid(*args)

A: Если нужно пробросить все аргументы метода - и позиционные (просто перечисляемые через запятую), и именованные (передаваемые с указанием имени аргумента, например row=3) - в вызов другого метода, нужно принять и передать и *args, и **kwargs:
def some_method(self, *args, **kwargs):
    some_object.some_other_method(*args, **kwargs)


text:
Q: Run Function / Get Data when loading new screen in Flutter I am trying to run a function that gets data via an API call that needs to initialize before / while loading the screen. I have tried using a future builder, and other methods, and perhaps i am not implementing this correctly but i cannot figure out how to do this. I have also called an async method that uses setState within my initstate method which works, but it initially loads and returns an error and what I assume is that after the state rebuilds it displays correctly.Ideally this should get the data before actually loading the screen to avoid errors.
Code for my main function in the main.dart file
void main() async {
WidgetsFlutterBinding.ensureInitialized();
SystemChrome.setPreferredOrientations(
  [DeviceOrientation.portraitUp, DeviceOrientation.portraitDown]
);
final Future<SharedPreferences> _prefs = SharedPreferences.getInstance();
final SharedPreferences prefs = await _prefs;

late String initialRoute;

var accessToken = prefs.getString('access_token');
var refreshToken = prefs.getString('refresh_token');

if (accessToken != null && refreshToken != null) {
  var response = await sessionRefresh(accessToken);
  if (response.statusCode == 200) {
    initialRoute = kDashboardID;
  }
  else if (response.statusCode == 401) {
    var refreshResponse = await tokenRefresh(refreshToken);
    if (refreshResponse.statusCode == 200) {
      prefs.setString('access_token', jsonDecode(refreshResponse.body)["access_token"]);
      initialRoute = kDashboardID;
    }
    else {
      initialRoute = kLoginScreenID;
    }
  }
}
else {
  initialRoute = kLoginScreenID;
}

runApp(MyApp(initialRoute: initialRoute,));
}

class MyApp extends StatelessWidget {
//const MyApp({Key? key}) : super(key: key);

final Future<SharedPreferences> _prefs = SharedPreferences.getInstance();
String initialRoute;

MyApp({required this.initialRoute});

// This widget is the root of your application.

@override
Widget build(BuildContext context) {
  return ChangeNotifierProvider(
    create: (context) => UserData(),
    child: MaterialApp(
      debugShowCheckedModeBanner: false,
      routes: {
        kLaunchScreenID: (context) => LaunchScreen(),
        kLoginScreenID: (context) => LoginScreen(),
        kUserRegistrationID: (context) => UserRegistration(),
        kAccountVerificationID: (context) => OTPVerification(),
        kDashboardID: (context) => Dashboard(),
        kAccountsID: (context) => Accounts(),
      },
      initialRoute: initialRoute,
    ),
  );

 }
}

The ideal result would be when the initialRoute equals "kDashboardID" (user dashboard) i need to run a function that gets data so that the data can be used to populate certain widgets (text widgets, etc.) on the dashboard screen.
Not sure how to best to accomplish this.


text:
Q: Make a line in faceted ggplot2 with width from dataframe I am looking to create a graph that looks like the second picture below, using data provided below. However, I can't get the width of the lines to correspond to the axis, "B", and to take the values from datlines$width. What I'd like is for geom_hline (or maybe geom_ribbon?) to read the widths from the data.frame "datlines" and create a line where the width is equal to the number provided in datlines$width. So far I haven't been able to make it work, even if I specify "size = width" in the geom_hlines call.
Any suggestions? Even if I get the size = width part to mirror my datlines data.frame, the size of the line doesn't correspond to the y-axis.
I'd be fine if I had to tell ggplot2 the upper and lower boundaries of the grey area, too.
dat
  A B      C
1 1 2 Facet1
2 1 3 Facet2
3 2 4 Facet1
4 2 5 Facet2

datlines
  int      C width
1   3 Facet1   1.0
2   4 Facet2   0.5

My data and code for the fist graph below
dat <- data.frame(A = c(1, 1, 2, 2), B = c(2, 3, 4, 5), C = c("Facet1", "Facet2"))
dat
datlines <- data.frame(int = c(3, 4), C = c("Facet1", "Facet2"), width = c(1, 0.5))
datlines
plot <- ggplot(dat, aes(x = A, y = B)) +
  geom_hline(data = datlines, aes(yintercept = int), colour = "gray") + geom_point() + facet_grid(. ~ C)
plot

Graph that results from the code I provided:

Graph that I want:

A: use geom_rect
dat <- data.frame(A = c(1, 1, 2, 2), B = c(2, 3, 4, 5),
                  C = c("Facet1", "Facet2"),
                  width=c(1,0.5), int = c(3, 4))
require(ggplot2)
ggplot(dat, aes(x=A,y=B)) + geom_point() + facet_grid(~C) +
  geom_rect(aes(xmin=-Inf, xmax=Inf,
                ymin=int-width/2, ymax=int+width/2), fill = 'grey')

A: You can use geom_rect, but you'll have to modify ymin and ymax first:
datlines$int2 <- c(2.5, 3.75)

ggplot() +
geom_point(data=dat, aes(x = A, y = B)) +
geom_rect(data=datlines, aes(ymin=int2, ymax=int2+width, xmin=-Inf, xmax=+Inf), fill='grey', alpha=1)  +
facet_grid(. ~ C)


text:
Q: The method sendKeys(CharSequence...) in the type WebElement is not applicable for the arguments (double) I have write a script for read input data from excel file,but gives me error into sendkeys where i use getNumericCellValue.
Please help.
This is my code
FileInputStream file = new FileInputStream(new File ("C:\\Documents and Settings\\Deepa\\Desktop\\AMC test cases.xls"));
 HSSFWorkbook workbook = new HSSFWorkbook(file);
 HSSFSheet sheet = workbook.getSheet("Clinic Basic info");
 WebElement creat_new_website = driver.findElement(By.className("createnew"));
 creat_new_website.click();
 driver.findElement(By.id("cname")).sendKeys(sheet.getRow(2).getCell(4).getStringCellValue());
 //driver.findElement(By.xpath("/html/body/div[4]/div[4]/div[12]/form/div/div[1]/div[3]/div[2]/div/button")).click();
 //driver.findElement(By.xpath("/html/body/div[4]/div[4]/div[12]/form/div/div[1]/div[3]/div[2]/div/ul/li[7]/a")).click();
 driver.findElement(By.id("caddress")).sendKeys(sheet.getRow(4).getCell(4).getStringCellValue());
 driver.findElement(By.id("clocality")).sendKeys(sheet.getRow(5).getCell(4).getStringCellValue());
 driver.findElement(By.id("ccity")).sendKeys(sheet.getRow(6).getCell(4).getStringCellValue());
 driver.findElement(By.id("cstate")).sendKeys(sheet.getRow(7).getCell(4).getStringCellValue());
 driver.findElement(By.id("cpincode")).sendKeys(sheet.getRow(8).getCell(4).getNumericCellValue());
 driver.findElement(By.id("ccountry")).sendKeys(sheet.getRow(9).getCell(4).getStringCellValue());
 driver.findElement(By.id("curl")).sendKeys(sheet.getRow(10).getCell(4).getStringCellValue());

A: Try
x.sendKeys(String.valueOf(someNumber))

A: As the error message mentions, sendKeys() receives String as parameter. To send double you need to convert it into String. The simplest ways are adding toString
 driver.findElement(By.id("cpincode")).sendKeys(sheet.getRow(8).getCell(4).getNumericCellValue().toString());

Or using String.valueOf
driver.findElement(By.id("cpincode")).sendKeys(String.valueOf(sheet.getRow(8).getCell(4).getNumericCellValue()));

A: Hi simplest of all is to make the complete excel sheet column and row format to string


text:
Q: tkinter canvas image is not displayed in class I am trying to display an image in python using the tkinter canvas option. However, if I input it in a class, like below, it doesn't give an error but also doesn't show my image. The buttons are displayed correctly though. Also, if I take the code for generating this image out of the class it works correctly. I can't seem to find out what the problem is.
import Tkinter as tk
from Tkinter import *

class Board(tk.Frame):
    def __init__(self,parent):

        frame = Frame(parent)
        frame.pack()
        tk.Frame.__init__(self,parent)

        frame2 = Frame(frame)
        frame2.pack()

        c=Canvas(frame2)
        c.pack(expand=YES,fill=BOTH)
        background=PhotoImage(file='Board.gif')
        c.create_image(100,100,image=background,anchor='nw')

        button = Button(frame, text="Next turn", command=self.next_turn)
        button.pack()

        button = Button(frame, text="Roll the dice", command=self.roll)
        button.pack()

        ....

root = Tk()
board = Board(root)
board.pack()
root.mainloop()

A: You have to keep a reference to the PhotoImage. This is just and example (you can also use self.background instead of c.background):
    c = Canvas(frame2)
    c.pack(expand=YES,fill=BOTH)
    c.background = PhotoImage(file='Board.gif')
    c.create_image(100,100,image=c.background,anchor='nw')


text:
Q: Some more explanation about an array example I found online I'm just starting out to learn program in C and am trying to get my head around arrays. I found this example online but don't understand how it works. Here is the code:
#include <stdio.h>

int main () {

   int n[ 10 ]; /* n is an array of 10 integers */
   int i,j;

   /* initialize elements of array n to 0 */
   for ( i = 0; i < 10; i++ ) {
      n[ i ] = i + 100; /* set element at location i to i + 100 */
   }

   /* output each array element's value */
   for (j = 0; j < 10; j++ ) {
      printf("Element[%d] = %d\n", j, n[j] );
   }

   return 0;
}

What I don't understand here is how int j links to int i. In the output, at the printf line, I don't understand why it is not:
printf("Element[%d] = %d\n", i, n[i]);

Why do we need another int j?
And another thing I don't understand is the %d's in that line. Why %d and not %i? d hasn't been declared anywhere right?
Any deeper explanation than on the website where I found this example would be appreciated.  Thank you.

A: Agreeing with @ Eugene Sh, that in this case, j is indeed an extra variable.
The coding would be as shown below, and would return the same output.
    for (i = 0; i < 10; i++) {
    printf("Element[%d] = %d\n", i, n[i]);
}

And another thing I don't understand is the %d's in that line.

The printf() family of functions uses % character as a placeholder. This is a format specifier and does not require initialization. When a % is encountered, printf reads the characters following the % to determine what to do:
%s - Take the next argument and print it as a string
%d - Take the next argument and print it as an int

Sooner or later you might also encounter %s, which indicates that you're expecting a String to be your first print parameter.
Hope this helps.

A:
Why do we need another int j?

You don't.  I'm assuming the author was just demonstrating that you can use any variable to index into an array, as long as the variable has the right type (pretty much any integral type) and holds a value in the correct range.
Array indices can be any integral expression, whether it's an integral constant (a[5]), a variable (a[i], a[j]), or a more complex expression (a[i+j], a[foo(i)],  a[1+j*k/2], etc.).  All that matters is that the expression has an integral type, and that its result is in the correct range (0 to N-1, where N is total number of elements in the array).

And another thing I don't understand is the %d's in that line. Why %d and not %i? d hasn't been declared anywhere right?

%d is a conversion specifier - it has nothing to do with any variable, and does not need to be declared separately.  Conversion specifiers in the format string tell printf the number and types of additional arguments, and how to format those values for display.
In the line
printf("Element[%d] = %d\n", i, n[i]);

the %d specifiers in the format string tell printf that i and n[i] both have type int, and that they are to be formatted as decimal integers (as opposed to hex or octal, for example).
Here's an incomplete list of conversion specifiers:
Specifier        Argument Type        Output format
---------        -------------        -------------
    %d,%i                  int        decimal integer
       %u         unsigned int        decimal integer (non-negative)
       %f               double        decimal floating point
    %x,%X         unsigned int        hexadecimal integer (non-negative)
       %o         unsigned int        octal (non-negative)
       %c                 char        single character
       %s               char *        text

Check your handy C reference manual for a complete list.  If you don't have a handy C reference manual, I recommend Harbison & Steele's C: A Reference Manual.

A:
What I don't understand here is how int j links to int i

They don't "link" and there is actually no connection between the two. The author simply used another integer (j) to avoid confusion.
As for your suggestion:

In the output, at the printf line, I don't understand why it is not:
printf("Element[%d] = %d\n", i, n[i]);

It is perfectly fine to do so if you make sure to use i as the loop variable for the second loop as well like so:
for (i = 0; i < 10; i++ ) {
      printf("Element[%d] = %d\n", i, n[i] );
   }

And another thing I don't understand is the %d's in that line. Why %d and not %i? d hasn't been declared anywhere right?

%d is a type modifier that tells the printf function to replace it with a decimal number when printing. It has nothing to do with some sort of variable named d. Your confusion might originated from the fact that there is also a %i modifier for printf but it is less commonly used. Refer to this wiki for more details.


text:
Q: Convert Dataset in Spark to XSSFRow in Java Working on a language conversion from .sas to java.
The code needs to take the data from an external audit set up in a spark session, and write to an excel sheet.
The current spark "tables" are written as Dataset and I need it in the XSSFRow or Row (also with poi) type.
Example for reference:
Dataset<Row> Platinum = dsd
    .where(col("cell").isin(plat_list)
    .select(//cols in sql table to be read)

XSSFRow row = Platinum.toXSSFRow()
//^ I need this to happen


text:
Q: Change Mac App Icon With A Terminal Command I like to use custom icons for a few apps. However, of course, when an app updates the icon is reset. I'd like to be able to run a script to instantly update all of my custom app icons automatically.
At present, I right click on an app and select get info. Then, I can drag an .icns file on to the original icon at the top of this window. Relaunch the dock, and done! Much like this tutorial.
Does anyone know if there's a terminal command to achieve the same thing? I've seen variations that dive into an app's resources folder and change the .icns file there, but this is a different process, and I haven't had much look with this.
Any ideas?

A: I have a folder called "App Icons" in my Dropbox. Just inside I have a shell script called install.sh, and next to that I have folders for each app I want custom icons for. Currently that's Atom and Mattermost.
Inside each directory I have atom.icns and Mattermost.icns, respectively.
To get both apps updated I run this script:
#!/usr/bin/env bash

set -euf -o pipefail
umask 077
has_copied=0

for atom in Atom "Atom Beta"; do
    path="/Applications/${atom}.app"
    [ -d "${path}" ] && \
    cp ./Atom/atom.icns "${path}/Contents/Resources/atom.icns" && \
    touch "${path}" && \
    has_copied=1
done

for mattermost in Mattermost; do
    path="/Applications/${mattermost}.app"
    [ -d "${path}" ] && \
    cp ./Mattermost/Mattermost.icns "${path}/Contents/Resources/Mattermost.icns" && \
    touch "${path}" && \
    has_copied=2
done

[ ${has_copied} = "2" ] && killall Dock

Atom usually updates immediately with the [ ${has_copied} = "2" ] && killall Dock line. Mattermost does not, but I'm guessing that's a case-by-case basis. I suspect there is a much smarter way to loop through all available icons and update their respective apps, but I'm no bash maestro, so I kept it simple.
In order to run this automatically you might use Automator, or event better, follow the instructions in this SO answer: https://stackoverflow.com/a/13372744/347884
If you choose the second route, make sure your shell script is executable:
chmod a+x /path/to/script.sh

Have fun!


text:
Q: How to connect sensor to PC? I have made a sensor that produces a 4 bit output. I want to perform some logic based on patterns.
I was thinking if somehow I could give that 4 bit input to my computer, I could then write code to perform logic. But, the problem is, I have no idea how to do this.
How can I give a 4 bit input to the computer? Can I use USB or some other hardware?

A: You can use any IO port available on your computer. PCI(e), USB, Ethernet, parallel ports, RS-232, PS/2, game port, Firewire...you could use any of them, provided they are fast enough for the rate of data you must transfer.
If you want easy, the parallel port is the way to go. These are trivial to interface to TTL. Though, they are quite uncommon these days.
RS-232 is also pretty easy. You can use MAX232 to generate the +/- 12V signaling, and a UART (included in most microcontrollers) to build circuitry that speaks RS-232. Serial ports are also becoming quite uncommon. One solution is to use a USB <-> RS-232 IC like those made by FTDI, either by including one of their ICs in your circuit, or buying a pre-made cable with the FTDI IC included. This is how the Arduino implements its "USB" connection.
You can also use the RS-232 control lines as a bit-bang interface if you don't need high speeds.
There are also any number of data acquisition peripherals. Some have PCIe interfaces and are extremely fast and expensive. Some cost a few dollars on eBay and may have a USB interface. Without knowing more about your requirements it's impossible to make a specific recommendation.