text:
Q: current user is not getting signed out I am using two mode of user authentication google and sign in with email and password. When I sign In or login with google and then pressed on sign Out the user signed out successfully but when  I sign In or login with email password and then pressed on sign Out the user it throws an PlateformException error.
Here is my signout methode
 Future<void> signOutUser() async {
    await _googleSignIn.disconnect();
    await _googleSignIn.signOut();
    await _firebaseAuth.signOut();
  }

I am using Bloc so here is my cubit class
class LogoutCubit extends Cubit<LogoutState> {
  LogoutCubit() : super(LogoutInitial());

  void logOut() async {
    try {
      await FirebaseRepo.instance.signOutUser();
      emit(LogoutSuccessState());
    }on PlatformException catch (e) {
      print(e.toString());
      emit(LogoutUnSuccessState(message: e.message));
    }
    on FirebaseAuthException catch(e){
      emit(LogoutUnSuccessState(message: e.message));
    }
  }
}

here is my home screen
class HomeScreen extends StatelessWidget {
  User user;

  HomeScreen({this.user});

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          BlocConsumer<LogoutCubit, LogoutState>(
            builder: (context, state) {
              if (state is LogoutInitial)
                return Center(
                  child: Text("InitialState"),
                );
              else if (state is LogoutUnSuccessState)
                return Center(
                  child: Text(state.message),
                );
              return Container();
            },
            listener: (context, state) {
              if (state is LogoutSuccessState){
                Navigator.of(context)
                    .pushReplacement(MaterialPageRoute(builder: (_) => LoginOrSignUpScreen()));
              }
            },
          ),
          Text(user.email),
          ElevatedButton(
              onPressed: () => BlocProvider.of<LogoutCubit>(context).logOut(),
              child: Text('Sign out'))
        ],
      ),
    );
  }
}

and here is my console when i click on logout button.
Performing hot restart...
Syncing files to device CPH2001...
Restarted application in 2,912ms.
I/GED     (28464): ged_boost_gpu_freq, level 100, eOrigin 2, final_idx 15, oppidx_max 15, oppidx_min 0
W/DynamiteModule(28464): Local module descriptor class for providerinstaller not found.
I/DynamiteModule(28464): Considering local module providerinstaller:0 and remote module providerinstaller:0
W/ProviderInstaller(28464): Failed to load providerinstaller module: No acceptable module found. Local version is 0 and remote version is 0.
I/verse.filmmake(28464): The ClassLoaderContext is a special shared library.
I/chatty  (28464): uid=10286(com.kinoverse.filmmaker) AsyncTask #1 identical 1 line
I/verse.filmmake(28464): The ClassLoaderContext is a special shared library.
V/NativeCrypto(28464): Registering com/google/android/gms/org/conscrypt/NativeCrypto's 287 native methods...
W/verse.filmmake(28464): Accessing hidden method Ljava/security/spec/ECParameterSpec;->getCurveName()Ljava/lang/String; (greylist, reflection, allowed)
I/verse.filmmake(28464): Waiting for a blocking GC ClassLinker
I/verse.filmmake(28464): WaitForGcToComplete blocked ClassLinker on ClassLinker for 36.514ms
I/ProviderInstaller(28464): Installed default security provider GmsCore_OpenSSL
D/ColorViewRootUtil(28464): nav gesture mode swipeFromBottom ignore false downY 1256 mScreenHeight 2400 mScreenWidth 1080 mStatusBarHeight 54 globalScale 1.125 nav mode 3 event MotionEvent { action=ACTION_DOWN, actionButton=0, id[0]=0, x[0]=507.0, y[0]=1256.0, toolType[0]=TOOL_TYPE_FINGER, buttonState=0, classification=NONE, metaState=0, flags=0x0, edgeFlags=0x0, pointerCount=1, historySize=0, eventTime=1070309419, downTime=1070309419, deviceId=2, source=0x1002, displayId=0 } rotation 0
I/flutter (28464): PlatformException(status, Failed to disconnect., null, null)

A: When signing out with FirebaseAuth all you need to do is to call FirebaseAuth.instance.signOut(). You don't need to sign out from Google seperately.


text:
Q: Correlation matrix for panel data in Python I want to create a correlation matrix for a data panel. The dataframe contains data on 15 numerical variables on a monthly basis for 11 years.
I would like to know, if possible, how to generate a single correlation matrix for the variables of this type of dataframe.
The alternative I have in mind would be to generate one correlation matrix per year, but I would like to know if it is possible to make only one correlation matrix for the whole dataframe in case the number of years is very large (which would make it unfeasible to make one matrix for each year).
Thanks in advance.

A: IIUC, you're mainly looking for the corr method of a DataFrame. Consider this example:
import pandas as pd
import numpy as np
np.random.seed(0)

df = pd.DataFrame(np.random.rand(30, 5)).add_prefix("feature_")
df["year"] = np.repeat(["2012", "2013", "2014"], 10)

print(df.head()) # first 5 rows. Note that there are 30 rows
   feature_0  feature_1  feature_2  feature_3  feature_4  year
0   0.548814   0.715189   0.602763   0.544883   0.423655  2012
1   0.645894   0.437587   0.891773   0.963663   0.383442  2012
2   0.791725   0.528895   0.568045   0.925597   0.071036  2012
3   0.087129   0.020218   0.832620   0.778157   0.870012  2012
4   0.978618   0.799159   0.461479   0.780529   0.118274  2012

Subset the numerical columns you want to be in the cormat (in this case I use .filter to get just the "feature_X" columns) and use  DataFrame.corr:
cormat = df.filter(like="feature").corr()

print(cormat)
           feature_0  feature_1  feature_2  feature_3  feature_4
feature_0   1.000000   0.004582   0.412658   0.269969   0.151162
feature_1   0.004582   1.000000  -0.200808   0.140620  -0.138652
feature_2   0.412658  -0.200808   1.000000  -0.019439   0.284211
feature_3   0.269969   0.140620  -0.019439   1.000000  -0.063653
feature_4   0.151162  -0.138652   0.284211  -0.063653   1.000000

If you want to get a correlation matrix at a grouping of some other variable, you can use .groupby first.
annual_cormat = df.groupby("year").corr()

print(annual_cormat)
                feature_0  feature_1  feature_2  feature_3  feature_4
year
2012 feature_0   1.000000   0.359721  -0.266740   0.285998  -0.526528
     feature_1   0.359721   1.000000  -0.330484   0.180620  -0.580236
     feature_2  -0.266740  -0.330484   1.000000   0.262000   0.428895
     feature_3   0.285998   0.180620   0.262000   1.000000  -0.144745
     feature_4  -0.526528  -0.580236   0.428895  -0.144745   1.000000
2013 feature_0   1.000000   0.135499   0.704653   0.081326   0.453111
     feature_1   0.135499   1.000000  -0.385677   0.732700  -0.065941
     feature_2   0.704653  -0.385677   1.000000  -0.607016   0.143572
     feature_3   0.081326   0.732700  -0.607016   1.000000   0.107971
     feature_4   0.453111  -0.065941   0.143572   0.107971   1.000000
2014 feature_0   1.000000  -0.624004   0.056185   0.351376  -0.038286
     feature_1  -0.624004   1.000000   0.103911  -0.284685   0.266124
     feature_2   0.056185   0.103911   1.000000   0.249860   0.145773
     feature_3   0.351376  -0.284685   0.249860   1.000000  -0.347361
     feature_4  -0.038286   0.266124   0.145773  -0.347361   1.000000

redpajama_set_name: RedPajamaStackExchange


text:
Q: Configure IIS web config for my webapi app to use snapshop isolation Due to performance in our system (deadlocks, db reads are locked when db writes are in progress, etc) we want to try out snapshop isolation. I have read about snapshot isolation level, here. We use Entity Framework
I have set Snapshop isolation on the db and want to configure our web api apps to use this isolation for both reads and writes. How can I do this? I have read that this can be done in web.config but cannot find how..

A: According to the Entity Framework documentation, you need to use a transaction to set the isolation level:
using (var tx = myContext.Database.BeginTransaction(IsolationLevel.Snapshot)) {

   // Perform operations on the context...

   await myContext.SaveAsync();
   tx.Commit();
}

See also this answer for details on the defaults: essentially EF uses whatever the database has as its default transaction isolation level via IsolationLevel.Unspecified.


text:
Q: Get back to master view programmaticcally - StoryBoard - iPhone I am using standard UISplitViewController, but for iPhone devices I need get back from detail view to master view programmatically.
Pushing back via the navigation stack does not work since detail view controller and master view controller do have separated navigation controllers.
Is there any chance to accomplish that?


text:
Q: SwiftUI: ScrollView not working correctly with ForEach I am making a card game and I'm trying to fit cards into a ScrollView. I'm doing this by iterating through an array of cards and subsequently building the view for each card with CardView.
struct ContentView: View {
    @ObservedObject var viewModel = SetGameViewModel()

    var body: some View {
        VStack {
            ScrollView {
                LazyVGrid(columns: [GridItem(),GridItem(),GridItem(),GridItem()]) {
                    ForEach(viewModel.cards) { card in
                        CardView(card: card)
                            //Individual card gets built depending on its data.
                            .aspectRatio(2/3, contentMode: .fill)
                        }
                }
            }
            DealThreeCardsButton()
                .onTapGesture { viewModel.dealThreeCards() }
        }
    }
}

Each card has a specific number of symbols (and several other characteristics, but those are not the issue right now.) which it should show. ->
struct CardView: View {
    let card: SetGame.Card
    private var color: Color {
        switch card.content.color {
        case .green:
            return Color(.green)
        case .purple:
            return Color(.purple)
        case .red:
            return Color(.red)
        }
    }

    var body: some View {
        if card.isFaceUp {
            ZStack{
                RoundedRectangle(cornerRadius: 20)
                    .foregroundColor(.clear)
                RoundedRectangle(cornerRadius: 20)
                    .stroke(lineWidth: 2.0)
                    .foregroundColor(/*@START_MENU_TOKEN@*/.blue/*@END_MENU_TOKEN@*/)
                VStack {
                    CardContentView(content: card.content)
                        //The contents of the cards are created
                        .foregroundColor(color)
                    Text("\(card.id), n: \(card.content.number)")
                }
            }
        } else {
            RoundedRectangle(cornerRadius: 20)
                .foregroundColor(.blue)
        }
    }
}

private struct CardContentView: View {
    let content: SetGame.CardContent
    var body: some View {
        ForEach(1..<content.number+1) { _ in
            //This ForEach should create the number of symbols held by the card struct
            //However this seems to not work.
            ZStack {
                switch content.symbol {
                case .oval:
                    DrawCircle(fillType: content.fillType.rawValue)
                case .diamond:
                    DrawDiamond(fillType: content.fillType.rawValue)
                case .squiggle:
                    DrawSquiggle(fillType: content.fillType.rawValue)
                }
            }
        }
    }
}

