text:
Q: BufferedWriter adds too many lines? I wanted to ask if there is a better solution than using StringBuilder to cut some part of a String, which is parsed from a method through BufferedWriter to a file ?
Without StringBuilder there is a bunch of much strings in the file, what happens with the rest of string, data-nirvana ?
  class TaskStartPart {
   public void calculHash() throws InterruptedException, IOException,  NoSuchAlgorithmException {
    try {
     DigestInputStream digestInputStream=null ;
     MessageDigest messageDigest=MessageDigest.getInstance("SHA-512") ;
     digestInputStream=new DigestInputStream(new TaskPart(new   File("C:\\Users\\win7p\\Documents/t")),messageDigest) ;
    while(digestInputStream.read()>=0) ;
     for(byte b: messageDigest.digest()) {
      hexRes2 += String.format("%02x",b);
     } sb = new StringBuilder(hexRes2);  //StringBuilder which adjust the string to be parsed
     dateiSpeichern(0,0,sb.substring(hexRes2.length() -  128,hexRes2.length())); System.out.println(sb.substring(hexRes2.length() - 128,hexRes2.length()));
        digestInputStream.close();
      } catch (IOException ex ) {ex.printStackTrace();}
     }
    }

  class TaskPart extends InputStream {
    private File mFile ;
    private List<File> mFiles ;
    private InputStream mInputStream ;

   public TaskPart(File file) throws FileNotFoundException {
    mFile=file ;
    if(file.isDirectory()) {
    mFiles=new ArrayList<File>(Arrays.asList(file.listFiles())) ;
    Collections.sort(mFiles) ;
    mInputStream=nextInputStream() ;
   } else {
     mFiles=new ArrayList<File>() ;
     mInputStream=new FileInputStream(file) ;
   }
  }

  @Override
  public int read() throws IOException {
   int result=mInputStream==null?-1:mInputStream.read() ;
   if(result<0 && (mInputStream=nextInputStream())!=null)
    return read() ;
    else return result ;
   }

   protected String getRelativePath(File file) {
   return   file.getAbsolutePath().substring(mFile.getAbsolutePath().length()) ;
   }

   protected InputStream nextInputStream() throws FileNotFoundException {
    if(!mFiles.isEmpty()) {
     File nextFile=mFiles.remove(0) ;
    return new SequenceInputStream(
    new ByteArrayInputStream(getRelativePath(nextFile).getBytes()),
    new TaskPart(nextFile)) ;
   }
   else return null ;
  }
 }

  private void dateiSpeichern(int i1, int i2, String hexR) throws  InterruptedException, IOException {
   try {
    String tF = new SimpleDateFormat("dd-MM-yyyy HH-mm-ss").format(new   Date().getTime());
   try (BufferedWriter writer = new BufferedWriter(new FileWriter("C:\\Users\\win7p\\Documents/hashLog.txt", true))) {
   writer.append(tF);
   writer.newLine();
   writer.append(dtf);
   writer.newLine();
   writer.append("Hash Value: ");
   writer.append(hexR); //without StringBuilder I would have much //strings added next to eachone line by line
 } //normal here is also a catch code.

A: You don't really need a StringBuilder, since you just load it with a single String and then you just take out a substring from it.
You can just use String#substring method.
Garbage collection will take care of unreachable object in both cases.
StringBuilder is meant for building a String,and is essentially a mutable char buffer,you use it when you want to mutate a String several times(which is not your case).


text:
Q: Are "Proactive" designs on new projects useful? When starting a new project, are "proactive" designs useful? I mean, if you create a UML diagram/Activity diagram/Use Case/Class diagram/etc. for anything and everything can think of, then when you think you're done, you start coding. Afterwards, you realize an important feature or method was left out. All your spiffy UML diagrams are nice stacks of worthless paper now.
Is it easier/better to design one class, work on it a bit, refine it, then work on it more?

A: Contrary to popular opinion I do not buy into the "Big Design Up Front is bad" movement very much.
This statement is used too often as a lead-in to a project with no design at all.  The project is started with no design, and none ever materialises during the development.
I also do not believe that this way of working is what the original claimers (from the Extreme Programming / Agile movements, IIRC) intended.  They intended that developers would evolve their design alongside the evolving implementation.
Therefore I believe the process should be:

*

*Create just enough design to be able to get started on the project.  Note:  I am a firm opponent of "one feature at a time" - I believe you should start with a minimal beginning-to-end skeleton implementation instead (also known as a vertical slice).  Otherwise you are not doing iterative development but incremental development, and you are still running the risk of having a "big bang integration" when you finally implement the last feature to complete the loop of your project.

*Implement your first design.

*Evaluate the design and implementation results.  This should include feedback from your customer and end-users whenever possible, to ensure you are building the right thing.

*Rework and expand your design.

*Implement your reworked and expanded design.

*Continue with 3 until you are done.

A: What you call "proactive design" is generally called "big design up front" (BDUF) and considered a very bad idea. Vendors of UML tools claim to make it work through MDD, i.e. more or less all your code is directly generated from UML diagrams, or by keeping the model in synch with subsequent changes in code. But this never works perfectly and generally has you run into more problems than it's worth.

Is it easier/better to design one class, work on it a bit, refine it, then work on it more?

One class at a time would not be a good idea either. But one feature at a time, while keeping future features in mind when deciding the high-level design, seems to work pretty well.
UML diagrams (or models in general) have the most value in providing a high-level overview of systems. If they become too detailed, the advantages (visual overview) decline, and producing them takes an unjustifiable amount of time.

A: some "proactive" designs  => can be useful
Complete detailed upfront design => not lickly to be useful

A: You definitely do not want the "one-feature-at-time" combined with some twisted form of YAGNI to lead to what often happens:

"Oh, so we need to allow the customer to store 3 addresses, so I'll
  just add three columns to the customer table."
"Shouldn't we try to maintain a relational model with a seperate
  address table and a surrogate key in case at some point a customer
  needs 4 addresses."
"YAGNI, they are really gonna need to put in another feature request
  for us to allow for 4 customers. You're overengineering for a use case
  that doesn't exist"
"...FML"

A certain amount of "looking ahead" is always required. If this was not the case, then no one would bother with patterns and best practices. Without a high level functional spec, how are you supposed to prioritize which feature comes next. I am not huge on UML, unless its a rough 1st iteration sketch on my legal pad, but the design phase always must include some sort of functional description of how things should behave. This might be contraversial, but I really do not even think it matters all that much what you even do with the spec once it is written down (update it as you go, put it in a folder no one goes to, delete it, etc.). The main benefit of the design process, and coming up with a loose spec, is that it forces you to write all of your ideas down, and see if they make any sense.

A: I usually do alot of UML and other forms of artifacts planing how to do it, and then sometimes overthink it, and implement something else. That leaves me with a lot of papers (I like painting with pen and paper) and many files on the computer.
My best advice is to create as many artifacts as you want/need and keep them. In the end you will see that Software is living. You will sooner or later refactor parts of your software, maybe parts that are well documented and have a lot of UML. Thats how it is. I have spend some time documenting parts of our company Software we were using. After finishing some diagrams and documentations we refactored the part, leaving all my documents doomed.
At some point in your career or your hobby-life, you will think back to some design from earlier and than you have the documents lying around :)

redpajama_set_name: RedPajamaStackExchange


text:
Q: Non-blocking recv on Tokio mpsc Receiver I am using Rust and Tokio 1.6 to build an app which can interact with an Elgato StreamDeck via hidapi = "1.2". I want to poll the HID device for events (key down / key up) and send those events on an mpsc channel, while watching a separate mpsc channel for incoming commands to update the device state (reset, change brightness, update image, etc). Since the device handle is not thread safe, I need to do both things from a single thread.
major edits below
This is a rewrite of my original question. I've left my interim answer below, but in the interest of a more self contained example, here is a the basic process using device_query = "0.2":
use device_query::{DeviceState, Keycode};
use std::time::Duration;
use tokio;
use tokio::sync::mpsc::{Receiver, Sender};
use tokio::time::timeout;

#[tokio::main]
async fn main() {
    // channel for key press events coming from device loop
    let (key_tx, mut key_rx) = tokio::sync::mpsc::channel(32);
    // channel for commands sent to device loop
    let (dev_tx, mut dev_rx) = tokio::sync::mpsc::channel(32);

    start_device_loop(60, key_tx, dev_rx);

    println!("Waiting for key presses");
    while let Some(k) = key_rx.recv().await {
        match k {
            Some(ch) => match ch {
                Keycode::Q => dev_tx.clone().try_send(String::from("Quit!")).expect("Could not send command"),
                ch => println!("{}", ch),
            },
            _ => (),
        }
    }
    println!("Done.")
}

/// Starts a tokio task, polling the supplied device and sending key events
/// on the supplied mpsc sender
pub fn start_device_loop(hz: u32, tx: Sender<Option<Keycode>>, mut rx: Receiver<String>) {
    let poll_wait = 1000 / hz;
    let poll_wait = Duration::from_millis(poll_wait as u64);

    tokio::task::spawn(async move {
        let dev = DeviceState::new();

        loop {
            let mut keys = dev.query_keymap();
            match keys.len() {
                0 => (),
                1 => tx.clone().try_send(Some(keys.remove(0))).unwrap(),
                _ => println!("So many keys..."),
            }

            match timeout(poll_wait, rx.recv()).await {
                Ok(cmd) => println!("Command '{}' received.", cmd.unwrap()),
                _ => (),
            };
            // std::thread::sleep(poll_wait);
        }
    });
}

Note this does not compile - I get an error future created by async block is not 'Send' and within 'impl Future', the trait 'Send' is not implemented for '*mut x11::xlib::_XDisplay'. My understanding of the error is that because device_query is not thread-safe, and awaiting introduces the possibility of scope moving across threads, nothing may be awaited while a non-thread-safe object is in scope. And indeed, if I comment out the block around match timeout... and uncomment the std::thread::sleep everything compiles and runs.
Which brings me back to the original question; how can I both send and receive messages in a single thread without using await or the apparently forbidden fruit of poll_recv()?

A: After much hunting I found noop_waker in the futures crate which appears to do what I need in combination with poll_recv:
pub fn start_device_loop(hz: u32, tx: Sender<Option<Keycode>>, mut rx: Receiver<String>) {
    let poll_wait = 1000 / hz;
    let poll_wait = Duration::from_millis(poll_wait as u64);

    tokio::task::spawn_blocking(move || {
        let dev = DeviceState::new();

        let waker = futures::task::noop_waker();
        let mut cx = std::task::Context::from_waker(&waker);

        loop {
            let mut keys = dev.query_keymap();
            match keys.len() {
                0 => (),
                1 => tx.clone().try_send(Some(keys.remove(0))).unwrap(),
                _ => println!("So many keys..."),
            }

            match rx.poll_recv(&mut cx) {
                Poll::Ready(cmd) => println!("Command '{}' received.", cmd.unwrap()),
                _ => ()
            };
            std::thread::sleep(poll_wait);
        }
    });
}

After digging through docs and tokio source more I can't find anything that suggests poll_recv is supposed to be an internal-only function or that using it here would have any obvious side effects. Letting the process run at 125hz I'm not seeing any excess resource usage either.

I'm leaving the above code for posterity, but since asking this question the try_recv method has been added to Receivers, making this all much cleaner.


text:
Q: Declare array into searchFields Worklight JSONStore I have a JSON object to my collection with JSONStore like this:
{
    name : 'name1',
    industry : ['Banking', 'Energy', 'Insurance', 'Media', 'Retail', 'Telco', 'Travel'],
    buyer : ['CMO'],
    link : 'foo.com'
}

But, how is possible declare the industry field into searchFields?, in order to search a pattern in the array.
Cheers

A: There's no array type for search fields. You can only index values in objects that are string, boolean, number and integer.
You could change:
{ industry : ['Banking', 'Energy'] }

to:
{ industry : [{name: 'Banking'}, {name: 'Energy'}] }

and then use the following search field: {'industry.name' : 'string'}. That will enable you to do something like WL.JSONStore.get('collection').find({'industry.name' : 'Banking'}, {exact: true}) and get back an object like this one:
[{_id: ..., json: {name: ..., industry: [..., {name: Banking}, ...], buyer: ..., link: ...}}]

This is documented under the search field section of general terminology in the documentation here.
That would mean writing code like this to change the data being added to the collection:
var output = [];
['Banking', 'Energy', 'Insurance', 'Media'].forEach(function (element) {
    output.push({name: element});
});
console.log( JSON.stringify(output, null, ' ') );

Alternatively, you could also change it into a string:
{industry : ['Banking', 'Energy', 'Insurance', 'Media'].toString() }

and get back something like this:
{industry : "Banking,Energy,Insurance,Media"}

Then you can use the search field {industry : 'string'} and do something like WL.JSONStore.get('collection').find({industry: 'Energy'}, {exact: false}) to get objects that have Energy somewhere in the industry value string.
FYI - Feature requests here.


text:
Q: (Discord.py) How do I make a dare 21 game? i need to take inputs in the form of numbers, like "1 2 3" (max 3 numbers) and make it turn by turn? I have been working on a discord bot where I am trying to make the game "21 dares" (see this link for info on that [https://www.wikihow.com/Play-21-Dares][1])
how do I take inputs turn by turn? I tried making a list of players using

players = await msg.reaction.users().flatten()

but how do I make it so that it's turn by turn?
next, I need to check the inputs, like, the first player is only allowed to say a maximum of 3 numbers, and the second player has to start after the first's third number.
basic idea being,
Player A: "1, 2, 3." Player B: "4, 5." Player C: "6, 7, 8." Player D: "9." Player E: "10, 11, 12." Player A: "13, 14, 15." Player B: "16, 17." Player C: "18." Player D: "19, 20." Player E: "21." In this instance, Player E was forced to say "21."
Player A: "1." Player B: "2, 3, 4." Player C: "5, 6, 7." Player D: "8, 9, 10." Player A: "11." Player B: "12, 13, 14." Player C: "15." Player D: "16, 17, 18." Player A: "19." Player B: "20." Player C: "21." In this instance, Player C was forced to say "21."
Player A: "1." Player B: "2, 3, 4." Player C: "5, 6, 7." Player D: "8." Player E: "9." Player F: "10, 11, 12." Player G: "13, 14." Player H: "15, 16." Player A: "17, 18, 19." Player B: "20." Player C: "21." In this instance, Player C was forced to say "21.
this is my code so far. pls help me I've been trying to make this work for 3 days
    async def tod(self, ctx, user: discord.Member = None):
        '''21 truth or dare game'''
        the_author = ctx.author
        channel = ctx.channel
        if user is None:
            embed = discord.Embed(title="Truth or Dare game", color=discord.Colour.orange(),
                                  description=f"{the_author.mention} is inviting anyone to play truth or dare! \n\nType `accept` now to accept the challenge and begin a game with them.")
        elif user != the_author and not user.bot:
            embed = discord.Embed(title=" truth or dare", color=discord.Colour.orange(),
                                  description=f"{the_author.mention} is inviting anyone to play truth or dare! \n\nType `accept` now to accept the challenge and begin a game with them.")
        else:
            embed = discord.Embed(title="You can't invite yourself or a discord bot to a game!")

        msg = await channel.send(embed=embed)
        await msg.add_reaction("✅")

        import time
        time.sleep(10)
        players = await msg.reaction.users().flatten()
        check_list = []
        current_count = []
        def check(message):
            list = message.split(' ')
            for element in list:

                element = int(element)
                check_list.append(element)

            range_list=list(range(min(check_list), max(check_list)+1))
            if check_list == range_list:
                for element in current_count :check_list.append(element)
                check_list.clear()

        await self.bot.wait_for( 'message', check=check, timeout=60)```

I'm quite new to discord.py, so any small tips are also appreciated.

  [1]: https://www.wikihow.com/Play-21-Dares

A: You can use the on_message to react on a sent message. From this event you receive an object of type Message.  With the attribute author you can get the member, which sent the message. You can now compare the id's of member and the current player. With the content attribute of Message you can check if the message is valid or not.
You can read the documentation yourself here
To check which players turn it is I suggest you simply create an counter, which increases each time you get an valid message. You compare the Member-ID of an user with the ID of player[counter].
Edit to comment of @Dhravya Shah:
I would check it like this (I didn't test the code, but the concept would be this):
client = discord.Client()
count = 0

@client.event
async def on_message(message):
    if players[count] == message.author:
        #Check if message is valid
        if messageIsValid: #placeholder variable
            #Save  the answer to an array or similar
            count += 1

A: Ok, i think i figured it out. I cycled through the playerlist using itertools.cycle() I couldn't figure out how I iterate through the particular element of the list again,so I simply made it so that the player who does a mistake loses the game
This is my entire code, hopefully it helps someone else
@commands.command(name='21dares', aliases= ['truth_or_dare'])
    async def tod(self, ctx, user: discord.Member = None):
        '''21 truth or dare game'''
        the_author = ctx.author
        channel = ctx.channel
        if user is None:
            embed = discord.Embed(title="Truth or Dare game", color=discord.Colour.orange(),
                                  description=f"{the_author.mention} is inviting anyone to play truth or dare! \n\nType `accept` now to accept the challenge and begin a game with them.")
        elif user != the_author and not user.bot:
            embed = discord.Embed(title=" truth or dare", color=discord.Colour.orange(),
                                  description=f"{the_author.mention} is inviting anyone to play truth or dare! \n\nType `accept` now to accept the challenge and begin a game with them.")
        else:
            embed = discord.Embed(title="You can't invite yourself or a discord bot to a game!")

        msg = await channel.send(embed=embed)

        playerlist = []
        check_list = []
        count_list = []
        current_count = 0

        def checkConsecutive(l):
            return sorted(l) == list(range(min(l), max(l)+1))

        def check(message):
            return True

        while True:
            msg = await self.bot.wait_for('message', timeout=60.0, check=check)
            if msg.content == 'accept':
                await ctx.send(f'{msg.author.mention} accepted! type `start` before 60 seconds to start')
                playerlist.append(msg.author)

            elif msg.content == 'start' and len(playerlist)>=2:
                await ctx.send(f'Game started!Start by typing `1 2 ..`')

                for player in itertools.cycle(playerlist):
                    embedlost = discord.Embed(title=f"{player} lost! choose `Truth or Dare?!`")
                    await ctx.send(f"{player.mention}'s turn!")
                    def check1(message):
                        if message.author == player:

                            return True
                    n = await self.bot.wait_for('message', timeout=60.0, check=check1)
                    if n.content == 'cancel' or n.content =='stop': break
                    if n.author == player and n.author != self.bot.user:
                        listn = n.content.split(' ')
                        for element in listn:
                            element = int(element)
                            check_list.append(element)

                        if current_count >= 21:

                            await ctx.send(embed= embedlost)

                            break
                        elif check_list[0] == current_count+1:
                            if checkConsecutive(check_list)==True:
                                for element in check_list : count_list.append(element)
                                current_count = count_list[-1]
                                check_list.clear()
                                await n.add_reaction('✅')
                            else :
                                await ctx.send('Numbers not consecutive! YOU SPOLIED THE GAME! YOU LOSE!')
                                await ctx.send(embed=embedlost)
                                check_list.clear()
                                break
                        else:
                            await ctx.send(f'Dude you have to start from {current_count+1}! YOU SPOLIED THE GAME! YOU LOSE!')
                            await ctx.send(embed=embed)

            elif msg.content == 'start' and len(playerlist)==0 or len(playerlist)==1:
                await ctx.send("Can't start, less than 2 players")
            elif msg.content == 'cancel':
                await ctx.send('Game Cancelled')
                break```
#Its probably not the ideal code, but it works as I want it to, so I guess its fine


text:
Q: ag-grid: color cells if nearing expiration date Trying to color cells if the dates on the grid are expiring soon i.e. 'Survey Exp - 1/1/2020' and I want the cell to turn red when today's date is 5 months within supplier expiration. Pls help
        var today = new Date();
        var curr_date = today.getDate();
        var curr_month = today.getMonth() + 1;
        var curr_year = today.getFullYear();
        var todayMan = curr_month + '/' + curr_date + '/' curr_year

        class Bsall extends React.Component {
        constructor(props) {
        super(props)
        this.state = {
        items: [],
        columnDefs: [

            {headerName: "Supplier Status", field: "supplier_status", sortable: true, filter: true},
            {headerName: "Survey Exp", field: "survey_exp", sortable: true, filter: true, cellStyle:
            params => {
                if (params.value < todayMan + 5) {
                    return {'background-color': 'red'}}
                }},

A: To achieve expected result, use below option of using new Date and comparing months with getMonth() from date

*

*Get years difference from both dates and convert to months by multiplying with 12
((new Date(val).getFullYear() - new Date(todayMan).getFullYear()) * 12)

*Get months from both dates by getMonth() method and difference of it
new Date(val).getMonth() - new Date(todayMan).getMonth()

*Combining both will give months count between dates

*Check if it less than 5 months and apply style

    if (months < 5) {
                        return {'background-color': 'red'}
                    }
Working code sample for reference - https://codepen.io/nagasai/pen/ZEEowMr?editors=1010


text:
Q: GnuPlot : feed each column from different files I would like to plot a 3D graph fed from two different data files.
The first one would have the Z-data, stored in the following way, where the columns have different sizes:
X00 Z00     X10     Z10     X20     Z20... XN0 ZN0
X01 Z01     X11     Z11     X21     Z21
X02 Z02     X12     Z12     X22     Z23
....
X0A Z0A     X1A     Z1A     X2A     Z2A     ...
            X1(A+1) Z1(A+1) X2(A+1) Z2(A+1) ...
...

            X1B     Z1B     X2B     Z2B
            X1(B+1) Z1(B+1) X2(B+1) Z2(B+1) ...
...
            X1C     Z1C
            X1(C+1) Z1(C+1)

The second file would contain the Y data, in the appropriate format:
Y00 Y10 Y20
...

I would need the equivalent to the following matlab code (where I already have separately read the columns, and then formed the appropriate XZ matrix data). Note that 'data' matrix, is a matrix of dimensions(2N x C) where C is the max size of the largest column. The remaining non-exiting data (for shorter columns) is filled with 'Nan' value.
Is there a way to use pm3d to achieve that?
        yData=[1,2,3,5,7,10];
        figure;
        hold all;
        for yIndex=1:length(yData)
            col = yIndex*2;
            colSize=length(data(:,col));
            plot3(yData(yIndex)*ones(colSize),data(:,col-1),data(:,col));
        end
        xlabel('x');
        ylabel('y');
        zlabel('z');
        grid on;
        hold off;


text:
Q: Number of Ticks shown on Xaxis I am using Recharts.js to create charts for my website.
I have some custom ticks that I'm using for the X-axis, but only a couple of them are actually shown when the chart is rendered.
I searched the documentation but I can't figure out what controls the number of ticks been shown.
This is my code for the XAxis:
 <XAxis name="city" dataKey="format" tick={<CustomTick/>}/>

And here are the Code for the Custom Tick:
const CustomTick = (props) =>{

return(
    <g transform={`translate(${props.x},${props.y})`}>
        <text textAnchor="end" fontSize={12} transform="rotate(-90)" >{props.payload.value}</text>
    </g>
)}

It produces something like this, where only a couple of ticks are shown:
Chart
Does anyone know what value in Recharts.js that controls the number of ticks rendered?

A: I found that the interval property controlled the number of ticks rendered. Setting it to 0 showed them all: Like this:
<XAxis interval={0} name="city" dataKey="format" tick={<CustomTick />}/>


text:
Q: render listView to the next row when end of the screen width reached I'm using listView for my react-native application. Right now, ListView renders all items on the first row and I should scroll screen horizontally to see more after second item. However, I want to render only two item for each row. So how can I change my ListView so it renders only two items per row?
Here is my ListView implementation code.
<ListView contentContainerStyle={{flexDirection: 'row', flexWrap: 'wrap', left: 5}}
                                     dataSource={this.state.dataSource}
                                     enableEmptySections={true}
                                     horizontal
                                     renderRow={(rowData)=>this.renderRow(rowData)}>
</ListView>

Here is how my ListView renders currently.


text:
Q: Add selected cells of different sections in different arrays, UICollectionView I want to add selected cells of UICollectionView in arrays, section wise in different arrays, means different arrays for each section. The problem is this that number of sections are dynamic. Below is my code.
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    NSString *seatV;
    int cs;

    NSString *secVal = [arrSeatSel objectAtIndex:indexPath.section];
    NSArray *arrSplit = [secVal componentsSeparatedByString:@":"];
    seatV = [arrSplit objectAtIndex:1];
    cs = [seatV integerValue];

    int v;
    NSString *cnt = [NSString stringWithFormat:@"%@",[arrTot objectAtIndex:indexPath.section]];
    v = [cnt intValue];

    NSString *sect = [NSString stringWithFormat:@"%d", indexPath.section];

    if(indexPath.item < v)
    {
        if([sectionInfo count] < cs)
        {
            itemPaths = [self.collectionView indexPathsForSelectedItems];

            sectionInfo = [NSMutableArray arrayWithArray: [self.collectionView indexPathsForSelectedItems]];
            [selectedItemsInfo setObject:sectionInfo forKey:sect];
            cell=[self.collectionView cellForItemAtIndexPath:indexPath];
            cell.contentView.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"yellow_seat.png"]];
        }

        else
        {
            [self.collectionView deselectItemAtIndexPath:[NSIndexPath indexPathForItem:indexPath.row inSection:indexPath.section] animated:YES];

            [sectionInfo removeAllObjects];
        }

        [self.collectionView deselectItemAtIndexPath:[NSIndexPath indexPathForItem:indexPath.row inSection:indexPath.section] animated:YES];
    }

    NSLog(@"section array:%@", sectionInfo);
    NSLog(@"section array1:%@", sectionInfo1);
    NSLog(@"selected seats dict:%@", selectedItemsInfo);
}

The array arrSeatSel is getting the number of sections and number of seats that can be choose from each section.
description of arr seatsel:(
 "Family:2",
 "Gold:3"
)

Here sections are 2 and cells that can be selected are 2. Similarly for other sections and in all cases.
arrTot is getting the total number of cells in each section
description of arrTot(
    10,
    10
)

array arrLevels are number of sections. and array itemPaths is adding the selected cells, and here the problem is, whichever section is it is adding selected cells, but each section has it's own limit of selecting cells. Hope you got my point, if anything clear ask freely.
In short i tell you what is happening here is there is seat map for different levels level 1, 2, etc. and for each level you can select limited seats, then those selected seats for different levels are required to add in different arrays.

A: Use a dictionary to store the details. section number becomes the keys and store an array of selected items corresponding to each keys
Here is outline
 NSDictionary
     Key:section0  value: array of selected items in section0
     Key:section1  value: array of selected items in section1

Code
 //Create a dictionary first
 NSMutableDictionary *selectedItemsInfo = [NSMutableDictionary new];

// During selection
NSMutableArray *sectionInfo = [selectedItemsInfo objectForKey:indexPath.section];
if (sectionInfo == nil) {
     NSMutableArray *array = [NSMutableArray array]
    [array addObject: ] // add selected item
    [selectedItemsInfo setObject:array forKey:indexPath.section];

}
else
{
    [sectionInfo addObject: ]  // add selected item
}

Edit (Imp code from discussion)
 // Follow the below pattern
 NSMutableArray *sectionInfo = [selectedItemsInfo objectForKey: [NSNumber numberWithInt:indexPath.section]];

if (sectionInfo == nil) {
     NSMutableArray *array = [NSMutableArray array];
     [array addObject: indexPath]; // add selected item
     [selectedItemsInfo setObject:array forKey:[NSNumber numberWithInt:indexPath.section]];

  }
  else
  {
      // check the count
     if([sectionInfo count] < cs)
     {

      [sectionInfo addObject: indexPath]; // add selected item
     }
     else
     {
       // No need to add the item. Deselect the cell
     }
  }

  // To remove an item
  sectionInfo = [selectedItemsInfo objectForKey: [NSNumber numberWithInt:indexPath.section]];
  [sectionInfo removeObject:indexPath]


text:
Q: Bypass unresolvable error when cleaning packages with package manager? Using MacPorts, when I run
sudo port -f clean --all all

Then I get an error. Snippet of output below:
--->  Cleaning ml
--->  Cleaning mldonkey
--->  Cleaning mlpack
--->  Cleaning mlt
Error: Unable to open port: Package Qt5Core was not found in the pkg-config search path.
Perhaps you should add the directory containing `Qt5Core.pc'
to the PKG_CONFIG_PATH environment variable

I don't know which one is causing the problem (I tried uninstalling/installing mlt but that doesn't do it). This may not be specific to MacPorts, but I see the same error with homebrew posted so maybe it is more general.
I searched in /opt/local/ which is the installation directory of MacPorts but I don't have Qt5Core.pc.
Is there a way to make this MacPorts command continue running (kind of like with exception handling) and continue cleaning other packages after the error is encountered?

A: The error has been reported at https://trac.macports.org/ticket/54861. A workaround patch has been provided.

diff --git a/multimedia/mlt/Portfile b/multimedia/mlt/Portfile
--- a/multimedia/mlt/Portfile
+++ b/multimedia/mlt/Portfile
@@ -42,7 +42,7 @@ if {${subport} eq "${name}"} {
     if {[info procs qt5.active_version] eq ""} {
         proc qt5.active_version {} {
             global prefix
-            if {[file exists ${prefix}/bin/pkg-config]} {
+            if {[file exists ${prefix}/bin/pkg-config/Qt5Core.pc]} {
                 set av [exec ${prefix}/bin/pkg-config --modversion Qt5Core]
                 return ${av}
             } else {
@@ -53,10 +53,15 @@ if {${subport} eq "${name}"} {

     qt5.depends_component \
                     qtsvg
-    if {[vercmp [qt5.active_version] 5.7.0] >= 0} {
-        configure.cxxflags-append \
-                    -stdlib=libc++ \
-                    -std=c++11
+    pre-configure {
+        # qt5.active_version only works if Qt is installed; we can
+        # be certain that is the case in the pre-configure phase.
+        if {[vercmp [qt5.active_version] 5.7.0] >= 0} {
+            ui_debug "Qt 5.7.0 and up require at least C++11"
+            configure.cxxflags-append \
+                        -stdlib=libc++ \
+                        -std=c++11
+        }
     }
 }


text:
Q: list comprehension for nested for loop in python I wrote the following for loop, I am looking into converting this into a list comprehension, would appreciate any pointers.
car_dict  = {'mazda': ('G1',), 'toyota': ('G2',), 'nissan': ('G3', 'G2', 'G4')}
group_list = ['G1', 'G2', 'G3', 'G4']

for group in group_list:
    for car, value in car_dict.items():
        for car_group in value:
            if car_group in group:
                print(f'{car} in {group}')
            else:
                print(f'{car} not in {group}')

A: If you want an array of True False you can do the following:
car_dict  = {'mazda': ('G1',), 'toyota': ('G2',), 'nissan': ('G3', 'G2', 'G4')}
group_list = ['G1', 'G2', 'G3', 'G4']

in_group = [[group in val for key, val in car_dict.items()]
            for group in group_list]
print(in_group)

# output
[[True, False, False], [False, True, True], [False, False, True], [False, False, True]]

If you want a dictionary of group with car manufacturers do the following:
in_group_names = {group: [key for key, val in car_dict.items() if group in val]
                  for group in group_list}
print(in_group_names)

# output
{'G1': ['mazda'],
 'G2': ['toyota', 'nissan'],
 'G3': ['nissan'],
 'G4': ['nissan']}


text:
Q: Flex List selected entire list by default I am currently working on a project in Flex and I am having a hard time having a list's contents ALL be selected by default. Wondering how to do this. Appreciate any help.
<mx:List id="list" dataProvider="{dp}" allowMultipleSelection="true"/>
I'm just trying to have the list all selected.

A: Try to use something like the following:
<mx:List id="list" dataProvider="{dp}" allowMultipleSelection="true"
    creationComplete="event.currentTarget.selectedItems = event.currentTarget.dataProvider.source"/>

A: I ended up trying many different variations to get the list to be all selected. This is the one that ended up working.
var arr:Array = new Array();
for (var i:Number = 0; i < (list.dataProvider as ArrayCollection).length; i++) {
arr[i] = i;
}
list.selectedIndices = arr;


text:
Q: How to copy a zip file from Windows to CentOS On a Windows machine, I have a zip file in my E:\ directory. I want to import this onto my CentOS system inside the directory user/user01.
I know the command must involve scp, but I am unable to find the exact format for the command. I get an error like cp: cannot stat 'IOT.zip': No such file or directory".
How do I get rid of this error?

A: Easier still I would suggest using a program such as WinSCP which is a windows gui you can use to pop the files on via SFTP. Just download it (google winscp) and connect using SSH details

A: If you are trying to check a network drive hosted by a windows machine I don't think you would be using ssh; unless it was set up that way. Probably would be a samba server.
Here is the man page for smbclient, there is probably better/more information out there for smb. duckduck it.
https://linux.die.net/man/1/smbclient


text:
Q: How to get the previous mongoDB document from a compound index Given this data with a unique compound index:
db.employees.drop()
db.employees.insert( { employeenum : 1, check : "A" } )
db.employees.insert( { employeenum : 1, check : "B" } )
db.employees.insert( { employeenum : 2, check : "A" } )
db.employees.insert( { employeenum : 2, check : "B" } )
db.employees.insert( { employeenum : 2, check : "C" } )
db.employees.insert( { employeenum : 5, check : "E" } )
db.employees.insert( { employeenum : 6, check : "A" } )
db.employees.ensureIndex( { employeenum: 1, check : 1 }, {unique: true} )

If I want the next document in the index after { employeenum : 5, check : "E" }. I can do this:
db.employees.find({ query: { $or: [ { employeenum: { $gt: 5 } }, { check: { $gt: "E" } } ] }, $min: { employeenum: 5, check: "E" }, $maxScan: 2 })

which returns { employeenum : 6, check : "A" }.
But how do I traverse backwards from { employeenum : 5, check : "E" }? How do I fetch { employeenum : 2, check : "C" }? The way I am doing it:
{ query: { $or: [ { employeenum: { $lt: 5 } }, { check: { $lt: "E" } } ] }, $hint: { employeenum: -1, check: -1 }, $min: { employeenum: 5, check: "E" }, $maxScan: 2 }

requires a reverse index, a very inefficient solution. Is there a better way? B-tree indexes are bi-directional, aren't they?

A: The answer is: It can't be done in the current version. The 2nd jira ticket is a possible future fix.
See: SERVER-9540
and
SERVER-9547
The workarounds: Use a reverse index as I outlined or create a (doubly) linked list by " by using a reference field to the primary key of the previous/next document."


text:
Q: How DNS lookups work when using an HTTP proxy (or not) in IE I recently participated in a discussion regarding what happens when a client requests a page from a proxy server. I just wanted to make sure that my understanding of this sequence of events was correct in the general case:

*

*User requests site

*A DNS request is sent by the client, to its configured DNS server to resolve the destination IP address (this is done first in order to accommodate HTTP requests that are configured to bypass the proxy)

*Once the destination IP is received from DNS, and just before the HTTP request is sent, the request is checked against the exception list

*If the destination server is not on the exception list, the request is forwarded to the proxy server.

*If the destination server is on the exception list, the request is forwarded according to the client machine's routing table.

Any feedback would be most appreciated.

A: Not exactly: it depends on how the client is configured. Let's use IE as the basic example.
If you configure IE with an explicit proxy: e.g. no other options ticked, proxy set to something:8080.

*

*User types an address

*IE checks the address for a string match against the IE proxy exceptions list (i.e. "Bypass proxy for these addresses:")
a. If it matches an entry in the Bypass list, the client uses its own DNS to resolve the name, and then the client connects directly to the target IP address on port 80 (assumed), then sends a request like:
GET /something.htm HTTP/1.1
Host: fulldomainame.example.com
b. If no bypass list entries match, continue:

*IE connects to its configured proxy, and sends a request of the form:
GET http://fulldomainname.example.com/something.htm HTTP/1.1
Bonus factoid: this use of the FQDN in the URL is one way you can tell that a client thinks it's talking to a proxy instead of a real web server

*The proxy resolves that host name using its own DNS, and then connects to the target site (acts like the client in step 2 above), etc, etc.
When using WPAD/PAC:
In the case of using a Web Proxy Auto Discovery (WPAD) or Proxy Auto Configuration (PAC or Autoconfig) script, such as those provided by ISA/TMG when autoconfiguration is enabled, it's different:

*

*User types an address

*Client downloads the current wpad.dat/autoproxy.js/.pac file from its configured location

*Client looks for the function "FindProxyForUrl" in the js file, and executes it

*The Autoproxy script processes the hostname and URL. This is a limited-function javascript file, but lots of things are still possible:
a. this may include name resolution (IsInNet, DnsResolve)
b. this may include string matching (ShExpMatch)
c. this may include counting to a million (i++)
d. this may include narky alert popup messages if the admin's a jerk

*

*(or just funny)

*((or debugging))

*The FindProxyForUrl function returns at least one string: an ordered list of the best proxies to use (semicolon separated)
a. either "DIRECT", in which case the client then needs to resolve the name itself and connect directly, as per the Bypass case above
b. or "PROXY proxyname:8080" or similar, in which case the client connects to that port on that proxy, tells it to GET the full URL, and the proxy performs name resolution.

*

*As an example: if the script function returned "PROXY yourProxy:8080;DIRECT" that tells the client to connect to yourproxy on TCP port 8080 to request this URL, and if that connection can't be established, try going direct.
Note that TCP session setup failure isn't exactly quick, so this isn't likely to be a pleasant failover experience for a user, but beats nothing. Maybe.

There are occasionally glitches, subtleties and unexplained behaviours, but for the most part when things aren't broken in weird and interesting ways, the above is how I've seen it work over many years. Newer browsers are optimizing behaviour, and parallelizing stuff, and trying interesting things all the time, so check out the most recent docs for your given browser to understand the fine detail.
WinSock Proxy / ISA Firewall Client / TMG Client:
If you're interested in the Winsock Proxy Client (from TMG/ISA Server), that's a different story, with more flexibility and moving parts. Too much to go into here, but there are docs around which describe how it works. In short: it plugs into Windows Sockets, and can intercept both TCP/UDP based traffic and name resolution requests on a per-app and per-user basis. Very powerful, but also deprecated now, and hasn't been updated in several years.
Clients can be Really Clingy:
One final note: Once an HTTP client has decided to talk to a proxy for a given site/url, there's no way for the proxy to tell it not to.
There is no HTTP status code or header for "I don't serve that, you should just go directly to it instead"...
Once the client decides a particular URL is proxy-served, proxy-death-grip ensues.
The only way to avoid it is by getting the selection logic right before the client makes its connection, in the PAC or Bypass list.
A final note on Zones and PAC files
IE treats sites which are DIRECT connected - even if they have dots in the URL - to be part of the Local Intranet Zone (by default - settable in Zone properties), and so will do things like allow Integrated Windows Authentication to those sites (i.e. Kerberos and/or NTLM authentication, transparently). So controlling whether something's in the Local Intranet Zone defines how trusted it is in terms of automatic authentication. Again, at least, by default.

A: I'm not sure that your DNS part is right.  I have seen a machine with no valid DNS servers fetch pages in IE fine using a proxy.

A: I try in ubuntu 10.04, wine, IE 6.0 and squid 2.7(system have one dns and squid have other dns server)

*

*User send requests to proxy

*Squid send DNS request to DNS server

*Squid receive DNS answer. If nxdomain or other error, send error page to IE. If name resolve, fetch the page and give it to IE.

IE 6.0 doesn't resolve DNS name.

A: I don't think it is - if you type in the IP and the domain's in the exception list, or the domain, and the IP is in the exception list, it will probably still go via the proxy.
It is possible that a proxy.pac/wpad.dat would enable you to force your way out of this behaviour.


text:
Q: CheckBoxGroupInput reactivity I will be very appreciative if someone could help me to solve the behavior of the code below.  This is the logic: Only if A+B are selected A1 is showing up.  If A1 is selected "Buttons" is showing up.  But when A and/or B are deselected, only A1 is disappearing but "Buttons" are staying visible.  Of course, if A1 is deselected "Buttons" are disappearing...  I am aware that the A1 is still being selected even if A and/or B are deselected.  Wondering if there is an easy way to deselect A1 "automatically" when A and/or B are deselected.
And apologies in advance, if this is trivial question...
library(shiny)

ui <- fluidPage(

    checkboxGroupInput("choice",
                       "Choice",
                       choices  = c("A", "B"),
                       selected = NULL),

    conditionalPanel(
       condition='input.choice.indexOf("A") > -1 &&
                 input.choice.indexOf("B") > -1',
       h5(tags$b("Single checkbox")),
           checkboxInput(inputId = "a1", label = "A1", value = FALSE)),

     conditionalPanel(
       condition = "input.a1 == 1",
           radioButtons(inputId = "A11",
                        label = "Buttons",
                        choices = list("Bla" = 2, "Ble" = 3),
                        selected = 2)))

server <- function(input, output, session) {}

shinyApp(ui = ui, server = server)

A: Using an observer and an updateCheckboxInput you could do:
library(shiny)

ui <- fluidPage(
  checkboxGroupInput("choice",
    "Choice",
    choices  = c("A", "B"),
    selected = NULL
  ),
  conditionalPanel(
    condition = 'input.choice.indexOf("A") > -1 &&
                 input.choice.indexOf("B") > -1',
    h5(tags$b("Single checkbox")),
    checkboxInput(inputId = "a1", label = "A1", value = FALSE)
  ),
  conditionalPanel(
    condition = "input.a1 == 1",
    radioButtons(
      inputId = "A11",
      label = "Buttons",
      choices = list("Bla" = 2, "Ble" = 3),
      selected = 2
    )
  )
)

server <- function(input, output, session) {
  observe({
    if (!all(c("A", "B") %in% input$choice)) {
      updateCheckboxInput(inputId = "a1", value = FALSE)
    }
  })
}

shinyApp(ui = ui, server = server)


text:
Q: TFS Disk Structure - and "Add new folder" vs "Add solution" Our organization recently got TFS 2008 set up ready for our use. I have a practice TeamProject available to play with.
To simplify slightly, we previous organized our code on disk like this:
-EC
  - Main
     - Database
         - someScript1.sql
         - someScript2.sql
     - Documents
         - ReleaseNotes_V1.doc
     - Source
        - Common
           - Company.EC.Common.Biztalk.Artifacts [folder]
           - Company.EC.Common.BizTalk.Components [folder]
           - Company.EC.Common.Biztalk.Deployment  [folder]
           - Company.EC.BookTransfer.BizTalk.sln
        - BookTransfer
           - Company.EC.BookTransfer.BizTalk.Artifacts [folder]
           - Company.EC.BookTransfer.BizTalk.Components [folder]
           - Company.EC.BookTransfer.BizTalk.Components.UnitTest [folder]
           - Company.EC.BookTransfer.BizTalk.Deployment [folder]
           - Company.EC.BookTransfer.BizTalk.sln

I'm trying to decide, do I want to check in the entire c:\EC directory?
Or do I want to open each solution and checkin. What are the pros and cons of each?
It seems like by doing the "Add Files/Folder" option, I could check in everything at once and it would match the disk structure.
It also looks like that if I check in each solution separately, that creates another working folder in my Workspace.  I think if I check in by "add files/folder", I will have one workspace and that would be better.
But most of the books and samples I see talk about checking in projects and solutions.
P.S.  I know I need to add more to my disk structure in accordance with the Branch/Merge guidelines, but that is not the question I'm asking here.
Thanks,
Neal Walters

A: It's fine to check in outside of the solution explorer (e.g. from the Source Control explorer).  The one downside if you do that is that your solutions will not initially be bound to source control.  The next time someone would check out one of those files, they would have to manually (through a dialog) bind to the source control server.
If you have a limited number of solutions, adding the solution to source control is feasible.  However, make sure that you have those files in a directory mapped to your current workspace.


text:
Q: Deg. in rotation I am building time picker where you can set time on "real" clocks.
Im finding the position of mouse and degrees + rotating div using this script
var g;
        var h;
        if (e.target.id == "rotationSliderContainer") {

            g = e.offsetX;
            h = e.offsetY;
        } else {
            g = e.target.offsetLeft + e.offsetX;
            h = e.target.offsetTop + e.offsetY;
        }
        var atan = Math.atan2(g - radius, h - radius);
        deg = -atan / (Math.PI / 180) + 180;

        var presne = Math.abs(deg - (Math.round(deg / 30) * 30));

        if (presne <= 2) deg = Math.round(deg / 30) * 30;

        if(deg == 360)
                deg = 0;
        two.style.transform = "rotate(" + deg + "deg)";

it works fine but it has little bug , whenever i want to move div , between 12 and 1,2,3 its flipping between 12 and one of those values.
Here is a live demo http://jsfiddle.net/Trolstover/afo7ky03/1/
Is there any shortcut how to prevent this unwanted behavior or did i simply made a mistake somewhere?

A: This if/else condition is switching between events in the rotationSliderContainer and other DOM elements (such as the rotationSlider and the body).  That else condition is your culprit.
if (e.target.id == "rotationSliderContainer") {

        g = e.offsetX;
        h = e.offsetY;
    } else {
        g = e.target.offsetLeft + e.offsetX;
        h = e.target.offsetTop + e.offsetY;
    }

remove those two lines and it should be fine.
    if (e.target.id == "rotationSliderContainer") {

        g = e.offsetX;
        h = e.offsetY;
    }

Cool clock ^_^


text:
Q: TLS handshake fails between organizations I am running a custom Hyperledger Fabric network with TLS enabled in all communications. Everyting looks great inside of an organizations and CLI can connect to its org peers with TLS and CLIENTAUTH enabled. This is the status of the network:
org1
  - peer0
    anchor: true
    tls_enabled: true
    tls_clientauth_enabled: true
  - peer1
    tls_enabled: true
    tls_clientauth_enabled: true
  - orderer0
    tls_enabled: true
    tls_clientauth_enabled: false
org2
  - peer0
    anchor: true
    tls_enabled: true
    tls_clientauth_enabled: true
  - peer1
    tls_enabled: true
    tls_clientauth_enabled: true
  - orderer0
    tls_enabled: true
    tls_clientauth_enabled: false
org3
  - orderer0
    tls_enabled: true
    tls_clientauth_enabled: false

However, once I start a channel than involves multiple organizations, I get Gossip and TLS hanshake related errors. This is an example (log from peer0.org1):
2019-10-07 10:01:45.615 UTC [gossip.service] func1 -> INFO 046 Elected as a leader, starting delivery service for channel global
2019-10-07 10:01:48.620 UTC [ConnProducer] NewConnection -> ERRO 047 Failed connecting to {orderer0.org2:7050 [org1MSP org2MSP org3MSP]} , error: context deadline exceeded
2019-10-07 10:01:51.622 UTC [ConnProducer] NewConnection -> ERRO 048 Failed connecting to {orderer0.org1:7050 [org1MSP org2MSP org3MSP]} , error: context deadline exceeded
2019-10-07 10:01:54.638 UTC [ConnProducer] NewConnection -> ERRO 049 Failed connecting to {orderer0.org3:7050 [org1MSP org2MSP org3MSP]} , error: context deadline exceeded
2019-10-07 10:01:54.638 UTC [ConnProducer] NewConnection -> ERRO 04a Could not connect to any of the endpoints: [{orderer0.org2:7050 [org1MSP org2MSP org3MSP]} {orderer0.org1:7050 [org1MSP org2MSP org3MSP]} {orderer0.org3:7050 [org1MSP org2MSP org3MSP]}]
2019-10-07 10:01:54.638 UTC [deliveryClient] connect -> ERRO 04b Failed obtaining connection: could not connect to any of the endpoints: [{orderer0.org2:7050 [org1MSP org2MSP org3MSP]} {orderer0.org1:7050 [org1MSP org2MSP org3MSP]} {orderer0.org3:7050 [org1MSP org2MSP org3MSP]}]
2019-10-07 10:01:54.638 UTC [deliveryClient] try -> WARN 04c Got error: could not connect to any of the endpoints: [{orderer0.org2:7050 [org1MSP org2MSP org3MSP]} {orderer0.org1:7050 [org1MSP org2MSP org3MSP]} {orderer0.org3:7050 [org1MSP org2MSP org3MSP]}] , at 1 attempt. Retrying in 1s
2019-10-07 10:01:58.640 UTC [ConnProducer] NewConnection -> ERRO 04d Failed connecting to {orderer0.org2:7050 [org1MSP org2MSP org3MSP]} , error: context deadline exceeded
2019-10-07 10:01:59.833 UTC [core.comm] ServerHandshake -> ERRO 04e TLS handshake failed with error remote error: tls: bad certificate server=PeerServer remoteaddress=172.17.0.24:54590
2019-10-07 10:02:00.828 UTC [core.comm] ServerHandshake -> ERRO 04f TLS handshake failed with error remote error: tls: bad certificate server=PeerServer remoteaddress=172.17.0.24:54604
2019-10-07 10:02:01.642 UTC [ConnProducer] NewConnection -> ERRO 050 Failed connecting to {orderer0.org1:7050 [org1MSP org2MSP org3MSP]} , error: context deadline exceeded
2019-10-07 10:02:02.609 UTC [core.comm] ServerHandshake -> ERRO 051 TLS handshake failed with error remote error: tls: bad certificate server=PeerServer remoteaddress=172.17.0.24:54624
2019-10-07 10:02:04.647 UTC [ConnProducer] NewConnection -> ERRO 052 Failed connecting to {orderer0.org3:7050 [org1MSP org2MSP org3MSP]} , error: context deadline exceeded
2019-10-07 10:02:04.647 UTC [ConnProducer] NewConnection -> ERRO 053 Could not connect to any of the endpoints: [{orderer0.org2:7050 [org1MSP org2MSP org3MSP]} {orderer0.org1:7050 [org1MSP org2MSP org3MSP]} {orderer0.org3:7050 [org1MSP org2MSP org3MSP]}]
2019-10-07 10:02:04.647 UTC [deliveryClient] connect -> ERRO 054 Failed obtaining connection: could not connect to any of the endpoints: [{orderer0.org2:7050 [org1MSP org2MSP org3MSP]} {orderer0.org1:7050 [org1MSP org2MSP org3MSP]} {orderer0.org3:7050 [org1MSP org2MSP org3MSP]}]
2019-10-07 10:02:04.647 UTC [deliveryClient] try -> WARN 055 Got error: could not connect to any of the endpoints: [{orderer0.org2:7050 [org1MSP org2MSP org3MSP]} {orderer0.org1:7050 [org1MSP org2MSP org3MSP]} {orderer0.org3:7050 [org1MSP org2MSP org3MSP]}] , at 2 attempt. Retrying in 2s
2019-10-07 10:02:04.755 UTC [core.comm] ServerHandshake -> ERRO 056 TLS handshake failed with error remote error: tls: bad certificate server=PeerServer remoteaddress=172.17.0.19:48822
2019-10-07 10:02:05.755 UTC [core.comm] ServerHandshake -> ERRO 057 TLS handshake failed with error remote error: tls: bad certificate server=PeerServer remoteaddress=172.17.0.19:48836
2019-10-07 10:02:07.118 UTC [core.comm] ServerHandshake -> ERRO 058 TLS handshake failed with error remote error: tls: bad certificate server=PeerServer remoteaddress=172.17.0.19:48854
2019-10-07 10:02:09.651 UTC [ConnProducer] NewConnection -> ERRO 059 Failed connecting to {orderer0.org2:7050 [org1MSP org2MSP org3MSP]} , error: context deadline exceeded
2019-10-07 10:02:10.595 UTC [gossip.gossip] func1 -> WARN 05a Deep probe of peer0.org2:7051 failed: context deadline exceeded
github.com/hyperledger/fabric/gossip/gossip.(*gossipServiceImpl).learnAnchorPeers.func1
        /opt/gopath/src/github.com/hyperledger/fabric/gossip/gossip/gossip_impl.go:251
github.com/hyperledger/fabric/gossip/discovery.(*gossipDiscoveryImpl).Connect.func1
        /opt/gopath/src/github.com/hyperledger/fabric/gossip/discovery/discovery_impl.go:153
runtime.goexit
        /opt/go/src/runtime/asm_amd64.s:1333
2019-10-07 10:02:10.595 UTC [gossip.discovery] func1 -> WARN 05b Could not connect to Endpoint: peer0.org2:7051, InternalEndpoint: peer0.org2:7051, PKI-ID: <nil>, Metadata:  : context deadline exceeded

How can I solve it? I tried to share CA Pems between orgs and set CORE_PEER_TLS_CLIENTROOTCAS_FILES to "/public/org1/ca-chain.pem /public/org2/ca-chain.pem /public/org3/ca-chain.pem", but it does not work. Do I have to add the client cert for each peer/orderer to every one of my nodes? Where? Is this problem not related to TLS? I am really lost.
Thank you.

A: Have you specified CORE_PEER_TLS_CERT_FILE, CORE_PEER_TLS_KEY_FILE and CORE_PEER_TLS_ROOTCERT_FILE (this one is for the CA) for each peer?
And if you run your CA Server with TLS you have to specify the cert and keyfiles for TLS there as well.


text:
Q: malformed JSON Retrofit2 How to solve this error I get from the from android emulator

com.google.gson.stream.MalformedJsonException: Use JsonReader.setLenient(true) to accept malformed JSON at line 1 column 1 path $

private void registerToken(final String token) {

    Retrofit retrofit = new Retrofit.Builder()
            .baseUrl(Constants.BASE_URL)
            .addConverterFactory(GsonConverterFactory.create())
            .build();

    tokenPostAPI = retrofit.create(TokenPostAPI.class);
    Call<String> tokenPostCall = tokenPostAPI.request(token);

    studentPostCall.enqueue(new Callback<String>() {
        @Override
        public void onResponse(Call<String> call, Response<String> response) {
        }
        @Override
        public void onFailure(Call<String> call, Throwable t) {
            Log.e("token", "onFailure: "+t.toString() );
            Log.e("token", "onFailure: applied token "+token);
        }
    });
}

Here is the applied token =
"fQEG8hgG8oE:APA91bGKsH78Ft6wCDW2EtMsuC19EXl10pxkJ95ZrVwnmaofFcw8-TgxeASujQva_gM7gYijIduYL82TmR5qeExxaeHP_252ZOSx7in99ShnaKwE8bsnOyYBDAI4M34d3APCiJKpWDqC "

Total token CHARACTERS 152.

A: compile 'com.google.code.gson:gson:2.6.1'
Gson gson = new GsonBuilder()
        .setLenient() //building as lenient mode`enter code here`
        .create();

Retrofit retrofit = new Retrofit.Builder()
        .baseUrl(BASE_URL)
        .addConverterFactory(GsonConverterFactory.create(gson))
        .build();


text:
Q: Sine curve fit using lm, nls and nls2 in R I acquired data (motor adaptation =y in function of delays =t ) which I expect to look like a sine wave. I am trying to:

*

*Fit a sine curve in my data

*Estimate the best model/parameters.

I have read several posts here, here and here but I am still struggling.

1) Using lm
Code:
t<-c(0, 1, 2, 3, 4, 5, 6, 7, 8, 9)
y<-c(0.310 ,0.630 ,0.430 ,0.245, 0.650 ,0.085 ,0.370, 0.560 ,0.250, 0.520)
reslm <- lm(y ~ sin(pi/2*t)+ cos(pi/2*t)) #my period is supposed to be 4, so period equals to pi/2
summary(reslm)
rg<-(max(y)-min(y)/2)
plot(y~t)
lines(fitted(reslm)~t,col=4,lty=2)

Output:
lm(formula = y ~ sin(pi/2 * t) + cos(pi/2 * t))

Residuals:
     Min       1Q   Median       3Q      Max
-0.32450 -0.13956 -0.00325  0.14819  0.24450

Coefficients:
              Estimate Std. Error t value Pr(>|t|)
(Intercept)   0.404375   0.067993   5.947 0.000572 ***
sin(pi/2 * t) 0.005125   0.095190   0.054 0.958567
cos(pi/2 * t) 0.001125   0.095190   0.012 0.990900
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

Residual standard error: 0.2107 on 7 degrees of freedom
Multiple R-squared:  0.0004303, Adjusted R-squared:  -0.2852
F-statistic: 0.001507 on 2 and 7 DF,  p-value: 0.998

Graph:

Questions:

*

*I am super confused, how can I change the amplitude as well as the phase shift?

*How can I improve my fit using this methods?

2) Using nls
I used the equation y(t) = A*sin(Omega*t + Phi) + C where A is the amplitude, Omega the period, Phi the phase shift and C the midline.
Code:
t<-c(0, 1, 2, 3, 4, 5, 6, 7, 8, 9)
y<-c(0.310 ,0.630 ,0.430 ,0.245, 0.650 ,0.085 ,0.370, 0.560 ,0.250, 0.520)

A<- (max(y)-min(y)/2)
C<-((max(y)+min(y))/2)

res1<- nls(y ~ A*sin(omega*t+phi)+C, data=data.frame(t,y), start=list(A=A,omega=pi/2,phi=0,C=C))
summary(res1)
co <- coef(res1)
resid(res1)
sum(resid(res1)^2)
fit <- function(x, a, b, c, d) {a*sin(b*x+c)+d}
# Plot result
plot(x=t, y=y)
curve(fit(x, a=co["A"], b=co["omega"], c=co["phi"], d=co["C"]), add=TRUE ,lwd=2, col="steelblue")

Output:
Formula: y ~ A * sin(omega * t + phi) + C

Parameters:
       Estimate Std. Error t value Pr(>|t|)
A       0.21956    0.03982   5.513   0.0015 **
omega   2.28525    0.07410  30.841 7.72e-08 ***
phi   -32.57364    0.40375 -80.678 2.44e-10 ***
C       0.41146    0.02926  14.061 8.07e-06 ***
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

Residual standard error: 0.09145 on 6 degrees of freedom

Number of iterations to convergence: 18
Achieved convergence tolerance: 9.705e-06

Graph:

Questions:

*

*This methods seem to work a bit better, but how can I improve the fit using this method? I tried to change some parameters manually, for example, changing the phase shift (phi) does not do much or lead to an error (see part 3).

3) Using nls and nsl2, in order to tune my model
Code:
###nls2
t<-c(0, 1, 2, 3, 4, 5, 6, 7, 8, 9)
y<-c(0.310 ,0.630 ,0.430 ,0.245, 0.650 ,0.085 ,0.370, 0.560 ,0.250, 0.520)
A <- (max(y)-min(y)/2)
C<-((max(y)+min(y))/2)
pp <- expand.grid(omega=(c(2.094395, 1.570796,  1.256637)), phi=(-1:1), A=A, C=C) # omega = 2*pi/3, pi/2 , 2*pi/5
View(pp)
pp1<-data.frame(pp)
res2<- nls2(y ~ A*sin(omega*t+phi)+C, data=data.frame(t,y), start=pp1,  algorithm = "brute-force")
res2
summary(res2)
co <- coef(res2)
resid(res2)
sum(resid(res2)^2)
fit <- function(x, a, b, c, d) {a*sin(b*x+c)+d}
# Plot result
plot(x=t, y=y)
curve(fit(x, a=co["A"], b=co["omega"], c=co["phi"], d=co["C"]), add=TRUE ,lwd=2, col="steelblue")

#optimisation
res3<-nls2(y ~ A*sin(omega*t+phi)+C, start = res2)
res3
summary(res3)
co3 <- coef(res3)
resid(res3)
sum(resid(res3)^2)
fit <- function(x, a, b, c, d) {a*sin(b*x+c)+d}
# Plot result
plot(x=t, y=y)
curve(fit(x, a=co3["A"], b=co["omega"], c=co3["phi"], d=co3["C"]), add=TRUE ,lwd=2, col="steelblue")

Output:
First attempt (nls2 model1):
model: y ~ A * sin(omega * t + phi) + C
   data: data.frame(t, y)
 omega    phi      A      C
2.0944 0.0000 0.6075 0.3675
 residual sum-of-squares: 0.8545

Number of iterations to convergence: 9
Achieved convergence tolerance: NA
> summary(res2)

Formula: y ~ A * sin(omega * t + phi) + C

Parameters:
      Estimate Std. Error t value Pr(>|t|)
omega  2.09440    0.08453  24.776 2.84e-07 ***
phi    0.00000    0.46494   0.000   1.0000
A      0.60750    0.17851   3.403   0.0144 *
C      0.36750    0.12044   3.051   0.0225 *
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

Residual standard error: 0.3774 on 6 degrees of freedom

Number of iterations to convergence: 9
Achieved convergence tolerance: NA

Graph:

Second attempt (nls2 model2):
Nonlinear regression model
  model: y ~ A * sin(omega * t + phi) + C
   data: <environment>
  omega     phi       A       C
 2.2852 -1.1577  0.2196  0.4115
 residual sum-of-squares: 0.05018

Number of iterations to convergence: 12
Achieved convergence tolerance: 8.075e-06
> summary(res3)

Formula: y ~ A * sin(omega * t + phi) + C

Parameters:
      Estimate Std. Error t value Pr(>|t|)
omega  2.28524    0.07410  30.841 7.72e-08 ***
phi   -1.15769    0.40375  -2.867   0.0285 *
A      0.21956    0.03982   5.513   0.0015 **
C      0.41146    0.02926  14.061 8.07e-06 ***
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

Residual standard error: 0.09145 on 6 degrees of freedom

Number of iterations to convergence: 12
Achieved convergence tolerance: 8.075e-06

Graph:

Questions:

*

*So here it seems I misunderstood what nls2 was doing as I am finding exactly the same results as part 2. I still do not know which parameters are the best, how can I do this?

4) Using nls, in order to tune my model by looping through several parameters
Code:
t<-c(0, 1, 2, 3, 4, 5, 6, 7, 8, 9)
y<-c(0.310 ,0.630 ,0.430 ,0.245, 0.650 ,0.085 ,0.370, 0.560 ,0.250, 0.520)
A <- (max(y)-min(y)/2)
C<-((max(y)+min(y))/2)
pp <- expand.grid(omega=(c(2.094395, 1.570796,  1.256637)), phi=(-1:1), A=A, C=C) # omega = 2*pi/3, pi/2 , 2*pi/5
#View(pp)

fit_AIC<- vector()
fit_BIC<- vector()

coef_A<- vector()
coef_ome<- vector()
coef_phi<- vector()
coef_C<- vector()
RSS<-vector()

for (ii in 1:nrow(pp))
{
    res<- nls(y ~ A*sin(omega*t+phi)+C, data=data.frame(t,y), start=list(A=pp$A[ii],omega=pp$omega[ii],phi=pp$phi[ii],C=pp$C[ii]), trace = TRUE)
    fit_AIC[ii]<-AIC(res)
    fit_BIC[ii]<-BIC(res)

    coef_A[ii]<- coef(res)[1]
    coef_ome[ii]<- coef(res)[2]
    coef_phi[ii]<- coef(res)[3]
    coef_C[ii]<- coef(res)[4]
    RSS<-sum(resid(res)^2)

}

results<-data.frame(RSS, fit_AIC,  fit_BIC,  coef_A,  coef_ome,  coef_phi,  coef_C)
View(results)

Output:
I get this error:
1.405742 :   0.607500  2.094395 -1.000000  0.367500
0.1448148 :   0.1563179  2.1441802 -0.9937729  0.4172079

...

0.05018035 :   0.2195573  2.2852482 -1.1577097  0.4114573
2.085664 :  0.607500 1.570796 1.000000 0.367500
0.3104012 :  0.01321257 1.60518024 0.83201816 0.40437498
0.3098916 :   0.0180852  3.0888764 -5.9933691  0.4060743
Error in nls(y ~ A * sin(omega * t + phi) + C, data = data.frame(t, y),  :
  le pas 0.000488281 est devenu inférieur à 'minFactor' de 0.000976562

        RSS    fit_AIC    fit_BIC     coef_A  coef_ome    coef_phi    coef_C
1 0.05018035 -14.568398 -13.055473 0.21955754 2.2852455  -1.1576955 0.4114573
2 0.05018035   2.753153   4.266079 0.07487110 0.8575642   0.2299909 0.3916769
3 0.05018035   2.753153   4.266079 0.07487109 0.8575736   0.2299951 0.3916763
4 0.05018035 -14.568398 -13.055473 0.21955763 2.2852443  -1.1576894 0.4114573
5 0.05018035 -14.568398 -13.055473 0.21955729 2.2852490 -32.5736406 0.4114573
6 0.05018035   2.753153   4.266079 0.07487105 0.8575619   0.2300021 0.3916770
7 0.05018035 -14.568398 -13.055473 0.21955735 2.2852482  -1.1577097 0.4114573

Questions:

*

*So this error seems to be because my initial parameters are wrong. Is this correct? But how can I estimate the best parameters if the majority of parameters do not  work?

*Also, I do not understand why the RSS is always the same despite different parameters

*And why do I observe only 2 different AIC and 2 different BIC while the models are different?

Any kind of help would be much appreciated, thanks.

A: On the first model you're effectiveluy fitting the model y = A*sin(pi/2 * t) + B*cos(pi/2 * t) + C and you can't change the phase shift with that approach. On the next steps you can fit an appropiated equation. nls performs a non linear regresion with the provided model and nls2 adds an extra step by creating a grid of  initial parameters and performing several nls calls. And in the last approach you coded a similar strategy as nls2. But some initial conditions lead to an error.
The objetive function that you minimize have multiple local minima, just like in the example the function have multiple minima with different coordinates.

Also when you change the equation to y ~ A * sin(omega * t + phi) + C you have four parameters to be determinated  and only nine data points you need to add more data points to get a better estimation of the parameters. You can also normalize the data to 0-1 range.
Hope it helps

A: *

*Using lm:
Your period is ~2.75 instead of 4.

  t<-c(0, 1, 2, 3, 4, 5, 6, 7, 8, 9)
  y<-c(0.310 ,0.630 ,0.430 ,0.245, 0.650 ,0.085 ,0.370, 0.560 ,0.250, 0.520)

  reslm <- lm(y ~ cos(2* pi/2.75*t) + sin(2* pi/2.75*t))

  summary(reslm)

  coef1 <- coef(reslm)

  plot(y~t)

  t1 <- seq(0,9,.1)
  y1 <- coef1[2] * cos(2*pi/2.75*t1) + coef1[3] * sin(2* pi/2.75*t1) + coef1[1]

  lines(t1,y1,col=2)


text:
Q: How to use less jQuery in jQuery accordion Here's a jsfiddle that works great. The HTML is good, but the problem is there's a LOT of jQuery. I'm sure there's a better way. Any help would be great!
https://jsfiddle.net/jrmleduc/q9dboshu/
<input type="radio" value="true" name="1" id="1">

One

<input type="radio" value="true" name="2" id="2">

Two

<input type="radio" value="true" name="3" id="3">

Three

$("input[name='1']").attr("checked", false);
$("input[name='3']").attr("checked", false);
$("input[name='2']").attr("checked", false);
$("span.classname1").toggle(this.value === "false");
$("span.classname2").toggle(this.value === "false");
$("span.classname3").toggle(this.value === "false");

$("input[name='1']").on("click", function(){
    $("span.classname1").toggle(this.value === "true");
    $("span.classname2").toggle(this.value === "false");
    $("span.classname3").toggle(this.value === "false");
    $("input[name='2']").attr("checked", false);
    $("input[name='3']").attr("checked", false);
});

$("input[name='2']").on("click", function(){
    $("span.classname1").toggle(this.value === "false");
    $("span.classname2").toggle(this.value === "true");
    $("span.classname3").toggle(this.value === "false");
    $("input[name='1']").attr("checked", false);
    $("input[name='3']").attr("checked", false);
});

$("input[name='3']").on("click", function(){
    $("span.classname1").toggle(this.value === "false");
    $("span.classname2").toggle(this.value === "false");
    $("span.classname3").toggle(this.value === "true");
    $("input[name='1']").attr("checked", false);
    $("input[name='2']").attr("checked", false);
});

A: This is a little fragile, but this is a quick way to do it.
const allInputs = $('input');

// Loop through all inputs,
// if checked, show the span, else hide the span
const showOnlyChecked = function(){
    allInputs.each(function(index, item){
    if (item.checked === false){
        $(item).next().next().hide(); // next() >
 > next() > <span?
    } else {
        $(item).next().next().show();
    }
    })
}

showOnlyChecked();
$('body').on('click', 'input', showOnlyChecked);

JS Fiddle
You should know that if you give all the radio boxes the same name="" attribute, then by default the browser will only let you select one of the group. That's just how Radio Buttons work...
Learn About Radio Buttons

A: If you add some more generic classes to your HTML, you can use those to select the entire group of elements more easily.
<input type="radio" value="true" name="1" id="1" class="accordion-radio">

One

<input type="radio" value="true" name="2" id="2" class="accordion-radio">

Two

<input type="radio" value="true" name="3" id="3" class="accordion-radio">

Three

Then you can condense your code down and take advantage of jQuery's use of $(this) to select the item currently firing the event handler and use the fact to have unique id attributes on your elements.
$("input.accordion-radio").prop("checked", false);
$("span.accordion-label").toggle(this.value === "false");

$("input.accordion-radio").on("click", function(){
    $("span.accordion-label").toggle(this.value === "false");
    $("input.accordion-radio").not("#"+$(this).attr("id")).prop("checked", false);
    $("span.classname" + $(this).attr("id")).toggle(this.value === "true");
});

JSFiddle Example

A: CSS only solution:

input[name="radio"]+br+span {
  display: none;
}

input[name="radio"]:checked+br+span {
  display: block;
}
<input type="radio" name="radio" id="1">

One

<input type="radio" name="radio" id="2">

Two

<input type="radio" name="radio" id="3">

Three


text:
Q: How to display page views on the page using google analytics
Possible Duplicate:
Use Google Analytics for data to display on our webpage?

I am using google analytics to track page views and other metrics. I want to display some of the metrics about particular page on the page itself.
How do i do that?
Its more like a public statcounter for that page i need to display.
My solutions is in ASP.net MVC 3

A: You will need to use the Data Export API. Here is some documentation:
General Dev Info: https://developers.google.com/gdata/docs/developers-guide
.NET Protocol: http://code.google.com/p/google-gdata/


text:
Q: Calculating the mean using regression data I have some data to analyze where $y$ is dependent of $x$ - a linear regression was used.
It's a question from an exam, so I think it should be solvable. The regression was used to estimate the mean miles per gallon (response) from the amount of miles driven (predictor).
I have the following statistics available:

*

*Correlation coefficient (0.117)

*Standard deviation (0.482)

*Number of observations (101)

An ANOVA of this regression yields (Regression and residuals, respectively):

*

*df: 1, 99

*SS: 0.319, 22.96

*MS: 0.319, 0.232

*F-value: 1.374, critical F-value: 0.244

The regression itself (Intercept and Slope, respectively):

*

*Coefficients: 6.51, -0.00024

*Standard deviations: 0.186, 0.0002

*t-Values: 34.90, -1.17

*p-Values: 1.93E-57, 0.2439

Also, the "upper and lower 95% and 99%" are given for the above regression (although I'm not sure what that means).
Now, I am asked to calculate the mean $y$ for several values $x$, that's relatively easy, I just use the coefficients. So for example, I can calculate the mean miles per gallon for 500 miles driven.
Part where I'm stuck: I need to calculate the 99% confidence interval for the mean of $y$.. Obviously, this is what the example is all about - the introduction states that the mileage of a car should be estimated.
My question: How can I find out the mean of $y$ using the data provided above? (And, subsequently, the 99% confidence interval, although I seem to have the standard deviation, so that shouldn't be the problem)

A: Contrary to @whuber's claim, the mean of x and y are contained in the information given.
Okay, so you have the line equation
$$y_i=\alpha +x_i\beta + e_i$$
estimates $\hat{\beta}=r\frac{s_y}{s_x}$ and $\hat{\alpha}=\overline{y}-\hat{\beta}\overline{x}$.
where $r$ is the correlation.  The question doesn't state whether the standard deviation (0.482) is for $s_y$ or $s_x$ (the MLE standard deviation, with divisor $n$).  Either way, you can work out the either from the info given.  for their ratio must satisfy:
$$\frac{\hat{\beta}}{r}=\frac{s_y}{s_x}$$
The slope can't be negative if the correlation is positive, so I have assumed that you have done something incorrectly (for you have correlation of 0.117, and slope of -0.00024; this is impossible).  This will affect the numbers, but not the general method.  So I will assume the standard deviations are both known, but not write in the specific values.  The same goes for the rest of the actual numbers.
Now the variance of $\hat{\beta}$ is given by:
$$var(\hat{\beta})=s_e^2(X^TX)^{-1}_{22}=\frac{s_e^2 (X^TX)_{11}}{|X^TX|}$$
Note that $(X^TX)_{11}=n$ and $s_e^2$ is the "mean square error".  The variance of $\alpha$ is given by:
$$var(\hat{\alpha})=s_e^2(X^TX)^{-1}_{11}=\frac{s_e^2 (X^TX)_{22}}{|X^TX|}$$
Now $(X^TX)_{22}=\sum_i x_i^2 = n(s_x^2+n\overline{x}^2)$
And dividing these two variances gives:
$$\frac{var(\hat{\alpha})}{var(\hat{\beta})}=\frac{(X^TX)_{22}}{(X^TX)_{11}}=\frac{n(s_x^2+n\overline{x}^2)}{n}=s_x^2+n\overline{x}^2$$
Now all quantities in the equation are known, except for the mean $\overline{x}$.  So we can re-arrange this equation and solve for the mean:
$$\overline{x}=\pm\sqrt{\frac{\frac{var(\hat{\alpha})}{var(\hat{\beta})}-s_x^2}{n}}$$
But we know from the start that $x_i>0$ - you can't drive "negative miles".  So only the positive square root is to be taken.  The rest is straight-forward CI stuff.  The estimate of the mean $\hat{\overline{y}}$ is given by:
$$\hat{\overline{y}}=\hat{\alpha}+\hat{\beta}\overline{x}=\hat{\alpha}+\hat{\beta}\sqrt{\frac{\frac{var(\hat{\alpha})}{var(\hat{\beta})}-s_x^2}{n}}=\overline{y}$$
And the variance is given by:
$$var(\hat{\overline{y}})=var(\hat{\alpha})+\overline{x}^2 var(\hat{\beta})+2\overline{x}cov(\hat{\alpha},\hat{\beta})$$
Now the covariance is equal to:
$$cov(\hat{\alpha},\hat{\beta})=s_e^2(X^TX)^{-1}_{21}=-\frac{s_e^2 (X^TX)_{21}}{|X^TX|}=-\frac{s_e^2 n\overline{x}}{ns_x^2}=-\frac{s_e^2 \overline{x}}{s_x^2}$$
And so the variance is given by:
$$var(\hat{\overline{y}})=var(\hat{\alpha})+\overline{x}^2 var(\hat{\beta})-2\frac{s_e^2 \overline{x}^2}{s_x^2}=var(\hat{\alpha})+\frac{\frac{var(\hat{\alpha})}{var(\hat{\beta})}-s_x^2}{n}\left(var(\hat{\beta})-2\frac{s_e^2}{s_x^2}\right)$$
So you construct your $100(1-P)$% confidence interval by choosing $T_{1-P/2}^{(n-2)}$ as the $P/2$ quantile of standard T distribution with $n-1$ degrees of freedom (which effectively equal to the standard normal, as $n-1=100$), and you have:
$$CI=\overline{y}\pm T_{1-P/2}^{(n-2)}\sqrt{var(\hat{\overline{y}})}$$
And all quantities are calculable, given the information.


text:
Q: Deleting contents of file after success I want to run the same Powershell command for every OU.
The list of OUs is given in a text file.
**Powershell command:**
run_script OU1
run_script OU2

**Text File:**
OU1
OU2
...

So far I have written the following logic:
$OUnames = Get-Content("C:\ouNames.txt");
foreach ($OU in $OUnames)
{
    $output = run_script $OU
      if($output -contains "success")
      // then delete $OU from ouNames.txt
      // and inlcude $OU in the file ouNamesAdded.txt
}

How to delete the OU from the first text file after the run_script $OU returns success for a particular OU. Also, how to add $OU to another file ouNamesAdded.txt
How can I pickup multiple OU from the C:\ouNames.txt and then run run_script $OU in parallel for multiple OUs

A: For adding new OU content to a new file, you can use Add-Content:
$OU | Add-Content "ouNamesAdded.txt"

For removing content, I would just do that after you finish the loop. You can remove the -whatif parameter if you are happy with the command.
Compare-Object -ReferenceObject (Get-Content ouNames.txt) -DifferenceObject (Get-Content ouNamesAdded.txt) -PassThru | Set-Content ouNames.txt -whatif

I don't know of anything that will just delete a line from a file. If you want to delete an OU from the file after every iteration, you will need to do something like the following:
# Execute within the if statement
Get-Content ouNames.txt -notmatch "^$OU$" | Set-Content ouNames.txt
# Or using the $OUNames array (more efficient)
$OUnames -notmatch "^$OU$" | Set-Content ouNames.txt

If you want to track a list and do real-time deletions, I would use something like an arraylist:
# Run this before the loop code
$OUs = $OUnames.clone() -as [system.collections.arraylist]
# Run this within the if statement
$OUs.Remove($OU)
# After the loop completes, then write to the output file
$OUs | Set-Content "ouNamesAdded.txt"

A: Here's what I cooked up:
    $OUnames = Get-Content("C:\ouNames.txt")
foreach ($OU in $OUnames)
{
$output = run_script $OU
  if($output -contains "success")
  {
   $OUs = Get-Content("C:\ouNames.txt")
   $OUs -notmatch "$OU" | Out-File "C:\ouNames.txt"
   $OU | Out-File "C:\ouNamesAdded.txt" -Append
  }
}

This code will go through the text file and run the "run_script' command on each of them. If successful, it will grab all the text in the file that doesn't match the successful OU, and write that to the text file, effectively erasing the string that ran successfully. It'll then write the successful string to a new "ouNamesAdded' text file.


text:
Q: Target necessary frameworks in order to support mixed project types I am currently using asp.net-core 2.1 with several .net-core 2.1 libraries. Two of the projects are based on an ef-core 2.1 library and a model library. I now need to develop a Windows service that references both of those projects, I assumed I could simply switch them to netstandard 2.0.
According to Package Microsoft.AspNetCore.All 2.1.0 is not compatible with netcoreapp2.0, this is possible, however I have the following set in the asp.net core project (using sdk 2.1.400):
<TargetFramework>netcoreapp2.1</TargetFramework>

but it fails to compile with:
NU1202 Package Microsoft.AspNetCore.App 2.1.0 is not compatible with netstandard2.0 (.NETStandard,Version=v2.0). Package Microsoft.AspNetCore.App 2.1.0 supports: netcoreapp2.1 (.NETCoreApp,Version=v2.1)

Anyone know how I can leverage the ef core and model libs in a Windows service?

A: Copied from the comment.
Most ASP.NET Core packages are .NET Standard 2.0 compliant, but the meta package Microsoft.AspNetCore.App is not.
So to re-target your two projects to .NET Standard 2.0, you need to remove the package reference to .App, and use references to the individual packages instead, like you discovered.


text:
Q: Multi Columns Combo Box for Swing currently, I am looking for a multi columns comb box components which can place in my Java Swing application.
Currently, I use combo box as auto complete drop down list as user is typing.

Is there any available GUI component, which enable me to have the following (multi collumns)? As you can see, there are 3 columns in the drop down list, as opposed to 1 column in the above example.

Thanks.

A: Here is a downloadable solution with two columns.
There are other candidates here and here but you need to write your own renderer.


text:
Q: Unit testing requires many interfaces? I'm currently working on my first project that uses TDD and unit testing. I'm writing in C++ with googletest and googlemock libraries. The project requires many small classes with particular functionalities. I mostly use dependency injection in constructors. According to this:
When should I mock? and
When to use mock objects in unit tests
dependency injected into constructor is good candidate for mocking in unit testing. There are two ways to do this in C++:

*

*Creating interface (pure virtual class). Production class and mock class derives from it.

*Create virtual member functions inside Production class. Mock class derives from Production class. There is a problem when Production class does not define default constructor. Mock class has to call Base class constructor explicitly (personally it is not the stuff that mock object should do).

How do you handle this kind of situation? Do you prefer many interfaces (N classes requires N interfaces) or deriving from Base class?

A: There is no single best answer to a question like this, but I can share some experience from my team. The approach we use is the following. The project is split into something we internally call "modules". These are basically just C++ classes, but what is special about them is that those are the biggest/most important classes in the project. Interfaces of these classes are exposed to other modules (this is configured via CMake) so they can be used with one another. Each module is a small static library, and inside that library there are additional C++ classes that are necessary only to complete the functionality of the containing module, but are irrelevant to other modules. These are configured to be private withing the module (again via CMake) and other modules have no knowledge of these classes.
So after a short explanation of how our project is organized, getting back to your question:

*

*For the main classes of the module (usually 1-3) that need to be exposed to other modules, we create an interface (pure virtual class) with detailed documentation (precise contract detailing how the client should use the class, sequence diagrams, detailed documentation for all methods, etc.). Then we have a mock that inherits from this interface and it is exposed to other modules, and an implementation class (what you call Production class) that also inherits but is private withing the module (other classes don't need the implementation details, only knowledge how to create and use an instance of the interface).

*For other classes that are private within each module, we just create virtual methods inside Production class to keep things simpler, and their mocks just inherit from the Production class. By the way, your issue with the default constructor should easily be solved by declaring a protected default constructor in the Production class?
In my opinion, this provides a good balance between avoiding too much boilerplate code (by having an interface for every single class), but also providing nice, clean and precisely defined interfaces for the most important classes in your project.


text:
Q: Other thread does not wake up even after notifying and releasing the lock in python import time
from threading import *
import random

class appointment:
    def patient(self):
        for _ in range(2):
            condition_object.acquire()
            print('patient john waiting for appointment')
            condition_object.notify()
            condition_object.wait() # Thread is in waiting state
            print('patiend john successfully got the appointment')
        condition_object.notify()
        condition_object.release()
        print('patient john is done')

    def doctor(self):
        for _ in range(2):
            print('doctor in chamber')
            condition_object.acquire()
            print('doctor jarry checking the time for appointment')
            time=0
            time=random.randint(1,13)
            print('oppointed time is {} PM'.format(time))
            condition_object.notify()
            print('doctor is going to wait')
            condition_object.wait(1.1)
        print('doctor is about to leave')
        condition_object.release()
        print('doctor is done')

condition_object = Condition()
class_obj=appointment()

T1 = Thread(target=class_obj.patient)
T2 = Thread(target=class_obj.doctor)

T1.start()
T2.start()

T1.join()
T2.join()
print("\nEND\n")

This a typical consumer producer threading code. And at the end of 2 loops, I expect that when patient thread notifies other thread and releases the lock, the waiting doctor thread would wake up. But the waiting doctor thread is not waking up (even if I set a timer).
The doctor thread wakes up if I use wait() at the end of the patient() function instead of release, but then the patient function isn't waking up after I release the lock from the doctor thread. I'm really confused.
Why isn't doctor thread waking up after release of lock from the other thread?
And
Why is the doctor thread waking up only after wait() is called from the other thread?

A: I changed your code the following way and it seems that it works as it should:
from threading import *
import random

class Appointment:
    def __init__(self, cond: Condition):
        self.cond = cond

    def patient(self):
        with self.cond:
            for _ in range(2):
                print('Patient John waiting for appointment')
                self.cond.notify()
                self.cond.wait()  # Thread is in waiting state
                print('Patient John successfully got the appointment')
                self.cond.notify()
        print('Patient John is done')

    def doctor(self):
        print('Doctor in chamber')
        with self.cond:
            for _ in range(2):
                print('Doctor Jarry checking the time for appointment')
                t = random.randint(1, 13)
                print('appointed time is {} PM'.format(t))
                self.cond.notify()
                print('Doctor is going to wait')
                self.cond.wait()
            print('Doctor is about to leave')
        print('Doctor is done')

if __name__ == '__main__':
    _condition_object = Condition()
    class_obj = Appointment(_condition_object)
    ths = [Thread(target=class_obj.patient), Thread(target=class_obj.doctor)]
    [th.start() for th in ths]
    [th.join() for th in ths]
    print("\nEND\n")

A: As stated in https://docs.python.org/3/library/threading.html#threading.Condition

If the lock argument is given and not None, it must be a Lock or RLock
object, and it is used as the underlying lock.  Otherwise, a new RLock
object is created and used as the underlying lock.

And as stated in https://docs.python.org/3/library/threading.html#threading.RLock

A reentrant lock must be released by the thread that acquired it.
Once a thread has acquired a reentrant lock, the same thread may
acquire it again without blocking; the thread must release it once for
each time it has acquired it

So, the problem with my code was that were more calls to acquire the RLock than to release it. Hence as https://stackoverflow.com/a/67617044/13023201 this answer shows, using a with clause with the Condition object or calling acquire outside the loop solves the problem.


text:
Q: Making GCP bucket default storage in Django I am not using App Engine.
I have deployed my Django server in my GCP instance and using Django root location for the storage. However, I want to access the GCP bucket and make it as the default storage location for uploading and sending the path to the function used in the views.py
Here's a link Configure Django and Google Cloud Storage?
From the URL above, I think that the issue can be solved but I'm unable to understand where to deploy the code: settings.py or views.py?
Is it possible that someone can help me with steps?


text:
Q: wsdl2py requests I'm trying to get results from a SOAP service called Chrome ADS (for vehicle data). They provided php and Java samples, but I need python (our site is in Django). My question is:
What should I be passing as a request to the SOAP service when using wsdl2py-generated classes?
Following the examples I'm using a DataVersionsRequest object as the request parameter, but the code generated by wsdl2py seems to want a getDataVersions object, and there's something like that defined at the bottom of the generated _client.py file. But that too seems to throw an error. So I'm not sure what I should be passing as the request obj.  Any suggestions?
$sudo apt-get install python-zsi
$wsdl2py http://platform.chrome.com/***********
$python
>>> url = "http://platform.chrome.com/***********"
>>> from AutomotiveDescriptionService6_client import *
>>> from AutomotiveDescriptionService6_types import *
>>> locator = AutomotiveDescriptionService6Locator()
>>> service = locator.getAutomotiveDescriptionService6Port()
>>> locale = ns0.Locale_Def('locale')
>>> locale._country="US"
>>> locale._language="English"
>>> acctInfo = ns0.AccountInfo_Def('accountInfo')
>>> acctInfo._accountNumber=*****
>>> acctInfo._accountSecret="*****"
>>> acctInfo._locale = locale
>>> dataVersionsRequest = ns0.DataVersionsRequest_Dec()
>>> dataVersionsRequest._accountInfo = acctInfo
>>> service.getDataVersions(dataVersionsRequest)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "AutomotiveDescriptionService6_client.py", line 36, in getDataVersions
    raise TypeError, "%s incorrect request type" % (request.__class__)
TypeError: <class 'AutomotiveDescriptionService6_types.DataVersionsRequest_Dec'> incorrect request type
>>> dataVersionsRequest = getDataVersions
>>> dataVersionsRequest._accountInfo = acctInfo
>>> service.getDataVersions(dataVersionsRequest)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "AutomotiveDescriptionService6_client.py", line 36, in getDataVersions
    raise TypeError, "%s incorrect request type" % (request.__class__)
AttributeError: class DataVersionsRequest_Holder has no attribute '__class__'
>>> quit()
$cat AutomotiveDescriptionService6_client.py
.....
# Locator
class AutomotiveDescriptionService6Locator:
    AutomotiveDescriptionService6Port_address = "http://platform.chrome.com:80/AutomotiveDescriptionService/AutomotiveDescriptionService6"
    def getAutomotiveDescriptionService6PortAddress(self):
        return AutomotiveDescriptionService6Locator.AutomotiveDescriptionService6Port_address
    def getAutomotiveDescriptionService6Port(self, url=None, **kw):
        return AutomotiveDescriptionService6BindingSOAP(url or AutomotiveDescriptionService6Locator.AutomotiveDescriptionService6Port_address, **kw)

# Methods
class AutomotiveDescriptionService6BindingSOAP:
    def __init__(self, url, **kw):
        kw.setdefault("readerclass", None)
        kw.setdefault("writerclass", None)
        # no resource properties
        self.binding = client.Binding(url=url, **kw)
        # no ws-addressing

    # op: getDataVersions
    def getDataVersions(self, request, **kw):
        if isinstance(request, getDataVersions) is False:
            raise TypeError, "%s incorrect request type" % (request.__class__)
        # no input wsaction
        self.binding.Send(None, None, request, soapaction="", **kw)
        # no output wsaction
        response = self.binding.Receive(getDataVersionsResponse.typecode)
        return response
.....
getDataVersions = GED("urn:description6.kp.chrome.com", "DataVersionsRequest").pyclass

Also, as an aside, I'm not sure that the strings I'm passing to the pname parameter are correct, I assume that those are the ones I see inside the XML when I explore the service with SOAP UI, right?

A: It looks like you might be passing a class to service.getDataVersions() the second time instead of an instance (it can't be an instance if it doesn't have __class__).
What's happening is isinstance() returns false, and in the process of trying to raise a type error, an attribute error gets raised instead because it's trying to access __class__ which apparently doesn't exist.
What happens if you try:
>>> dataVersionsRequest = getDataVersions**()**
>>> dataVersionsRequest._accountInfo = acctInfo
>>> service.getDataVersions(dataVersionsRequest)

?
Based on the line:
if isinstance(request, getDataVersions) is False:
            raise TypeError, "%s incorrect request type" % (request.__class__)

it definitely looks like you should be passing an instance of getDataVersions, so you're probably on the right track.

A: You probably need to be instantiating your definition objects and then populating them. Look for type == pyclass_type objects associated with the request you're wanting to make and instantiate them.
e.g. (just guessing)
>>> versionrequest = getDataVersions()
>>> versionrequest.AccountInfo = versionrequest.new_AccountInfo()
>>> versionrequest.AccountInfo.accountNumber = "123"
>>> versionrequest.AccountInfo.accountSecret = "shhhh!"
>>> service.getDataVersions(versionrequest)

I found that the code generated by wsdl2py was too slow for my purposes. Good luck.


text:
Q: R: How to combine duplicated rows from multiple columns based on unique values in a single column and merge those unique values by |? I have the following data frame:
gene    gene_name   source  chromosome  details
1       a           A           2       01; xyz
1       a           A           2       02; ijk
2       b           B           3       03; efg
2       b           C           3       03; efg
3       c           D           4       04; lmn
3       c           D           4       05; opq
3       c           D           4       06; rst
4       NA          10          6       NA
4       NA          11          6       NA

I want to get the following output:
gene    gene_name   source  chromosome  details
1       a           A       2           01; xyz | 02;ijk
2       b           B, C    3           03; efg
3       c           D       4           04; lmn | 05; opq | 06; rst
4       NA          10, 11  6           NA | NA

I have tried to use aggregate() and group_by() in different ways, but did not get it.
Please guide.
Thanks.

A: This should work:
df %>%
  group_by(gene, gene_name, source, chromosome) %>%
  summarise(details = paste(details, collapse = " | "))

I ran the below on iris and got a result similar to as you described
iris %>%
  group_by(Sepal.Length, Sepal.Width, Petal.Length, Species) %>%
  summarise(Petal.Width = paste(Petal.Width, collapse = " | "))