When I run this, the View builds correctly. The image shows the id and the n (number of symbols that should be on the card.)
Correctly built view
However when I scroll down and back up, the View gets rebuilt incorrectly. The number of symbols seems to be completely random. This only happens when the ScrollView is of a certain length, so when the number of cards is over 30 cards (depending on their size.) The cards aren't getting mixed up because the id remains the same and n is also unchanged.
Refreshed and incorrectly rebuilt View
Am I missing something? It must be something to do with the way ScrollView and ForEach interact. It seems to be a problem with the CardContentView struct and the ForEach statement within it. I just don't know what.
These are the errors I'm getting after refreshing;

ForEach<Range, Int, ZStack<_ConditionalContent<_ConditionalContent<DrawCircle, DrawDiamond>, DrawSquiggle>>> count (3) != its initial count (2). ForEach(_:content:) should only be used for constant data. Instead conform data to Identifiable or use ForEach(_:id:content:) and provide an explicit id!

Below; the entire Model which holds the CardContent and Card structs along with the init that creates the cards array;
struct SetGame {
    private(set) var cards: Array<Card>
    private(set) var deck: Array<Card>

    init() {
        deck = []
        cards = []
        var id = 1
        var color = CardContent.Color.red
        var fillType = CardContent.FillType.hollow
        var symbol = CardContent.Symbol.oval
        while deck.count < 81 {
            if deck.count % 27 == 0 {
                switch color {
                case .red:
                    color = .green
                case .green:
                    color = .purple
                case .purple:
                    color = .red
                }
            }
            if deck.count % 9 == 0 {
                switch symbol {
                case .oval:
                    symbol = .diamond
                case .diamond:
                    symbol = .squiggle
                case .squiggle:
                    symbol = .oval
                }
            }
            if deck.count % 3 == 0 {
                switch fillType {
                case .hollow:
                    fillType = .shaded
                case .shaded:
                    fillType = .filled
                case .filled:
                    fillType = .hollow
                }
            }
            deck.append(Card(id: id, content: CardContent(number: 1, color: color, fillType: fillType, symbol: symbol)))
            deck.append(Card(id: id+1, content: CardContent(number: 2, color: color, fillType: fillType, symbol: symbol)))
            deck.append(Card(id: id+2, content: CardContent(number: 3, color: color, fillType: fillType, symbol: symbol)))
            id += 3
        }
        //deck.shuffle()
        while cards.count < 81 {
            //When cards.count > 28; the view starts bugging
            cards.append(deck.popLast()!)
        }
    }

    mutating func dealThreeCards() {
        for _ in 0...2 {
            if deck.isEmpty {
                break
            } else {
                cards.append(deck.popLast()!)
            }
        }
        print("I was called :)")
    }

    struct Card: Identifiable {
        var isFaceUp = true
        var isMatched = false
        let id: Int
        let content: CardContent
    }

    struct CardContent: Equatable {
        let number: Int
        let color: Color
        let fillType: FillType
        let symbol: Symbol
        enum Color { case red, green, purple }
        enum FillType: Double {
            case hollow = 0.0
            case shaded = 0.2
            case filled = 1.0
        }
        enum Symbol { case oval, diamond, squiggle }
    }
}

Below; the entire ViewModel which is used in the ContentView. The app is extremely simple, yet I don't understand what's not working.
class SetGameViewModel: ObservableObject {
    @Published private(set) var game: SetGame

    init() {
        game = SetGame()
    }

    var cards: Array<SetGame.Card> {
        game.cards
    }

    func dealThreeCards() {
        game.dealThreeCards()
        print("I was called :)))")
    }
}

Minimal Reproducible Example
Main:
import SwiftUI

@main
struct mreApp: App {
    var body: some Scene {
        let game = ViewModel()
        WindowGroup {
            ContentView(viewModel: game)
        }
    }
}

Model:
import Foundation

struct CardGameModel {
    private(set) var cards: Array<Card>
    private(set) var deck: Array<Card>

    init() {
        //the init only takes care of creating the two arrays
        //deck and cards. It seems to be working correctly and nothing
        //is wrong here, I believe.
        deck = []
        cards = []
        var id = 1
        var color = CardContent.Color.red
        var fillType = CardContent.FillType.hollow
        var symbol = CardContent.Symbol.oval
        while deck.count < 81 {
            if deck.count % 27 == 0 {
                switch color {
                case .red:
                    color = .green
                case .green:
                    color = .purple
                case .purple:
                    color = .red
                }
            }
            if deck.count % 9 == 0 {
                switch symbol {
                case .oval:
                    symbol = .diamond
                case .diamond:
                    symbol = .squiggle
                case .squiggle:
                    symbol = .oval
                }
            }
            if deck.count % 3 == 0 {
                switch fillType {
                case .hollow:
                    fillType = .shaded
                case .shaded:
                    fillType = .filled
                case .filled:
                    fillType = .hollow
                }
            }
            deck.append(Card(id: id, content: CardContent(numberOfShapes: 1, color: color, fillType: fillType, symbol: symbol)))
            deck.append(Card(id: id+1, content: CardContent(numberOfShapes: 2, color: color, fillType: fillType, symbol: symbol)))
            deck.append(Card(id: id+2, content: CardContent(numberOfShapes: 3, color: color, fillType: fillType, symbol: symbol)))
            id += 3
        }
        //deck.shuffle()
        while cards.count < 81 {
            //When cards.count > 28; the view starts bugging.
            //However it also depends on the amount of columns in the
            //LazyVGrid. If more columns are included, the number of cards
            //displayable before bugs is greater.

            //Optional
            cards.append(deck.popLast()!)
        }
    }

    struct Card: Identifiable {
        let id: Int
        let content: CardContent
    }

    struct CardContent: Equatable {
        let numberOfShapes: Int
        let color: Color
        let fillType: FillType
        let symbol: Symbol
        enum Color { case red, green, purple }
        enum FillType: Double {
            case hollow = 0.0
            case shaded = 0.2
            case filled = 1.0
        }
        enum Symbol { case oval, diamond, squiggle }
    }
}

ViewModel:
import Foundation

class ViewModel: ObservableObject {
    @Published private(set) var game: CardGameModel

    init() {
        game = CardGameModel()
    }

    var cards: Array<CardGameModel.Card> {
        game.cards
    }
}

View:
import SwiftUI

struct ContentView: View {
    @ObservedObject var viewModel: ViewModel

    var body: some View {
        ScrollView {
            LazyVGrid(columns: [GridItem(),GridItem(),GridItem(),GridItem()]) {
                ForEach(viewModel.cards) { card in
                    CardView(card: card)
                        .aspectRatio(2/3,contentMode: .fill)
                }
            }
        }
    }
}

struct CardView: View {
    let card: CardGameModel.Card
    private var color: Color {
        switch card.content.color {
        case .green:
            return Color(.green)
        case .purple:
            return Color(.purple)
        case .red:
            return Color(.red)
        }
    }

    var body: some View {
        ZStack{
            RoundedRectangle(cornerRadius: 20)
                .stroke(lineWidth: 2.0)
                .foregroundColor(/*@START_MENU_TOKEN@*/.blue/*@END_MENU_TOKEN@*/)
            VStack {
                CardContentView(content: card.content)
                    //The contents of the cards are created
                    .foregroundColor(color)
                Text("\(card.id), n: \(card.content.numberOfShapes)")
            }
        }
    }
}

struct CardContentView: View {
    let content: CardGameModel.CardContent
    var body: some View {
        VStack {
            ForEach(0..<content.numberOfShapes) { _ in
                switch content.symbol {
                case .oval:
                    Circle()
                case .squiggle:
                    RoundedRectangle(cornerRadius: 35.0)
                case .diamond:
                    Rectangle()
                }
            }
        }
    }

}

A: In CardContentView add in the ForEach the id identifier as the error message requests it:
ForEach(0..<content.numberOfShapes, id: \.self) { _ in
       ...
}

Tested and working.


text:
Q: jQuery Fixed Header Table doesn't work with Angular2 ngFor I need to create table in Angular2  with fixed header and left (or right) column scrollable vertically and horizontally (both bars should be visibile all the time) and auto width columns. I've tried to do this without jQuery but eventually I had to use it. I found plugin Fixed Header Table. However it doesn't work with ngFor- header doesn't scroll horizontally and left column is not fixed. Without ngFor it works correctly.

           col1
            ...

               {{item.arg1}}
                  ...

...
export class itemComponent implements OnInit{

       ngOnInit(){
          $('#tableId').fixedHeaderTable({fixedColumn: true});
       }
}


text:
Q: How to detect Javascript pop-up notifications in WatiN? I have a, what seems to be, rather common scenario I'm trying to work through.
I have a site that accepts input through two different text fields. If the input is malformed or invalid, I receive a Javascript pop-up notification.
I will not always receive one, but I should in the event of (like I said earlier) malformed data, or when a search result couldn't be found.
How can I detect this in WatiN?
A quick Google search produced results that show how to click through them, but I'm curious as to whether or not I can detect when I get one?
In case anyone is wondering, I'm using WatiN to do some screen scraping for me, rather than integration testing :)
Thanks in advance!
Ian

A: Here's what I came up with.
I read this question several times before I came up with the obvious solution..
Can I read JavaScript alert box with WatiN?
This is the code I came up with.. While it does force a delay of 3 seconds if the alert doesn't happen, it works perfectly for my scenario.
Hope someone else finds this useful..
frame.Button(Find.ByName("go")).ClickNoWait();

System.Diagnostics.Stopwatch stopwatch = new System.Diagnostics.Stopwatch();
stopwatch.Start();

while (stopwatch.Elapsed.TotalMilliseconds < 3000d)
{
    if (alertDialogHandler.Exists())
    {
        // Do whatever I want to do when there is an alert box.
        alertDialogHandler.OKButton.Click();
        break;
    }
}


text:
Q: How to calculate branch instruction in powerpc programing environment : vxworks +powerpc
branch instruction:
b targetaddress

NIA = CIA+ EXTS(LI||0b00)

while NIA-CIA= 0x82fb7b4 = 1000 0010 1111 1011 0111 1011 0100

EXTS(LI) = 1000 0010 1111 1011 0111 1011 01

I followed the powerpc white paper book.
LI take only 24Bits . but i calculated 26 bits and i don't know how to trim it.

A: from https://www.ibm.com/docs/en/aix/7.2?topic=set-b-branch-instruction
The b instruction branches to an instruction specified by the branch target address. The branch target address is computed one of two ways.
Consider the following when using the b instruction:
If the Absolute Address bit (AA) is 0, the branch target address is computed by concatenating the 24-bit LI field. This field is calculated by subtracting the address of the instruction from the target address and dividing the result by 4 and b'00'. The result is then sign-extended to 32 bits and added to the address of this branch instruction.
If the AA bit is 1, then the branch target address is the LI field concatenated with b'00' sign-extended to 32 bits. The LI field is the low-order 26 bits of the target address divided by four.
The b instruction has four syntax forms. Each syntax form has a different effect on the Link bit and Link Register.


text:
Q: Marshaling list of objects containing maps of objects to JSON I have this object structure which I'm trying to annotate with Jackson to marshal/unmarshal to a JSON file.
public class A {
    List<B> bList;
}

public class B {
    String attr;
    Map<String, C> map;
}

public class C {
    @JsonIgnore
    String name;
    String value;
}

A has a list of B's and B has a map of C's where the key of the map is the name attribute of C. I want the JSON to look like this if possible:
{
    "bList" : [
               {
                   "attr":"itsValue"
                   "KEY_IN_MAP":"VALUE_IN_C",
                   "KEY_2_IN_MAP":"VALUE_2_IN_C"
               }
               ]
}

Where KEY_IN_MAP is the name of C as the key in B's map and VALUE_IN_C is the value of the value object in the map. I've tried annotating a put method for the map:
@JsonAnySetter
private void put(String name, C value) {
    map.put(name, c);
}

But marshaling this gives me:
{
    "bList" : [
               {
                   "attr":"itsValue"
                   "KEY_IN_MAP": {
                       "value":"VALUE_IN_C",
                   },
                   "KEY_2_IN_MAP": {
                       "value":"VALUE_2_IN_C"
                   }
               }
               ]
}

Is there any way to get the above mapping with Jackson or any other JSON serializing library? My goal is to get rid of the redundancy of writing "value" every time and compress the file as much as possible.
The map in B could be turned into a list of C but I still need the mapping to be
{"name" : "value"} for each object C

A: Here are few suggestions that I have:

*

*Make your Map<String,C> to be a Map<String,String>.

*You can also make your Map<String,C> to be List<C>.

Please have a look at the other thread which discusses the same.


text:
Q: How to port-forward IPv6 in m0n0wall? How do i port-forward IPv6 packets in m0n0wall?
For example i want to forward traffic arriving on port 443 of my router to another IPv6 address:

*

*Interface: WAN

*Protocol: TCP

*External port range: 443

*Destination address: 2607:f8b0:4009:801::1053

*Destination port range: 443

*Description: https goes to secure server

Or for other kinds of services:

*

*Interface: WAN

*Protocol: TCP+UDP

*External port range: 3784

*Destination address: 2607:f8b0:4009:801::1058

*Destination port range: 3784

*Description: Ventrilo

IPv6 removes the need for NAT; but how do i port-forward?

Bonus Question
How do i port-forward IPv4 in m0n0wall?
For example i want to forward traffic arriving on port 443 of my router to another IPv4 address:

*

*Interface: WAN

*Protocol: TCP

*External port range: 443

*Destination address: 74.125.225.53

*Destination port range: 443

*Description: https goes to secure server

Or for other kinds of services:

*

*Interface: WAN

*Protocol: TCP+UDP

*External port range: 3784

*Destination address: 74.125.225.58

*Destination port range: 3784

*Description: Ventrilo

i know how to NAT to a private internal address, but my servers are not behind a NAT proxy - they are directly connected to the internet, each with a publically routable IPv4 address, e.g.
74.125.225.53

i want people to only have to know one address, e.g.:
superuser.com -> 64.34.119.12

but have my m0n0wall router forward the packets to the appropriate machine.
Extraneous bonus chatter
i have a web-server that is directly connected to the internet using IPv6, listening on port 80.
In the olden days i would give people one address:

superuser.com

and that address resolves to a router, which forwards packets to the appropriate machine.
But with the advent of IPv6, and the removal of NAT, it is no longer possible to give people on address name, e.g.:

*

*http://superuser.com

*irc://superuser.com

*ftp://superuser.com

*news://superuser.com

*https://superuser.com

*ventrilo://superuser.com

*torrent://superuser.com
doesn't work. That's because superuser.com resolves to the same IPv6 address, e.g.:
2607:f8b0:4009:801::100e

And the other servers are on other addresses:
http      -> 2607:f8b0:4009:801::1031
irc       -> 2607:f8b0:4009:801::1041
ftp       -> 2607:f8b0:4009:801::1059
news      -> 2607:f8b0:4009:801::1026
https     -> 2607:f8b0:4009:801::1053
ventrilo  -> 2607:f8b0:4009:801::1058
torrent   -> 2607:f8b0:4009:801::1097

So a user is now forced to memorize other address names, e.g.:
www.superuser.com
wwws.superuser.com
ventrilo.superuser.com
torrent.superuser.com
irc.superuser.com
news.superuser.com

rather than the single:
superuser.com

for everything.
i like only having to know one name. i want that back again. How do i get it back again? How do i port-forward in IPv6?

Update 2:
Another issue is when multiple host names are supposed to be the same server
http://www.superuser.com:80
http://m.superuser.com:80
http://mobile.superuser.com:80
http://english.superuser.com:80
http://spanish.superuser.com:80
http://latin.superuser.com:80
...

What i really want is just:
*.superuser.com

to resolve to the same address, and :80 is forwarded to the server.

A: I think what you are looking for could be a load balancer.
But i dont think m0n0wall has one.

A: First part
There is no NAT in IPv6 (or at least there shouldn't be). So you will not be forwarding ports. You have a few options to do the equivalent of the port translation you are used to in IPv4:

*

*Use an identical port on the destination machine (which it looks like you are doing) so you don't need the port translated. You will only need to create a firewall rule to allow access to that port. No translation of address is needed either.

*Use a port proxy to translate TCP or UDP ports and addresses. Static NAT essentially.

Bonus part 1
Exact same situation here in IPv4 without NAT as in the above response regarding IPv6 without NAT.
Bonus Part 2
I do not recommend routing based on port. Routing based on port number is against the paradigms of networking. Routing should be based on address. And that address may be based on DNS. There are extensions to DNS to specify services and ports known as SRV records but they do not exist for all servers (like HTTP or SSH).
If you must route on port, then again, you can use port proxies to redirect certain TCP or UDP services to other machines.
Bottom Line:
Do not route based on port; route based on address. Sorry but that means you need separate DNS entries for each service.


text:
Q: Coded UI - Another control is blocking the control I'm new to Coded UI automation testing. In my MVVM silvelight application, doing automation testing for HyperlinkLink button and facing below error (see image):

Stack Trace:
at Microsoft.VisualStudio.TestTools.UITest.Playback.Engine.IScreenElement.MouseButtonClick(Int32 x, Int32 y, Int32 nButton, Int32 fEnsureVisible, String bstrKeyModifiers)
at Microsoft.VisualStudio.TestTools.UITest.Playback.ScreenElement.MouseButtonClick(Int32 x, Int32 y, MouseButtons button, ModifierKeys modifierKeys, Int32 ensureVisible)
at Microsoft.VisualStudio.TestTools.UITest.Playback.ScreenElement.MouseButtonClick(Int32 x, Int32 y, MouseButtons button, ModifierKeys modifierKeys)
at Microsoft.VisualStudio.TestTools.UITesting.UITestControl.Click(MouseButtons button, ModifierKeys modifierKeys, Point relativeCoordinates)
Error Message:
Another control is blocking the control. Please make the blocked control visible and retry the action. Additional Details:
TechnologyName: 'Silverlight'
ControlType: 'Image'
Source: '../Assets/Images/add.pn
Please Help..!!

A: This can happen when there is a transparent control overlaid on the control you are trying to click - First, make sure that no other windows are covering what you're trying to work with and then you can do the (slightly less reliable) version of Mouse.Click() which clicks on a point on the screen instead of clicking on the control. To do so, pass in a Point to the .Click method -
Mouse.Click(uIAssertsImagesaddpngImage.GetClickablePoint());

The downside to doing this is that if there is actually another window or control over top of the button you're trying to click, you're going to end up clicking on it instead. That's where the loss of reliability comes in.

A: Use Mouse.Hover() to demonstrate access to the control, and then Mouse.MoveScrollWheel() to move the location of the control to a place where it can be manipulated.
Background:
This is the first internet result on SO for FailedToPerformActionOnBlockedControlException that involves browser automation (as opposed to a desktop application) so I'm going to add my solution here. It does not involve Silverlight, but I'm not certain that matters.
For me, I would attempt to manipulate an element on the page, but that element was "below" the screen. Using any number of CodedUI methods that are supposed to grab the control (like .SetFocus()) would grab the appropriate control. However it would bring the control to the bottom part of the screen, where a semi-transparent bar across the bottom of the screen would block the control. Wanting to adjust where the control would be displayed on the screen, I attempted to use Mouse.MoveScrollWheel(), but the mouse action would not occur. Using Keyboard.SendKeys("{PGDN}") would not work either since CodedUI focus was "trapped" in a control. This particular application uses three browser windows (not tabs) open simultaneously, so mouse focus never made it onto the screen without something to trigger it. I eventually got around all of this using the following code
System.Drawing.Point location = obj.BoundingRectangle.Location;
Mouse.Hover(location);
Mouse.MoveScrollWheel(-2);


text:
Q: Send & retrive data from Remote server through javascript I created system that count my website visitor through javascript that's working fine But Now I want to show live Total Number of Visitor in my advertise which is in my other websites
So Please anybody can help me that how can I do this Or How can I Get data from my first website javascript data to my another website
I searched many thing in google but it do not answering my question
Thanks in Advance

A: Assuming all sites are served by the same host:

*

*send site visits to the server via AJAX or http POST (plenty of tutorials on how to do this

*store total visits in a database

*have your other site show this data (again Ajax or http post)
These are fairly trivial things to do and there is a ton of tutorials out there, I'd suggest w3schools as a starting point.


text:
Q: Class Property Not be included as sqlite database column I have one entity class as
  public class someclass
  {
      public string property1 {get; set;}
      public string property2 {get; set;}
      public string property3 {get; set;}
  }

and using sqlite connection class obj DB I am creating the table
  Db.CreateTableAsync<someclass>().GetAwaiter().GetResult();

What I want to achieve is, I don't want sqlite to create column in the table for property3. Is there any way to achieve this?
I am using SQLiteAsync library for windows store apps.

A: You can use the Ignore attribute:
public class someclass
{
    public string property1 { get; set; }
    public string property2 { get; set; }
    [Ignore]
    public string property3 { get; set; }
}

A: As chue x has said previously, you should use the Ignore attribute, but I figured I would give a bit more information as to what all the attributes do since it seems like some information that would be useful in this thread.
Here's a quick summary of the types of attributes available for use (for those of you that don't like reading and just want to know quickly):
PrimaryKey - This property is the primary key of the table. Only single-column primary keys are supported.
AutoIncrement - This property is automatically generated by the database upon insert.
Indexed - This property should have an index created for it.
MaxLength - If this property is a String then MaxLength is used to specify the varchar max size. The default max length is 140.
Ignore - This property will not be in the table.
If you want to know more, check out my more in depth blog post on these attributes:
http://lukealderton.com/blog/posts/2016/august/sqlite-attributes-and-what-they-do.aspx


text:
Q: Escape sequence for % character I have a following code which works fine.
a = 5
b = "%"
print "Hello %d \%s" % (a ,b)

Output:
$ python a.py
Hello 5 \%

But if i try to write code in this way
a = 5
print "Hello %d \%" % a

It is giving error, it seems escape sequence in not working for '%'
  File "a.py", line 2, in <module>
    print "Hello %d \%" % a
ValueError: incomplete format

To be more accurrate, it thier is any way to enter '%' character in 2nd programm.

A: Yes, it is called format escaping.
>>> print 'hello %s %%' % 5
hello 5 %

You just need to use 2 %.
Documentation:

'%%'  No argument is converted, results in a '%' character in the
  result.

A: Use new-style string formatting:
print "Hello {} %".format(a)

This method of string formatting is the new standard in Python 3, and should be preferred to the % formatting in new code.

Or a double %:
print "Hello %d %%" % a

A: When you use string formatting ("some %s" % ('string')), the % character has to be escaped. To do that, just use %%.
If you string is not formatted, you don't have to do that.
See this guide on string formatting.


text:
Q: How to account for temporal autocorrelation in a hierarchical generalized additive model (HGAM/GAMM) with a negative binomial distribution? I am using a harvest data set (count data) that I am trying to infer population abundance from. This data set contains annual harvest estimates from 20 Zones of varying areas, spanning 34 years. While catch-per-unit-effort is often used as a response variable in similar analyses, I would like to model Effort as a predictor variable and keep my harvest data (Catch) as counts. I would also like to include annual Price as a predictor variable in the model.
Based on diagnostic plots, it is clear that my data fit a negative binomial distribution better than a poisson. There are not many zeros in my data either (~2%).
As of right now, I have separated my data into training (first 27 yrs) and testing (last 7 yrs) data sets. To account for the different areas within each zone, I divided Effort by the area (i.e., Effort_km2) of each Zone. I then scaled and centered the Effort_km2 and Price variables (mean=0, sd=1), and only centered the year data around 0. This is my general model structure using the gam function in the mgcv package:
log_area <- log(area)

m1 <- gam(Catch ~ s(Effort_km2, bs="tp") +
                  s(Price, bs="tp") +
                  s(Year, bs="tp") +
                  s(Year, by=Zone, m=1, bs="tp") +
                  s(Zone, bs="re", k=20) +
                  offset(log_area),   #control for different sized Zone areas
                data = dat,
                family = nb(link="log"),
                method = "REML")

Here, I fit a global smoother for year, as well as a group smoother for each zone that will allow for the wiggliness to vary by zone.
When I examine the normalized residuals from this model using acf function, I see evidence of temporal autocorrelation unless I increase the basis size (k values) of the Price and the two Year covariates up to their near-maximum values (e.g., s(Year, bs="tp", k=25)). (Similarly, the k.check function indicated the k-values need to be that high.) I saw mentioned in a tutorial (by Gavin Simpson) that this would indicate that the model is basically modeling the autocorrelation in the data, which should be accounted for in a different way. I should also note that there are a few NAs in my data.
So my question is how can I develop a GAMM with a negative binomial distribution that can account for temporal autocorrelation? I tried the following model using the gamm function:
th1 <- m1$family$getTheta # estimate theta

m2 <- gamm(Catch ~ s(Effort_km2, bs="tp") +
                  s(Price, bs="tp") +
                  s(Year, bs="tp") +
                  s(Year, by=Zone, m=1, bs="tp") +
                  offset(log_area),   #control for different sized Zone areas
                data = dat,
                correlation = corCAR1(form = ~ Year | Zone)
                random=list(Zone=~1),
                family = negbin(theta=th1),
                method = "REML",
                niterPQL = 1000)

However, I get an error message about singularity, which I think comes from having the two Year covariates. Is there a way to specify the year terms to get both 'global' and 'group-level' smoothers? And is there a better way to specify the autocorrelation structure? Any suggestions about how to best proceed would be really wonderful. Thanks!

A: Autocorrelation can be seen as a trend in a time series, albeit a wiggly one. Hence you can just crank up the k if you want to get the residuals as independent as possible.
Effort should be included as an offset term using + offset(log(Effort_km2)) in the model formula. This turns the model into one for the response on the catch per unit effort scale. Making Effort_km2 a smooth term in the model is saying that the effort itself affects the response in a non-linear way. Using the offset gets a model for  $\frac{\text{catch}}{\text{effort}}$, without you having to modify the response counts themselves. You can combine multiple variables in the offset term, so you can include Effort and Area by summing the log effort and log area terms.
If the fit is returned, you're just getting a singularity warning, look where the singularity os coming from. Often in these models it's the correlation term that can't be identified with a wiggly trend also in the model, for reasons due to the fact described above in my first paragraph. If you get a returned model, you can check this by looking at the estimate CAR(1) term and it's confidence interval with the intervals() function applied to the $lme component of the model fit.
You can also try simpler models and build up from there; it is likely too that the multiple Year smooths are causing you fitting problems. Instead, try a model with just one Year smooth: s(Year, by = zone, bs = "tp") so that you just get a separate smooth per zone without the global smooth.


text:
Q: Attempting to calculate cost when button is clicked - value not updating I've coded a simple ordering system where you 'select' an integer from a number input, and then when you click on an 'update' button, it alters the inner text of a paragraph element below it. However, I've tried two methods:

*

*plain JavaScript for orderQuantity - innerHTML doesn't update

*parseInt for orderQuantity - returns £NaN in innerHTML

Please can someone point out where I'm going wrong?
Here's the code:

let orderQuantity = parseInt(document.getElementById("order-stepper").value);
let orderText = document.getElementById("order-value");
let orderValue = 2.50;
let orderAmount =  orderValue * orderQuantity;
let updateButton = document.getElementById("order-update");

function update() {
  orderText.innerHTML = ("Total cost: £" + orderAmount);
}

updateButton.addEventListener("click", update);
.order-stepper {
  width: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
}

.order-stepper label {
  font-size: 20px;
  margin: 30px 20px;
}

.order-stepper input {
  font-size: 18px;
  background-color: #f9f9f9;
  color: #999;
}

.order-price {
  width: 80%;
  display: flex;
  align-items: center;
  justify-content: center;
}

#order-value {
  font-size: 28px;
}

#order-update {
  height: 60px;
  width: 300px;
  display: flex;
  align-items: center;
  justify-content: center;
  margin: 30px 0;
  border: 3px solid #e2979c;
  border-radius: 5px;
  font-size: 2rem;
  font-weight: bold;
  background-color: #fff;
  cursor: pointer;
}

#order-update:hover {
  background-color: #e2979c;
}

          Select your quantity
          <input id="order-stepper" type="number" name="quantity" value="" max="3">

        <button id="order-update" type="button" name="button">Update</button>

Total cost: £0

Thanks.

A: You should move the variables inside the function. The variables have been initialized just once and are not updating with the changing value of the text box so you don't get any value when you click update.

let updateButton = document.getElementById("order-update");

function update() {
    let orderQuantity = parseInt(document.getElementById("order-stepper").value);
    let orderText = document.getElementById("order-value");
    let orderValue = 2.50;
    let orderAmount =  orderValue * orderQuantity;

  orderText.innerHTML = ("Total cost: £" + orderAmount);
}

updateButton.addEventListener("click", update);
.order-stepper {
  width: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
}

.order-stepper label {
  font-size: 20px;
  margin: 30px 20px;
}

.order-stepper input {
  font-size: 18px;
  background-color: #f9f9f9;
  color: #999;
}

.order-price {
  width: 80%;
  display: flex;
  align-items: center;
  justify-content: center;
}

#order-value {
  font-size: 28px;
}

#order-update {
  height: 60px;
  width: 300px;
  display: flex;
  align-items: center;
  justify-content: center;
  margin: 30px 0;
  border: 3px solid #e2979c;
  border-radius: 5px;
  font-size: 2rem;
  font-weight: bold;
  background-color: #fff;
  cursor: pointer;
}

#order-update:hover {
  background-color: #e2979c;
}

  Select your quantity
  <input id="order-stepper" type="number" name="quantity" value="" max="3">

<button id="order-update" type="button" name="button">Update</button>

Total cost: £0

A: I agree with putting variables inside the function.  You may be able to clean up the code and make it safer by replacing the lets with consts, using the parseInt() shorthand +, and using element.textContent instead of element.innerHTML for security.
document.getElementById("order-update").addEventListener("click", update);

function update() {
    const orderQuantity = +document.getElementById("order-stepper").value;
    const orderText = document.getElementById("order-value");
    const orderValue = 2.50;
    const orderAmount = orderValue * orderQuantity;
    orderText.textContent = ("Total cost: £" + orderAmount);
}

In addition, if you import the JS file in the head, make sure to defer it so it does not break your listener.

    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <link rel="stylesheet" href="app.css">


text:
Q: Make 2 Create Line From in 1 Window iDempiere I need customization to make 2 different Create Line From in 1 Window. The reason I need to make this because the security for our client because the behavior to take data is different from the original.
I have already read some suggestion in this topic Adempiere - How to design/call 2 CreateLinesFrom button in Same window
But still need the details, how I can do it properly?
Thanks

A: Resolved
This link will help https://groups.google.com/forum/#!topic/idempiere/MMGlpMunsLM
Summary from the link :

*

*Make Column CreateFromOther

*Generate model

*Make new Class ICreateFromOtherFactory copy from ICreateFromFactory and just change create become createOther

*Make new Class WCreateFromOtherFactory copy from WCreateFromFactory and change all code ICreateFromFactory become ICreateFromOtherFactory and create become createOther

*Deploy fragment for org.adempiere.ui.zk and change the code in AbstratctADWindowContent actionButton0

*Make plugin CreateFromOther extends CreateFrom and WCreateFromOther extends CreateFromOther

*Make Factory for this plugin reference to ICreateFromOtherFactory

*Make Component Definition and include the services ICreateFromOtherFactory

Thanks


text:
Q: how to implement pagination correctly? I am currently working on an MVC4 application that accesses a set of wcf services which delivers content.
I have a page that lists products. This page has a pagination feature called infinite scrolling, so as you scroll down the page, products are loaded.
I am wondering what is the best way to achieve such a pagination feature. The data source is sql server. Options as I see it are:

*

*Paginate at the sql server 2012 layer - returning only the required recordset and feed it back up the stack through wcf and in to the MVC application to display

*As option 1 but also include caching at the WCF layer so that the recordset is cached long term. This will mean though that a number recordsets will be stored in cache instead of one large one

*Cache all the data, and paginate the cached items, returning the subset from the WCF services cached data

Note: I am using asp.net for caching.
So I am looking for feedback as to the best practice for this.

A: How big is your possible dataset?  That I think would be the concern with caching, if it's feasible to hold it all in memory, then do option 3, I don't see the point of option 2, as if you cache for long term, you will most likely get to caching everything anyway. If you want to implement #2, I would cache for a short period of time (the timeframe would depend on how busy the site is).

A: When i tried this for test purposes i followed this guide: http://www.gavindraper.co.uk/2012/05/10/infinite-scroll-with-asp-net-mvc-4/
I dont know if it's the best way of implementing infinite scroll but it's at least a proof of concept.


text:
Q: why react javascript const object's members can be modified As here shows
// allowed
const helloWorld = {
  text: 'Welcome to the Road to learn React'
};
helloWorld.text = 'Bye Bye React';

works.
But why helloworld, as a constant object, its member can be modified? what is essentially const mean in react javascript?

A: The const declaration creates a read-only reference to a value.
when you are assigning an object to a const. you are creating a reference to that object.
const helloWorld = {
   text: 'Welcome to the Road to learn React'
};

Now const helloWorld does not know about the implementation or inner structure what it is holding. Javascript just has told to "helloWorld" that "I am giving you this object, hold it. and Listen!!! man!!!,, you are not supposed to hold anything else".
So, helloWorld does the same.
it holds the same object. But people can change the inner parts of the object.
Hence,
People can do following:
helloWorld.text = 'Bye Bye React';

Here helloWorld is still holding the same object. hellowWorld will allow you  to do anything with what it is holding. But, what it won't do is: "it won't drop it"
So, people can not do following:
helloWorld = "something else";

People cannot ask to helloWorld to hold something else.

A: Const will define a object no reassignable but we can edit properties in the object. Using const won't change the structure of the object.


text:
Q: Autoreconf failing when installing (py)COMPSs in a clusters I tried to install pyCOMPSs (v1.4) on a Cluster system using the
installation script for Supercomputers.
The script terminates with the following error:
libtool: link: ranlib .libs/libcbindings.a
libtool: link: ( cd ".libs" && rm -f "libcbindings.la" && ln -s
"../libcbindings.la" "libcbindings.la" )
make[1]: Entering directory
`/home/xxx/repos/pycompss/COMPSs/Bindings/c/src/bindinglib'
  /usr/bin/mkdir -p
'/home/cramonco/svn/compss/framework/trunk/builders/specs/deb/compss-c-binding/tmp/opt/COMPSs/Bindings/c/lib'
/usr/bin/mkdir: cannot create directory '/home/cramonco': Permission denied
make[1]: *** [install-libLTLIBRARIES] Error 1
make[1]: Leaving directory
`/home/xxx/xxx/repos/pycompss/COMPSs/Bindings/c/src/bindinglib'
make: *** [install-am] Error 2

BindingLib Installation failed, please check errors above!

A: Seems the error is due to the package includes a previous configuration
and in your case the autoreconf is not overwritting the Makefile and
other files produced by autotools.  try with
running
cd /home/xxx/repos/pycompss/COMPSs/Bindings/c/src/bindinglib
make maintainer-clean

After this run again the install command


text:
Q: Installing Windows 7 after installing Ubuntu I accidentally installed Ubuntu and now I am trying to install Windows 7 again, but when I go into BIOS, the only bootable device I can find is Ubuntu, and not the Windows 7 installation DVD I have inserted in my CD-ROM. How do I solve this?

A: On boot, try pressing F12 to set a temp boot device, and you should be able to boot off the DVD. You can also set the boot order in BIOS.

A: There is a key (usually F8-F12) that lets you pick which device you want to boot from. If you're using that and not seeing the DVD drive, check the boot order in the BIOS and make sure the DVD drive is enabled and added to the boot order.
If you can't see the drive in BIOS, check if it's accessible from Ubuntu, it might be faulty. Also, make sure to try another DVD, your Windows disc could be dead. (These might be stupid suggestions but they've worked for me a few times...)
Once you get the DVD working, if you haven't done anything with Ubuntu yet, it's probably best to wipe the disk and install Windows, then Ubuntu again. Getting Windows working alongside Linux is much harder than getting Linux working alongside Windows.


text:
Q: Isosceles triangles with integer side lengths whose vertices are lattice points I was wondering if such a triangle exists and I indeed found one: the triangle whose vertices are
$(0,0), (-33,56), (63,16)$. But is there a way to somehow "generate" these triangles? By the way, I'm only interested in isosceles triangles that don't have horizontal or vertical sides.
Here's what I've done so far:  To make things easier, I made the origin the vertex. The other vertices are denoted as $(a,b)$ and $(c,d)$, and $$a^2+b^2=c^2+d^2=r^2$$$$(a-c)^2+(b-d)^2=n^2$$ where $a, b, c, d, r, $ and $n$ are integers. The second equation becomes $$a^2-2ac+c^2+b^2-2bd+d^2=2r^2-2ac-2bd$$$$2(r^2-(ac+bd))=n^2$$
I don't know how to proceed from this. Any ideas?

A: Here is one method. Given two Pythagorean triples: $\,a^2+b^2=c^2\,$
and $\,d^2+e^2=f^2,\,$ use the first one to create an isosceles triangle with
vertices $\,(-a,0),(a,0),(0,b)\,$ and sides $2a,c,c.\,$ Regard each vertex
as a point in the complex plane and multiply each point by $\,d+ei\,$ to
get the triangle with vertices $\,(-ad,-ae),(ad,ae),(-be,bd)\,$ and sides multiplied by $\,f.\,$ This triangle will have horizontal or vertical
sides iff $\,\,a/b=d/e\,$ or $\, a/b=e/d.\,$


text:
Q: Exception while creating a COM object with comtype In one of my projects we are using comtypes to remote control GUI applications in order to automize testing. In case the tests are called manually everything seems to work smoothly, but in case jenkins is executing the test cases it might happen, that a strange OSError is thrown by
from comtypes.client import CreateObject

app=createObject("App")

The error reading is:
OSError: [WinError -2147467238] The server processs could not be started, as the configured identity is wrong. Check your username and password.

Does anyone know how it might be possible to fix this issue?

A: The error is stated here as
CO_E_RUNAS_LOGON_FAILURE
0x8000401A

Please use this answer to check which user is executing the script in your manual and automatized testing and I am quite sure they are different.


text:
Q: Securionpay checkout verify success Ok, I decided to use securionpay as a payment method.
What I'm struggling is I don't know how I can verify on my server that the payment was successful
<script src = "https://securionpay.com/checkout.js"> </script>
<script src="https:/ / ajax.googleapis.com / ajax / libs / jquery / 3.1.0 / jquery.min.js "></script>
<script type="
text / javascript ">
  $(function () {
    SecurionpayCheckout.key = 'pk_test_ZVhCjD2Gz7OF222L00bxIdlD';
    SecurionpayCheckout.success = function (result) {
      // handle successful payment (e.g. send payment data to your server)
    };
    SecurionpayCheckout.error = function (errorMessage) {
      // handle integration errors (e.g. send error notification to your server)
    };

    $('#payment-button').click(function () {
      SecurionpayCheckout.open({
        checkoutRequest: 'NTQ1NDAwYTczZTljMjUwYzNhZjA0NTdkOTFjNThiOTY5YzIxY2ViMjBhMDRmOTYwNjg1MDI3OWQ2OTZlN2VjMnx7ImNoYXJnZSI6eyJhbW91bnQiOjQ5OSwiY3VycmVuY3kiOiJFVVIifX0=',
        name: 'SecurionPay',
        description: 'Checkout example'
      });
    });
  });
</script>

<button id="payment-button">Payment button</button>

it goes like this

*

*user picks a product

*user clicks order(the request is going to my server where I create signed 'checkout request'

*I render javascript file with checkoutRequest filled

*User clicks 'Payment button'

*user fills card information and clicks Pay

*SecurtionpayCheckout.success run

whatever 'result' will return to me it doesn't help to verify it on the server. I only generate checkout request on the server side.
My thought is that my server should generate some variable that I would store in order model and 'result' should return me that variable if success then i could verify it otherwise based on what I can verify it ? I propably missing something...
docs:
https://securionpay.com/docs/tutorials/checkout
P.S I don't want to store card information on my server
Thanks

A: You should use metadata. Put whether data you need in checkoutRequest.charge.metadata attribute. It will be attached to charge and returned in result parameter in success method.


text:
Q: Save blank data in database using material design form using c# I've used material design form in html and I set EnableEventValidation=false after click save button to save data in sql server, however there is a blank data saved in sql server

Patient Information

        <input type="text" runat="server" id="Fname" required="required" />
        First Name

        <input type="text" runat="server" id="Lname" required="required" />
        Last Name

        <input type="text" runat="server" id="Address" required="required" />
        Address

        <input type="text" runat="server" id="city" required="required" />
        City

        <select runat="server" id="gender">
            <option>Male</option>
            <option>Female</option>
        </select>
        Gender

        Date Of Birth
        <input type="date" id="birth" runat="server" name="datePurchase" />

        <input type="text" runat="server" id="ssec" required="required" />
        Social Security

        <select runat="server" id="inppSel">
        </select>
        <input runat="server" type="hidden" style="color: red;" id="inpTxt" />
        Patient Case

        <button onserverclick="save" type="submit" class="button" id="addnew" runat="server">Submit</button>

C#:
DataBaseConnection db = new DataBaseConnection();
db.disconnect();

string sql1 = "INSERT INTO TBL_Persons VALUES( @First_Name, @Last_Name, @Address, @City)";

SqlCommand cmd1 = new SqlCommand(sql1, db.connect());
cmd1.Parameters.AddWithValue("@First_Name", Fname.Value);
cmd1.Parameters.AddWithValue("@Last_Name", Lname.Value);
cmd1.Parameters.AddWithValue("@Address", Address.Value);
cmd1.Parameters.AddWithValue("@City", city.Value);

cmd1.ExecuteNonQuery();

string sql2 = "INSERT INTO TBL_Patients VALUES(@Gender, @Date_OF_Birth, @Social_Security, @Person_ID, @Case_ID)";
db.disconnect();

string sql3 = "SELECT MAX(Person_ID) FROM TBL_Persons ";

SqlCommand cmd2 = new SqlCommand(sql3, db.connect());
int max = (int)(cmd2.ExecuteScalar());
db.disconnect();

SqlCommand cmd3 = new SqlCommand(sql2, db.connect());
cmd3.Parameters.AddWithValue("@Gender", gender.Items[gender.SelectedIndex].Text);
cmd3.Parameters.AddWithValue("@Date_OF_Birth", birth.Value);
cmd3.Parameters.AddWithValue("@Social_Security", ssec.Value);
cmd3.Parameters.AddWithValue("@Person_ID", max);
cmd3.Parameters.AddWithValue("@Case_ID", inpTxt.Value);

cmd3.ExecuteNonQuery();


text:
Q: How can I handle password input? I am managing user table by SonataAdminBundle
protected function configureFormFields(FormMapper $formMapper){
    $formMapper
    ->with('General')
     ->add('username')
     ->add('email')
     ->add('plainPassword','text',array('required' => false))

I leave password input blank,when I edit the existing user data.
It is OK,password is kept as same .
However I forgot to input password when I create new item.
It shows SQL error(password has required attribute in database)
but if I deleted required => false attribute,
->add('plainPassword','text')

it requires new input when you edit.
How can I change the behavior or How can I handle password
 input as normal input?

A: You should use different field type for create and update actions. In your configure configureFormFields:
protected function configureFormFields(FormMapper $formMapper)
{
    // ...

    if ($isCreateAction) {
        $formMapper->add('plainPassword','text');
    }
    else {
        $formMapper->add('plainPassword','text', array('required' => false));
    }
}

I don't know how to set $isCreateAction exactly, but maybe you could check Admin::getSubject() method? Inside it there is a routine to get GET id. If there is no id set, then action type is create.


text:
Q: Run terraform modules conditionally I am trying to run modules conditionally. Below is the code. It works fine if the values are provided but if var.accounts[*].vpc_ids is blank, it fails saying var.vpc_id can't be empty. But that is basically the condition based on which the modules should run. If the vpc_id count is 0, then the modules should not run. Please help.
resource "aws_ec2_transit_gateway_vpc_attachment" "this" {
   transit_gateway_id = var.transit_gateway_id
  vpc_id = var.vpc_id
  subnet_ids = var.subnet_ids
  dns_support                                     = "disable"
  ipv6_support                                    = "disable"
  transit_gateway_default_route_table_association = false
  transit_gateway_default_route_table_propagation = false
}

locals {
  create_tgw_attach = var.accounts[*].vpc_ids != "" ? true : false
}

module "tgw_peer2" {
  source = "../modules/tgw"
    count = length(var.accounts[2].vpc_ids)
  providers  = {
    aws = aws.accepter2
  }
  create_tgw_attach      = local.create_tgw_attach
  transit_gateway_id = aws_ec2_transit_gateway.this.id
  vpc_id = var.accounts[2].vpc_ids[count.index]
  subnet_ids = var.accounts[2].vpc_subnets[count.index].subnet_ids
  destination_cidr_block = var.destination_cidr_block_route

  share_tgw                             = true
  create_tgw                            = false
}

module "tgw_peer3" {
  source = "../modules/tgw"
  create_tgw_attach      = local.create_tgw_attach
  count = length(var.accounts[3].vpc_ids)
  providers  = {
    aws = aws.accepter3
  }
  transit_gateway_id = aws_ec2_transit_gateway.this.id
  vpc_id = var.accounts[3].vpc_ids[count.index]
  subnet_ids = var.accounts[3].vpc_subnets[count.index].subnet_ids

  share_tgw                             = true
  create_tgw                            = false
}

A: I was trying to put the condition of vpc_id which I was using as a value in the module. I modified the condition and it worked. Below is the code.
module "tgw_peer1" {
  source = "./modules/tgw"
  providers  = {
    aws = aws.accepter1
  }
  count = var.accounts[1].account_id != "" ? length(var.accounts[1].vpc_ids) : 0
  transit_gateway_id = aws_ec2_transit_gateway.this.id
  vpc_id = var.accounts[1].vpc_ids[count.index]
  subnet_ids = var.accounts[1].vpc_subnets[count.index].subnet_ids
}


text:
Q: local migrations not showing up on heroku I know this question has been asked before however, my issue is a bit different from those problems.
I am working on a project and added a few attributes to different models in different apps and I did migrations gradually. and everything worked fine.
I created a PR on a forked public branch and my client merged my branch into a testing branch.
Now the issue is that Heroku is not recognizing the migrations on the remote server.
I am using sqlite3 on my local development environment and PostgreSQL on the production environment.
Is Heroku serving the sqlite3 or PostgreSQL on production? or what can be the main issue?
NOTE : I am added as a collaborator and can't pull the local changes to the remote server and hence can't deploy the local changes to remote server.
UPDATE
the result of git remote -v
heroku  https://git.heroku.com/tarot-testing.git (fetch)
heroku  https://git.heroku.com/tarot-testing.git (push)
master  https://github.com/abubakarA-Dot/tarot_juicer.git (fetch)
master  https://github.com/abubakarA-Dot/tarot_juicer.git (push)
origin  https://github.com/abubakarA-Dot/tarot_juicer.git (fetch)
origin  https://github.com/abubakarA-Dot/tarot_juicer.git (push)
upstream        https://github.com/enoren5/tarot_juicer.git (fetch)
upstream        https://github.com/enoren5/tarot_juicer.git (push)

A: @djangodeveloper and I are on the same team working on the same project on GitHub.
The three methods for migrating a db on Heroku discussed in the comments so far include:

*

*Running $ heroku run python manage.py migrate

*Adding some paramaters to the Procfile

*Install a third party (unofficial) Buildpack

Here is one more method to consider (the one that I use):

*Run a remote AWS Postgres db locally.

It's as straightforward as running:
(local venv) $ export DATABASE_URL='postgres://USER:PASSWORD@HOST:PORT/NAME'

You can locate the DATABASE_URL with all the right variables specified inside the Heroku dashboard after revealing the config vars. All you need to do to get it working is to copy and paste that config var into your shell within the quotes. For a more in-depth explanation of how to use this technique, you can view the documentation in our GitHub project's README.md at the heading titled: "#3. Handling db remote instances but locally". Using this technique, after having exported the db in my local development environment, I ran:
(local venv) $ python manage.py migrate
Database Config: {'default': {'NAME': <redacted>, 'USER': <redacted>, 'PASSWORD': <redacted>, 'HOST': '<redacted>', 'PORT': 5432, 'CONN_MAX_AGE': 600, 'ENGINE': 'django.db.backends.postgresql_psycopg2'}}
Operations to perform:
  Apply all migrations: accounts, admin, auth, contenttypes, essays, generators, landings, sessions
Running migrations:
  Applying essays.0007_auto_20221107_2032... OK
  Applying essays.0008_auto_20221108_0627... OK
  Applying generators.0004_generator_is_published... OK
  Applying generators.0005_alter_generator_is_published... OK
  Applying landings.0005_auto_20221107_1312... OK
  Applying landings.0006_auto_20221108_0627... OK

As you can see  in the output at the bottom, the database has now been migrated successfully. In the Django Admin Dashboard, I can see all the data was preserved. Although there are new issues with the generators web app which will need to be handled separately outside the scope of the OP's original question. The staging version of the site otherwise is running beautifully now.
Back in September when Heroku began notifying their users that the free PostgreSQL and Hobby dynos were being phased out, I proactively moved both our staging and production PostgreSQL databases to Basic tiers costing $9.00/mo for each. I didn't lose any data and the transition so far has been seamless.
While the OP in the comment section shared his experience with a different Heroku project with PostgreSQL becoming unavailable and encountering data loss, I can confirm that was never the case with this project.
To this end, have a look at this output:
$ heroku pg:info -a tarot-testing
=== DATABASE_URL, COPPER_TESTING_URL
Plan:                  Basic
Status:                Available
Connections:           8/20
PG Version:            14.6
Created:               2022-10-02 13:50 UTC
Data Size:             11.1 MB/10.00 GB (In compliance)
Tables:                28
Rows:                  351/10000000 (In compliance)
Fork/Follow:           Unsupported
Rollback:              Unsupported
Continuous Protection: Off
Billing App:           tarot-prod
Add-on:                postgresql-lorem-2

As you can see, it was created on October 2nd (well before the change-over deadline at the end of November) and it is populated with some data.
Here is a screenshot from our project's Heroku Dashboard showing  further proof that our PostreSQL is online and configured properly:


text:
Q: iPhone Get UIImagePickerController Lat/Lng I'm using the UIImagePickerController to take a photo and then upload the photo to a WCF Service. Along with the image, I also need to send to the latitude and longitude of the photo.
How can I get hold of this information from the photo taken?
I've searched online but can't seem to find a good source of info. I've seen about the EXIF data that is passed through the UIImagePickerControllerMediaMetadata key as part of the didFinishPickingMediaWithInfo delegate method. However, when I print out the contents to the log, there's no location information.
Am I missing something, do I need to turn on location services prior to taking the photo? Or is there another way to get the information?
Many thanks.

A: New since iOS 8
It was complicated with ALAssetLibrary, which is now deprecated, use Photos.Framework instead.
func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : AnyObject]) {
    if let assertURL = info[UIImagePickerControllerReferenceURL] as? NSURL {
        let fetchResult = PHAsset.fetchAssetsWithALAssetURLs([assertURL], options: nil)
        if let asset = fetchResult.firstObject as? PHAsset
        {
            print(asset.location)
        }
    }
}

Quick and easy :)

A: I've been figuring this out for a couple of days, and finally got a solution. As already suggested, you can use ALAssetsLibrary.
The image picker will give you a dictionary, which contains an url that points to the asset.
The ALAssetsLibrary's assetForURL: resultBlock: failureBlock: method uses blocks. You can read more about them from example here.
So this is how we handle the info given by the picker:
- (void)imagePickerController:(UIImagePickerController *)picker
            didFinishPickingMediaWithInfo:(NSDictionary *)info
{

    if ([picker sourceType] == UIImagePickerControllerSourceTypePhotoLibrary) {
        // We'll store the info to use in another function later
        self.imageInfo = info;

        // Get the asset url
        NSURL *url = [info objectForKey:@"UIImagePickerControllerReferenceURL"];

        // We need to use blocks. This block will handle the ALAsset that's returned:
        ALAssetsLibraryAssetForURLResultBlock resultblock = ^(ALAsset *myasset)
        {
            // Get the location property from the asset
            CLLocation *location = [myasset valueForProperty:ALAssetPropertyLocation];
            // I found that the easiest way is to send the location to another method
            [self handleImageLocation:location];
        };
        // This block will handle errors:
        ALAssetsLibraryAccessFailureBlock failureblock  = ^(NSError *myerror)
        {
            NSLog(@"Can not get asset - %@",[myerror localizedDescription]);
            // Do something to handle the error
        };

        // Use the url to get the asset from ALAssetsLibrary,
        // the blocks that we just created will handle results
        ALAssetsLibrary* assetslibrary = [[[ALAssetsLibrary alloc] init] autorelease];
        [assetslibrary assetForURL:url
                       resultBlock:resultblock
                      failureBlock:failureblock];

    }
    [picker dismissModalViewControllerAnimated:YES];
    [picker release];
}

And next the method that handles the image and location data:
- handleImageLocation:(CLLocation *)location
{
    UIImage *image = [self.imageInfo objectForKey:UIImagePickerControllerOriginalImage];
    // Do something with the image and location data...
}

And of course you can also get other information about the image with this method by using keys:
ALAssetPropertyType
ALAssetPropertyLocation
ALAssetPropertyDuration
ALAssetPropertyOrientation
ALAssetPropertyDate
ALAssetPropertyRepresentations
ALAssetPropertyURLs

A: It's a 'bug', I guess. A UIImagePickerViewController won't return location data of the images you select from it: as you've discovered, they are stripped from the meta data.
However, if you use ALAssetLibrary to get your images you can get the location data (in the form of a CLLocation object associated with the image). There is some code in this question - iphone image ALAsset problem - that will help you get an ALAsset from a UIImagePickerController.
Of course, this would be easier if you could just get that information from the picker straight away, so consider filing a feature request with Apple.

A: As your source type would appear to be UIImagePickerControllerSourceTypeCamera, this gets very frustrating very quickly, as you already know. Location info appears to be MIA.
As an alternative to UIImageWriteToSavedPhotosAlbum() (which does not refer to the saved image) I've tried ALAssetsLibrary and -writeImageToSavedPhotosAlbum:metadata:completionBlock: (using UIImagePickerControllerMediaMetadata to populate it, hoping the framework would fill in the blanks with location info).
Alas, no such luck. Even though this method gives back a URL to the saved image, I still can't get ALAssetPropertyLocation info from it. Even if I use the orientation variant of the save method, it is of no use.
At this point, I think the only recourse would appear to be incorporating your own location info, as outlined here.
It seems somewhat fishy that I'd have to do this, however, as I would expect the framework to handle this for you automagically. In fact, I can't even get location info for previously taken photos. This is with all permissions granted in all the right places, no matter which device I use, iPhone or iPad. (Even the Camera app has proper permission, FWIW.)


text:
Q: How to prove this inequality for operator and function How to prove this?
$\sum_{k=1}^{\infty}|(Tf)_k|^2\leq ||T||^2||f||^2$
where $T$ is an operator and a function $f$. $(Tf)_k$ is the $k$-th coordinate of Tf.
Should this involve Cauchy-Schwarz or the inner product $< ,>$?
Thanks in advance.

A: The term on the left is
$$
     \|Tf \|^2
=    \left\|T \frac{f}{\|f\|} \right\|^2 \|f\|^2
\leq \sup\left\{ \left\|T g \right\| \mid \|g\|=1\right\}^2 \|f\|^2
=    \|T\|^2 \|f\|^2
$$

A: Here it is in a nutshell, sans my typical long-windedness;  note that, to make this one fly, Wilbur, we need to assume we are dealing with a separable Hilbert space, so we can invoke a countable orthonormal basis $\mathbf e_k$.  Also, I am obviously assuming that $(Tf)_k = \langle \mathbf e_k, Tf \rangle$.
1.)  $Tf = \sum_1^\infty \langle \mathbf e_j, Tf \rangle \mathbf e_j; \tag{1}$
2.)  $\langle Tf, Tf \rangle = \langle \sum_1^\infty \langle \mathbf e_j, Tf \rangle \mathbf e_j, \sum_1^\infty \langle  \mathbf e_k, Tf \rangle \mathbf e_k \rangle = \sum_{j, k = 1}^{j, k = \infty} \langle \mathbf e_j, \mathbf e_k \rangle \overline{\langle \mathbf e_j, Tf \rangle} \langle \mathbf e_k, Tf \rangle$
$= \sum_{j, k = 1}^{j, k = \infty} \delta _{jk} \overline{\langle \mathbf e_j, Tf \rangle} \langle \mathbf e_k, Tf \rangle = \sum_1^\infty \overline{\langle \mathbf e_k, Tf \rangle} \langle \mathbf e_k, Tf \rangle = \sum_1^\infty  \vert (Tf)_k \vert^2; \tag{2}$
3.)  Also, $\vert \langle Tf, Tf \rangle \vert \le \Vert Tf \Vert^2$ by Cauchy-Schwarz, and $\Vert Tf \Vert \le \Vert T \Vert \Vert f \Vert$, so $\vert \langle Tf, Tf \rangle \vert  \le \Vert T \Vert^2 \Vert f \Vert^2; \tag{3}$
Finally, combining (2) and (3) we have
4.)  $\sum_1^\infty \vert (Tf)_k \vert^2 \le \Vert T \Vert ^2 \Vert f \Vert^2, \tag{4}$
as was to be shown.  QED.
Hope this helps.  Cheerio,
and as always,
Fiat Lux!!!


text:
Q: Add or Update elements of an ArrayList based on another ArrayList I have two ArrayLists of ClassRoom object and below shows the ClassRoom class :
public class ClassRoom {

    private String className; // className is unique here
    private List<Student> students = new ArrayList<>();

    public ClassRoom(String className, List<Student> students) {
        this.className = className;
        this.students = students;
    }

    public String getClassName() {
        return className;
    }

    public void setClassName(String className) {
        this.className = className;
    }

    public List<Student> getStudents() {
        return students;
    }

    public void setStudents(List<Student> students) {
        this.students = students;
    }

    @Override
    public String toString() {

        String ss = "[";
        for (int i = 0; i < students.size(); i++) {
            ss += "{name:'" + students.get(i).getName() + "',age:" + students.get(i).getAge() + "}";
            ss += (i == (students.size() - 1)) ? "" : ",";
        }
        ss += "]";
        return "{'" + className + "':" + ss + "}";
    }

}

ClassRoom class contains className String property and List of Student object which describes below:
public class Student {

    private String name; // name is unique here
    private int age;

    public Student(String name, int age) {
        this.name = name;
        this.age = age;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

}

I have created my two lists of ClassRoom object like below :
List<ClassRoom> list1 = new ArrayList<>();

list1.add(new ClassRoom("A", Arrays.asList(new Student("Sam", 20), new Student("Peter", 40), new Student("Aaron", 15))));
list1.add(new ClassRoom("B", Arrays.asList(new Student("Ronnie", 33), new Student("Daniel", 41), new Student("Gabe", 35))));
list1.add(new ClassRoom("C", Arrays.asList(new Student("Fabian", 42), new Student("Edgar", 33))));
list1.add(new ClassRoom("D", Arrays.asList(new Student("Peter", 39), new Student("Calvin", 45))));

List<ClassRoom> list2 = new ArrayList<>();

list2.add(new ClassRoom("A", Arrays.asList(new Student("Sam", 26), new Student("Aaron", 18))));
list2.add(new ClassRoom("B", Arrays.asList(new Student("Daniel", 38), new Student("Eddy", 29))));
list2.add(new ClassRoom("C", Arrays.asList(new Student("Fabian", 42), new Student("Edgar", 33))));

So my final task is to create a new List of ClassRoom object like below :
List<ClassRoom> mergedList = merge(list1, list2);

for (ClassRoom classRoom : mergedList) {
    System.out.println(classRoom.toString());
    /* Expected output here
    {'A':[{name:'Sam',age:26},{name:'Peter',age:40},{name:'Aaron',age:18}]}
    {'B':[{name:'Ronnie',age:33},{name:'Daniel',age:38},{name:'Gabe',age:35},{name:'Eddy',age:29}]}
    {'C':[{name:'Fabian',age:42},{name:'Edgar',age:33}]}
    {'D':[{name:'Peter',age:39},{name:'Calvin',age:45}]}
   */
}

And below explains my merge method:
public static List<ClassRoom> merge(List<ClassRoom> listA, List<ClassRoom> listB) {

      ArrayList<ClassRoom> collect = Stream.of(listA, listB).collect(ArrayList<ClassRoom>::new, (item1, item2) -> {
          item2.forEach((c2) -> {
            item1.forEach((c1) -> {
                if (c2.getClassName().equalsIgnoreCase(c1.getClassName())) {
                    // Student list update goes here
                } else {
                    item1.add(c2);
                }
            });
        });
      }, (item1, item2) -> {

      });

    return collect;
 }

Problem I am having so far is resulting an empty list after the merge method call. Any suggestions would be appreciated.

A: *

*Override the equals and hashCode methods in Student on name.

@Override
public boolean equals(Object obj) {
    return Objects.equals(name, ((Student) obj).getName());
}

@Override
public String toString() {
    return "name: " + name + ", age: " + age;
}

*Override the equals and hashCode methods in ClassRoom using the default implementation suggested by your IDE.

*Collect list2 into a Map<String, List<Student>> map and process each element of list1 as shown below:

Map<String, List<Student>> map = list2.stream()
            .collect(Collectors.toMap(ClassRoom::getClassName, ClassRoom::getStudents));

list1.forEach(e -> map.merge(e.getClassName(),
                                Stream.of(map.getOrDefault(e.getClassName(), e.getStudents()), e.getStudents())
                                .flatMap(List::stream)
                                .distinct()
                                .collect(Collectors.toList()),
                                    (v1, v2) -> v2)
                            );

Output:

{A=[name: Sam, age: 26, name: Aaron, age: 18, name: Peter, age: 40],
B=[name: Daniel, age: 38, name: Eddy, age: 29, name: Ronnie, age: 33,
name: Gabe, age: 35], C=[name: Fabian, age: 42, name: Edgar, age: 33],
D=[name: Peter, age: 39, name: Calvin, age: 45]}

ONLINE DEMO

A: You can do like this:
public static List<ClassRoom> merge(List<ClassRoom> listA, List<ClassRoom> listB) {
    Map<String, Set<Student>> map = new HashMap<>();
    listA.forEach(item -> map.put(item.getClassName(), new HashSet<>(item.getStudents())));
    for (ClassRoom classRoom : listB) {
        Set<Student> set = map.getOrDefault(classRoom.getClassName(), new HashSet<>());
        set.addAll(classRoom.getStudents());
        map.put(classRoom.getClassName(), set);
    }
    List<ClassRoom> list = new ArrayList<>();
    map.forEach((k, v) -> list.add(new ClassRoom(k, new ArrayList<>(v))));
    return list;
}

and add below in Student:
@Override
public boolean equals(Object o) {
    if (this == o) return true;
    if (!(o instanceof Student)) return false;
    Student student = (Student) o;
    return getName() != null ? getName().equals(student.getName()) : student.getName() == null;
}
@Override
public int hashCode() {
    return getName() != null ? getName().hashCode() : 0;
}


text:
Q: How can I run a Haskell file using window's powershell? I downloaded chocolatey and am able to load up ghci and get prelude on powershell.
I then cd into the directory where I have a haskell file I want to run, then I type ghci and then type:
load haskellprogram.hs

but then I get an error about it not being in scope.
Is this not how you run a Haskell program?

A: The GHCi command to load a file is :load, not load. You should write:
:load haskellprogram.hs

The command can also be abbreviated :l. You can find more information about the available commands in GHCi by entering :help. Also note that the prompt shows the modules you have imported; Prelude is just the name of the standard library module that gets imported by default. You can change the prompt with:
:set prompt "> "
:set prompt-cont "| "

(Where prompt-cont is the prompt for multi-line input, using the commands :{ and :} or the multi-line input mode enabled by :set +m.)
When you entered load haskellprogram.hs, it was interpreted as a Haskell expression: (load haskellprogram) . hs, which tries to use the (.) composition operator and three variables load, haskellprogram, and hs that are not defined.


text:
Q: Best way (regex?) to delete all occurrences of char in string plus next two chars after each occurrence I have a string that holds certain markers, and after each marker is certain value (unknown beforehand), composed of two or one chars. I want to remove both the markers and next two chars.
For example, string is:
var string = "123 t16 456 t26 789 t8 321";

Marker is "t" and each is followed by two or one characters that represent its value, in this case 16, 26 and 8, so I need to remove t16, t26 and t8 (t8+blank space). I always remove two chars after the marker.
I understand how to do it with substring or slice - start a loop to get a position of each marker, remove both the marker and next two chars based on position of the marker, and continue with the loop until all markers and its values are removed.
Is there a better way - in terms of speed and it being a one line solution - to do it with regex?

A: string = string.replace(/t../g, '');

If you want it case-insensitive:
string = string.replace(/t../gi, '');

A: This should do :
s.replace(/t.{1,2}\s/g, '')

See it in action here


text:
Q: Flutter: Firestore how to save query results? I have a page that uses collection from FireStore to display information. I have Card with InkWell that uses onTap to open new page and pass DocumentSnapshot. Now in opened page i want to perform Query of different collection and get data from node where title is equals to passed DocumentSnapshot's title. For this i have written a little code. Now i want to get result's and save it. To be specific i want to save from query nodes 'title','desc' and 'phone' as String to use it.
I used this code to make query but don't know how to save said nodes:
Stream<QuerySnapshot> snapshot(BuildContext context) async* {
yield* FirebaseFirestore.instance
    .collection('campus' + widget.locationTitle.get('type'))
    .where('title', isEqualTo: widget.locationTitle.get('title'))
    .snapshots();

}


text:
Q: Suppose that X and Y are independent geometric random variable, where X has parameter p and Y has parameter q. I would like to calculate the conditional expectation $E(X|X>Y)$.
I reckon that there are two scenarios for solving this question. But the ansewers are not the same in the end and I am confused by this.
First scenario
Firstly, we compute $E(X|X>y)$:
$E(X|X>y) = \sum x\frac{P(X \ = \  x, \ X \ > \ y)}{P(X \ > \ y)} \\ =\sum_{x\ = \ y +1} \ x\frac{(1 \ - \ p)^x \ p}{(1 \ - \ p)^y} \\ = y \ + \ \frac{1}{p}$
As $E(X|X>Y) \ = \ E(E(X|X>Y,Y)) \ = \ E(E(X|X>y))$, therefore,
$E(X|X>Y) = E(y \ + \ \frac{1}{p}) \ = \ \frac{1}{q} \ + \ \frac{1}{p}$
Second scenario(I think this is correct!)
$E(X|X>Y) = \sum x\frac{P(X \ = \  x, \ X \ > \ Y)}{P(X \ > \ Y)} \\
=\frac{1}{P(X \ > \ Y)}\sum_{x}x \ P(X \ = \ x)P(Y \ < \ x)$

A: Your first attempt is based on an erroneous claim that $X$ is conditionally independent of $Y$ when given $X>Y$. Surely it cannot be so. $$\mathsf P(X=x\mid X>Y, Y=y)~\neq~\mathsf P(X=x\mid X>y)$$

Rather, indeed you should indeed use the second approach. $$\begin{align}\mathsf E(X\mid X>Y)&=\sum_{x=2}^\infty x\,\mathsf P(X=x\mid X>Y)\\[2ex]&=\dfrac{\sum_{x=2}^\infty x\,\mathsf P(X=x)\,\mathsf P(Y<x)}{\mathsf P(X>Y)}\\&=\dfrac{pq\sum_{x=2}^\infty x(1-p)^{x-1}\sum_{y=1}^{x-1}(1-q)^{y-1}}{pq\sum_{x=2}^\infty (1-p)^{x-1}\sum_{y=1}^{x-1}(1-q)^{y-1}}\end{align}$$


text:
Q: Sticky hover state in chrome on buttons I have a problem with the hover state in Chrome. There are a couple of bagdes on my site ... when I remove one of them, the next badge remains hovered ... even if I am not hovering with my mouse (same on mobile touch device (but in FF (is it using chrome engine?))). FF and Safari on desktop works fine.
Same Question here.
Couldnt find any solution yet. Can someone help?

A: we found a solution to that problem. Simply modified the onClick ... the problem was the focus -> .blur() method
before:
onClick={onRemove}

after
onClick={(event) => {event.currentTarget.blur() onRemove()}}


text:
Q: android activity running in bkground is there a way to keep an activity running even though it has been sent to the background, home button is clicked, ?
My app has a countdowntimer and i want the timer to keep running even though the app is in the background.
Is there a way to do this without using services ? Because ive been reading up on services and im really notgetting how to use them... and if services is the only way can someone give me a simple tutorial or guide from where i can try this...
I've already seen all the documents and examples on the developer.android.com website... anything apart from those...
thankyou

A: I have implemented small stopwatch application (for puzzle solving time measurement), and it continues to work in the background even if I press home button.
I use Handler()
mRepetitiveTimeoutHandler.postDelayed(processWatchTimer, DISPLAY_UPDATE_TIMEOUT);

to periodically call
private Runnable processWatchTimer = new Runnable()

...
Time measurement is done via comparing current time System.currentTimeMillis() each time when runnable triggers.

A: Handler usage example below. It will continue to work if you press Home button, but not if you press Back button. In order to achieve that, you need to use Service, as already suggested in the first answer.
import android.os.Bundle;
import android.app.Activity;
import android.os.Handler;

public class HandlerExample extends Activity {

    private final static int DELAYED_ACTION_TIMEOUT = 10000;

    private Handler mRepetitiveTimeoutHandler;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        super.setContentView(R.layout.example);

        mRepetitiveTimeoutHandler = new Handler();
        mRepetitiveTimeoutHandler.postDelayed(processWatchTimer, DELAYED_ACTION_TIMEOUT);
    }

    private Runnable processWatchTimer = new Runnable()
    {
        public void run()
        {
            mRepetitiveTimeoutHandler.removeCallbacks(processWatchTimer);
            //Put your action here.
        }
    };
}

A:
Is there a way to keep an activity running even though it has been sent to the background?

No.  No way at all.
If you read about the Android Lifecycle you'll find that it's pretty clear that there is no way to do this.  I think part of the reason that Android makes you split your application in Activities is that it can easily free resources for Activities not being currently used.

My app has a countdowntimer and i want the timer to keep running even though the app is in the background.  Is there a way to do this without using services ?

If you didn't want to use a Service you could try using the AlarmManager.


text:
Q: generating an android ant file from eclipse I have an android project containing all my activities and manifest file etc and I am referencing 2 class libraries that contain various helpers, adapters etc. The class libraries are standard java projects.
My issue is that when I use the android update project --path . to generate the build.xml and run an ant release against this it fails because there is no dependency on the 2 class libraries.
Am I missing something big with the "android" command? or do I have to manually add to the generated build.xml to add these 2 class library builds.

A: You can write a custom "compile" task in your build.xml, to compile your class libraries and then compile your android project. It is not hard at all, just copy paste the compile target from /tools/ant/main_rules.xml into your build.xml and modify accordingly.
You can read up on main_rules.xml to learn how to do this for any part of android build.


text:
Q: Insert rows based on column entry and determine the entry of the inserted row based on where it inserts I have this data, which I named A:
A <- read.table(text = "ID  TIME    EVID    AMT DOSE
1   10      1       100 20
1   12      1       100 20
1   14      1       100 20
1   16      1       100 20
1   17      0       100 20
1   18      1       100 20
1   20      1       100 20
1   22      1       100 20
2   5       1       100 40
2   10      1       100 40
2   15      1       100 40
2   17      0       100 40
2   20      1       100 40
3   4       1       100 25
3   7       1       100 25
3   10      1       100 25
3   11      0       100 25
3   13      1       100 25
3   16      1       100 25
3   19      1       100 25", header = TRUE)

And my goal is insert new rows with EVID=2, ID the same as the preceding row ID, and TIME = preceding row's TIME entry plus AMT/DOSE, and I want the new rows to be follow after the first EVID=1 after the 0s, as below:
ID  TIME    EVID    AMT DOSE
1   10      1       100 20
1   12      1       100 20
1   14      1       100 20
1   16      1       100 20
1   17      0       100 20
1   18      1       100 20
1   23      2       100 20
1   20      1       100 20
1   22      1       100 20
2   5       1       100 40
2   10      1       100 40
2   15      1       100 40
2   17      0       100 40
2   20      1       100 40
2   22.5    2       100 40
3   4       1       100 25
3   7       1       100 25
3   10      1       100 25
3   11      0       100 25
3   13      1       100 25
3   17      2       100 25
3   16      1       100 25
3   19      1       100 25

I get as far as to indexing my EVID's
rle(as.character(EVID))$lengths
A$Index<-unlist(sapply(rle(as.character(EVID))$lengths, seq_len), use.names = FALSE)

In this circumstance this code works better than ave(EVID, EVID, FUN=seq_along) which would index all the 1s and all the 0s regardless of whether they are continuous. I want to insert my new rows between Index=1 and Index=2 rows (I will just manually delete the first new row).
   ID TIME EVID AMT DOSE Index
1   1   10    1 100   20     1
2   1   12    1 100   20     2
3   1   14    1 100   20     3
4   1   16    1 100   20     4
5   1   17    0 100   20     1
6   1   18    1 100   20     1
7   1   20    1 100   20     2
8   1   22    1 100   20     3
9   2    5    1 100   40     4
10  2   10    1 100   40     5
11  2   15    1 100   40     6
12  2   17    0 100   40     1
13  2   20    1 100   40     1
14  3    4    1 100   25     2
15  3    7    1 100   25     3
16  3   10    1 100   25     4
17  3   11    0 100   25     1
18  3   13    1 100   25     1
19  3   16    1 100   25     2
20  3   19    1 100   25     3

The resulting A has a new Index column; I want the new rows to be between Index 1 and 2, i.e. after row number 1, 6, 13, and 19 in this example.
I've come across solutions in which we can make a column vector, then insert the column as row into the data by defined row number. How do I add the rows based on column entry and determined some entries dynamically?
Thanks for your help!

A: here is a solution with data.table
It's really just two lines of code (with a bit of comments)
library(data.table)
ADT <- data.table(row=1:nrow(A), A, key="ID")

# just to give an idea of how we can Find the first 0 after the first 1, look at the output from this
ADT[, list(row, EVID,c(NA,diff(EVID)), c(NA,diff(EVID))==1)]

# identify afer which row to insert
# the values you want to change, assign using the `=`
# the values to keep, just call the variable name, no `=` sign
newRows <- ADT[c(NA,diff(EVID))==1, list(row=row+1, ID, TIME=TIME+AMT/DOSE, EVID=2, AMT, DOSE)]

# rbind the new rows with the original DT
# then reverse order by EVID, and order by row.
# After ordering, remove the first column (`row`) since it is not needed
newA <- rbind(ADT, newRows)[order(EVID, decreasing=TRUE)][order(row)][, -1, with=FALSE]

### Results:

 > newA
    ID TIME EVID AMT DOSE
 1:  1   10    1 100   20
 2:  1   12    1 100   20
 3:  1   14    1 100   20
 4:  1   16    1 100   20
 5:  1   17    0 100   20
 6:  1   18    1 100   20
 7:  1   23    2 100   20
 8:  1   20    1 100   20
 9:  1   22    1 100   20
10:  2    5    1 100   40
11:  2   10    1 100   40
12:  2   15    1 100   40
13:  2   17    0 100   40
14:  2   20    1 100   40
15:  2   22    2 100   40
16:  3    4    1 100   25
17:  3    7    1 100   25
18:  3   10    1 100   25
19:  3   11    0 100   25
20:  3   13    1 100   25
21:  3   17    2 100   25
22:  3   16    1 100   25
23:  3   19    1 100   25
    ID TIME EVID AMT DOSE