text:
Q: Abstract class or interface. Which way is correct? There are two way for choosing between abstract class or interface. Microsoft solution and Oracle solution:

Microsoft, design guideline:
Do use abstract (MustInherit in Visual Basic) classes instead of interfaces to decouple the contract from implementations.
http://msdn.microsoft.com/en-us/library/ms229013.aspx

Oracle, The Java Tutorials:
If an abstract class contains only abstract method declarations, it should be declared as an interface instead.
http://docs.oracle.com/javase/tutorial/java/IandI/abstract.html

My question is which way is correct? Microsoft or Oracle solution? Note that I think choose between abstract class or interface should not depends on programming language (Java or C#).

A: They are 2 statements for different contexts.
The Microsoft guideline you quote from is for "Designing Class Libraries". And it states the reason for favoring abstract classes there: you can add functionality without breaking anything.
For separation and decoupling over layers and other boundaries, Microsoft also advices interfaces.

A: If I recall my blog reading correctly, the Microsoft advice to use abstract classes stems from the ability to reuse implementation with an abstract class, something you can't do with an interface.
Note also that the Microsoft page you linked to is specifically guidance for writing code libraries for sharing/reuse across multiple projects. The likelihood in this situation is that you'll be writing all the implementations of the interface yourself, probably within the same assembly. Good practices for working on a single product or system will vary somewhat.
One common approach that I've seen across a number of codebases in a number of languages is this:

*

*Define an interface to specify the contract

*Create an abstract class implementing the contract to provide any common implementation useful to all descendants

*Implementations of the contract then have the option to start from the base class for convenience, or just to implement the interface if they want full control

A fourth step common in the .NET world is to provide convenience extension functions built on the interface.

A: An interface carries no implementation - it's a contract.  It allows for complete decoupling.
I will go from an interface to an abstract (base) class if I want to provide some common implementation while forcing on the inheriting class concrete class to provide some implementation specific to that class.  That's provides a little less decoupling.
Also be aware that many languages like C# (and .net languages like VB.net etc...) as well as Java do not allow multiple inheritance so interfaces become a way of allowing a class to have many behaviors.


text:
Q: Как автоматически раздать ключ при занесении значения в объект? Есть такой код (подрезал для упрощения):

let names = {
    0: 'name1',
    1: 'name2',
    2: 'name3'
};

class Element extends React.Component {

    ....

    handleAddElement = (e) => {
        e.preventDefault();
        this.setState({
            input:''
        });
        let result = this.input;
    }

    render () {
        let brand = this.props.brand;
        return (
        .... {names[brand]} ....
        );
    }
}

function App () {
    return (
            <div>
                <Element brand="0"/>
                <Element brand="1"/>
                <Element brand="2"/>
            </div>
    );
}

Мне нужно, чтобы из handleAddElement результат инпута добавлялся в объект и у него автоматически ставился ключ. Также мне нужно, чтобы в функции App автоматически выставлялся ключ brand. Подскажите как реализовать.

A: Что бы отрендерить массив вам нужен метод map https://reactjs.org/docs/lists-and-keys.html

redpajama_set_name: RedPajamaStackExchange


text:
Q: How do they know Magnetic Field Lines run from South to North inside a magnet? I get how they can plot the field lines outside the magnet, but how do they know how it runs inside the magnet to form a closed loop? Isn't the direction fo the field lines the direction of the force acting on a north pole placed at that point in the field? Then what would be the direction of the force acting on a hypothetical North Pole at the center of the magnet. Thanks!:(Image Attached)

A: There are two (2) kinds of field inside a magnetic material $\mathbf B$ and $\mathbf H$. The one that has continuous loops is $\mathbf B$ field and it is "surface thing" by which is meant that if you cut a thin disk, a crevasse as Thomson called it, out of the material whose normal is parallel with the direction of $\mathbf B$ then this field across the slit is continuous. On the contrary, if you cut a thin cylinder, a  needle out of the material that is parallel with $\mathbf H$ field then $\mathbf H$ is continuous across the needle. Here $\mathbf B = \mu_0(\mathbf  H + \mathbf M)$, where $\mathbf M$ is the local magnetization density of the material. Inside a long permanent magnet the fields $\mathbf B$ and $\mathbf H$ are in opposite direction, the field lines of $\mathbf B$ are closed continuous loops but that of $\mathbf H$ are not closed originate but start at one pole and end at the other.
Within the crevasses, disks or needles, one can measure the local fields. If you place a wire loop in the disk you can measure the induced voltage when changing the $\mathbf B$ and its flux rate $\Phi$ in time, and thus both field magnitude and direction can be ascertained.
If you place a magnetic needle inside the thin cylinder carved out of the magnetic material then $\mathbf H$ will exert a torque and force that can be measured from which the field magnitude and its direction can be deduced.

A: Permanent magnets have their magnetic field from the self-sustaining alignment of the magnetic dipoles of the electrons involved in the magnetic body.
You can therefore imagine - in a very simplified way - the permanent magnet as a multitude of small bar magnets. Together, these produce the magnetic field that is represented by the field lines in your sketch.
The direction of the arrow on the outside is therefore the continuation of the inner orientation.


text:
Q: convert if/else to case I was wondering if anyone out there is able and willing to assist me.
In my Sql Server stored procedure I have a series of if / else if statements, I would like a little assistance to change it to case...when...then as I feel it would be more efficient and look less messy.
I am not asking for you to do it for me just a quick example to enable me to get my head around it.
My strored procedure is as follows...
CREATE PROCEDURE [Blog].[ttc_BlogPosts]
@Status varchar(50) = '' ,
@EntryId int = '',
@Title nvarchar(max) = '',
@Added datetime = '',
@Updated datetime = '',
@Message nvarchar(max) = '',
@ImgId int = '',
@ImgUrl nvarchar(max) = ''

AS
BEGIN
     IF(@Status = 'Display')
       begin
            select Id, EntryTitle, Message, ImageUrl, DateAdded, LastEdited
            from Blog.BlogEntry
            order by DateAdded desc
       end

     else if(@Status = 'AddPost')
            begin

                insert into Blog.BlogEntry (EntryTitle, Message, DateAdded, ImageUrl)
                values (@Title, @Message, GETDATE(), @ImgUrl)
            end
          else if(@Status = 'DisplayPost')
                 begin
                      select EntryTitle, DateAdded, LastEdited, Message, ImageUrl
                      from Blog.BlogEntry
                      where Id = @EntryId
                  end
               else if(@Status = 'UpdatePost')
                      begin
                          update Blog.BlogEntry
                          set EntryTitle = @Title, Message = @Message, LastEdited = GETDATE()
                          where Id = @EntryId
                      end
                    else if(@Status = 'UpdatePostImage')
                           begin
                           update Blog.BlogEntry
                           set ImageUrl = @ImgUrl, LastEdited = GETDATE(), EntryTitle = @Title, Message = @Message
                           where Id = @EntryId
                        end
                     else if(@Status = 'DeletePost')
                         begin
                              delete from Blog.BlogEntry
                              where Id = @EntryId
                          end
          END

Any help that you guys are willing to offer will be very much appreciated. If any further details are required please do not hesitate to give me a shout ;)

A: Being worried about how your code looks, I'll be more worried about how this code will perform, You will get huge parameter sniffing issues with this procedure, to avoid it you need dynamic sql so that sql server can cache a parameterised execution PLANS for this procedure instead of having one execution plan and trying to execute each query using the same plan.
Also you have some variable values set to invalid values such as Int variables are being set to empty string '' also datetime variables being set to empty string too please have a look below and this procedure should get you better performance.
CREATE PROCEDURE [Blog].[ttc_BlogPosts]
    @Status     varchar(50)   = '' ,
    @EntryId    int           = NULL,  --< can't set int variable to empty string
    @Title      nvarchar(max) = '',
    @Added      datetime      = NULL,    --< can't set Date/DateTime variable to empty string
    @Updated    datetime      = NULL,
    @Message    nvarchar(max) = '',
    @ImgId      int           = NULL,
    @ImgUrl     nvarchar(max) = ''
AS
BEGIN
  SET NOCOUNT ON;

  DECLARE @Sql NVARCHAR(MAX);

-- A validate check since your else..if statement don't handle this case
IF (@Status = '')
 BEGIN
  RAISERROR('Provide value for @Status variable',16,1)
  RETURN
 END

    IF(@Status = 'Display')
        begin
            SET @Sql = N'
            select Id, EntryTitle, Message, ImageUrl, DateAdded, LastEdited
            from Blog.BlogEntry
            order by DateAdded desc'
        end
    else if(@Status = 'AddPost')
        begin
            SET @Sql = N'
            insert into Blog.BlogEntry (EntryTitle, Message, DateAdded, ImageUrl)
            values (@Title, @Message, GETDATE(), @ImgUrl)'
        end
    else if(@Status = 'DisplayPost')
        begin
            SET @Sql = N'
            select EntryTitle, DateAdded, LastEdited, Message, ImageUrl
            from Blog.BlogEntry
            where Id = @EntryId'
        end
    else if(@Status = 'UpdatePost')
        begin
            SET @Sql = N'
            update Blog.BlogEntry
            set EntryTitle = @Title, Message = @Message, LastEdited = GETDATE()
            where Id = @EntryId'
        end
    else if(@Status = 'UpdatePostImage')
        begin
            SET @Sql = N'
            update Blog.BlogEntry
            set ImageUrl = @ImgUrl, LastEdited = GETDATE(), EntryTitle = @Title, Message = @Message
            where Id = @EntryId'
        end
    else if(@Status = 'DeletePost')
        begin
            SET @Sql = N'
            delete from Blog.BlogEntry
            where Id = @EntryId'
        end

Exec sp_executesql @Sql
                  ,N'@Status varchar(50),@EntryId int, @Title nvarchar(max), @Added datetime,
                    @Updated datetime, @Message nvarchar(max), @ImgId int, @ImgUrl nvarchar(max)'
                  ,@Status
                  ,@EntryId
                  ,@Title
                  ,@Added
                  ,@Updated
                  ,@Message
                  ,@ImgId
                  ,@ImgUrl
END

A: Using M.Ali solution with searched CASE to compare readability concerns.
Also added addtional @status validation
CREATE PROCEDURE [Blog].[ttc_BlogPosts]
     @Status     varchar(50)   = '' ,
     @EntryId    int           = NULL,
     @Title      nvarchar(max) = '',
     @Added      datetime      = NULL,
     @Updated    datetime      = NULL,
     @Message    nvarchar(max) = '',
     @ImgId      int           = NULL,
     @ImgUrl     nvarchar(max) = ''
 AS
 BEGIN
 SET NOCOUNT ON;

 DECLARE @Sql NVARCHAR(MAX);

-- A validate check since your else..if statement don't handle this case
IF (@Status = '' AND @Status NOT IN ('Display', 'DisplayPost', ...))
BEGIN
   RAISERROR('Provide value for @Status variable. Allowed values (Display, ...)',16,1)
   RETURN
END

SELECT @sql = CASE @status
    WHEN 'Display' THEN
        N'select Id, EntryTitle, Message, ImageUrl, DateAdded, LastEdited
        from Blog.BlogEntry
        order by DateAdded desc'

    WHEN 'AddPost' THEN
        N'insert into Blog.BlogEntry (EntryTitle, Message, DateAdded, ImageUrl)
        values (@Title, @Message, GETDATE(), @ImgUrl)'

    WHEN 'DisplayPost' THEN
        N'select EntryTitle, DateAdded, LastEdited, Message, ImageUrl
        from Blog.BlogEntry
        where Id = @EntryId'

    WHEN 'UpdatePost' THEN
        N'update Blog.BlogEntry
        set EntryTitle = @Title, Message = @Message, LastEdited = GETDATE()
        where Id = @EntryId'

    WHEN 'UpdatePostImage' THEN
        N'update Blog.BlogEntry
        set ImageUrl = @ImgUrl, LastEdited = GETDATE(), EntryTitle = @Title, Message = @Message
        where Id = @EntryId'

    WHEN 'DeletePost' THEN
        N'delete from Blog.BlogEntry
        where Id = @EntryId'
   END

EXEC [dbo].[sp_executesql] @Sql
              ,N'@Status varchar(50),@EntryId int, @Title nvarchar(max), @Added datetime,
                @Updated datetime, @Message nvarchar(max), @ImgId int, @ImgUrl nvarchar(max)'
              ,@Status
              ,@EntryId
              ,@Title
              ,@Added
              ,@Updated
              ,@Message
              ,@ImgId
              ,@ImgUrl
END

A: So, in the spirit of

"just a quick example to enable me to get my head around it..."

You could do dynamic SQL.
DECLARE @SQL VARCHAR(MAX)

SELECT @SQL = CASE
                  WHEN @Status = 'Display' THEN @SQL = 'select Id, EntryTitle, Message, ImageUrl, DateAdded, LastEdited from Blog.BlogEntry    order by DateAdded desc'
                  WHEN @Status = 'DisplayPost' THEN ...
                  WHEN @Status = 'UpdatePost' THEN ...
                  WHEN @Status = 'UpdatePostImage' THEN ...
                  WHEN @Status = 'DeletePost' THEN ...
              END

EXEC (@SQL)

The only catch you're going to run into is you'll need to concatenate your variables into your statements like the following
THEN @SQL = 'update Blog.BlogEntry set EntryTitle =''' + @Title + ''', Message =''' + @Message + ''', LastEdited = ''' + GETDATE() + ''' where Id = ''' @EntryId

A: In SQL, IF/ELSE serves a completely different function from CASE/WHEN, and the two are rarely interchangeable.
IF/ELSE can be used to control flow:
IF This
  DO THAT
ELSE
  DO Something else

CASE/WHEN returns a single value, and cannot control flow.
SET @MyValue = CASE
  WHEN [Color] = 'Red' THEN 1
  ELSE 0
END

Your code is not a good candidate for CASE/WHEN since you are using the IF/ELSE to control flow.

A: This will work. That's simple transformation of IF .. ELSE  into CASE.. ELSE ... END
CREATE PROCEDURE [Blog].[ttc_BlogPosts]
@Status varchar(50) = '' ,
@EntryId int = '',
@Title nvarchar(max) = '',
@Added datetime = '',
@Updated datetime = '',
@Message nvarchar(max) = '',
@ImgId int = '',
@ImgUrl nvarchar(max) = ''

AS
BEGIN
     CASE WHEN(@Status = 'Display')
        THEN
            select Id, EntryTitle, Message, ImageUrl, DateAdded, LastEdited
            from Blog.BlogEntry
            order by DateAdded desc

        ELSE (CASE WHEN(@Status = 'AddPost')
              THEN

                insert into Blog.BlogEntry (EntryTitle, Message, DateAdded, ImageUrl)
                values (@Title, @Message, GETDATE(), @ImgUrl)

              ELSE (CASE WHEN(@Status = 'DisplayPost')
                     THEN
                          select EntryTitle, DateAdded, LastEdited, Message, ImageUrl
                          from Blog.BlogEntry
                          where Id = @EntryId

                   ELSE (CASE WHEN(@Status = 'UpdatePost')
                          THEN
                              update Blog.BlogEntry
                              set EntryTitle = @Title, Message = @Message, LastEdited = GETDATE()
                              where Id = @EntryId

                        ELSE (CASE WHEN(@Status = 'UpdatePostImage')
                               THEN
                               update Blog.BlogEntry
                               set ImageUrl = @ImgUrl, LastEdited = GETDATE(), EntryTitle = @Title, Message = @Message
                               where Id = @EntryId

                               ELSE (CASE WHEN(@Status = 'DeletePost')
                                 THEN
                                      delete from Blog.BlogEntry
                                      where Id = @EntryId
                                  END)
                               END)
                         END)
                     END)
                END)
            END
END


text:
Q: delete node in BST python class Node:
    def __init__(self,data):
        self.data = data
        self.left = None
        self.right = None
        self.count = 1

class BST:
    def __init__(self):
        self.root = None
        self.size = 0

    def _insert(self,val,node):
        if val<node.data:
            if node.left:
                self._insert(val,node.left)
            else:
                self.size+=1
                node.left = Node(val)
        elif val>node.data:
            if node.right:
                self._insert(val,node.right)
            else:
                self.size+=1
                node.right = Node(val)
        else:
            self.size+=1
            node.count+=1

    def insert(self,val):
        if not self.root:
            self.size+=1
            self.root = Node(val)
        else:
            self._insert(val,self.root)

    def _inorder(self,node):
        if node:
            self._inorder(node.left)
            self.bstview.append(node.data)
            self._inorder(node.right)

    def view(self):
        if self.root:
            self.bstview = []
            self._inorder(self.root)
            return self.bstview

    def _min(self,node):
        if node.left:
            return self._min(node.left)
        return node

    def _max(self,node):
        if node.right:
            return self._max(node.right)
        return node

    def min(self):
        if self.root:
            return self._min(self.root).data

    def max(self):
        if self.root:
            return self._max(self.root).data

    def _remove(self,val,node):
        if not node:
            return
        if val < node.data:
            node.left = self._remove(val,node.left)
        elif val > node.data:
            node.right = self._remove(val,node.right)
        else:
            if node.count >1:
                self.size-=1
                node.count-=1
                return node
            elif not node.left:
                temp = node.right
                del node
                self.size-=1
                return temp
            elif not node.right:
                temp = node.left
                del node
                self.size-=1
                return temp
            else:
                temp = self._min(node.right)
                node.data = temp.data
                node.right = self._remove(temp.data,node.right)
        return node #WHY THIS IS NECESSARY PLEASE EXPLAIN!!

    def remove(self,val):
        if self.root:
            self._remove(val,self.root)

b = BST()
for x in list(map(int,"20 10 30 5 15 25 35 3 7 23 27 40 4 45".split(" "))):
    b.insert(x)
print(b.view())
print(b.min(),b.max(),b.size)
b.remove(20)
b.remove(45)
b.remove(1)
print(b.view())
print(b.min(),b.max(),b.size)

In the above code of BST, why is it necessary to return node in the _remove() method? The if/elif statements are already returning nodes?
Also, I would be greatly thankful to you if you can guide me to an easy/less time consuming way to understand recursive functions (I know what they are and how they work, my question is if someone asks me how a particular recursive function works then I would be able to explain him without confusing myself).


text:
Q: Percent comparison I have a frequency list of words. This list was generated using 1,000,000 words. I want to compare how much more word 1 occurs compared to word 2.
For example,
The word "he" shows up 20000 times
The word "she" shows up 6000 times
What percent does the word he occur compared to she. In other words,
"He" occurs xx% more than the word "she"
Thanks

A: just take numbers of "he" divide it by the number of "she" then multiple the result by 100:
let
$n1$ is how much word1 showup
$n2$ is how much word2 showup
then the percentage $p$ is:
$p=\frac{n1}{n2} \cdot 100$


text:
Q: Using multiple backreference in Perl I am trying to use multiple backreference in Perl, to match 5 different patterns, but I am getting no match except for the first one.
I tried the following:
my $string = ">abc|XYUXYU|KIOKEIK_7XNCU Happy, not-happy apple banana X ORIG=Came from trees NBMR 12345 OZ=1213379 NG=popZ AZ=2 BU=1";
$string =~ m/>(abc)|(.*)|.*ORIG=(.*)[A-Z].*NG=(.*)\s(.*)\s/;

print "First match should be 'abc'. We got: $1\n";
print "Second match should be 'XYUXYU'. We got: $2\n";
print "Third match should be 'Came from trees'. We got: $3\n";
print "Fourth match should be 'popZ'. We got: $4\n";
print "Fifth match should be 'AZ=2'. We got: $5\n";

I wanted as output:
First match should be 'abc'. We got: abc
Second match should be 'XYUXYU'. We got: XYUXYU
Third match should be 'Came from trees'. We got: Came from trees
Fourth match should be 'popZ'. We got: popZ
Fifth match should be 'AZ=2'. We got: AZ=2

Any clue how to solve this in the correct way on Perl?

A: You have to escape the | by prepending \ as they otherwise mean an alternation (a|b matches a or b). And for your third match you have to make the quantifier * non greedy by appending ?. And you need to tweak the pattern following the third capture group a little to match a space an at least one upper character (It's not entirely clear here what the overall possibilities are as you just gave an expample without further details. It might need further adaption.)
#!/usr/bin/perl

use strict;
use warnings;

my $string = ">abc|XYUXYU|KIOKEIK_7XNCU Happy, not-happy apple banana X ORIG=Came from trees NBMR 12345 OZ=1213379 NG=popZ AZ=2 BU=1";
$string =~ m/>(abc)\|(.*)\|.*ORIG=(.*?)\s[A-Z]+.*NG=(.*)\s(.*)\s/;

print "First match should be 'abc'. We got: $1\n";
print "Second match should be 'XYUXYU'. We got: $2\n";
print "Third match should be 'Came from trees'. We got: $3\n";
print "Fourth match should be 'popZ'. We got: $4\n";
print "Fifth match should be 'AZ=2'. We got: $5\n";

Output:
First match should be 'abc'. We got: abc
Second match should be 'XYUXYU'. We got: XYUXYU
Third match should be 'Came from trees'. We got: Came from trees
Fourth match should be 'popZ'. We got: popZ
Fifth match should be 'AZ=2'. We got: AZ=2


text:
Q: How to specify a Rust struct field must satisfy a trait when the struct has async methods? Creating an authentication server.
I want a PGUserRepo struct, which implements a UserRepo trait async fn create.
The PGUserRepo should have a field that implements the Hasher trait.
However when I try to restrict the PGUserRepo field to be a dyn Hasher I get the error
"the trait std::marker::Send is not implemented for `(dyn domain::hasher::Hasher + 'static)".
If I make the PGUserRepo field the concrete implementing type, ArgonHasher, no error. But I don't want the PGUserRepo to care about what kind of Hasher was given to it, just that it implements the Hasher trait.
I have tried wrapping the hasher field in various combinations of Box, Arc, and Mutex, but I do not understand the root of why calling it an ArgonHasher is fine but saying it is some implementer of Hasher is not.
Code, collapsed to one file for convenience:

pub trait Hasher {
    fn hash(&self, password: String) -> Result<String, HasherError>;
}

pub struct ArgonHasher {}

impl Hasher for ArgonHasher {
    fn hash(&self, password: String) -> Result<String, HasherError> {
        let result = argon2id13::pwhash(
            &password.as_bytes(),
            argon2id13::OPSLIMIT_INTERACTIVE,
            argon2id13::MEMLIMIT_INTERACTIVE,
        );
        match result {
            Ok(hashed_password_result) => match std::str::from_utf8(&hashed_password_result.0) {
                Ok(hashed_password_utf8) => Ok(String::from(hashed_password_utf8)),
                Err(e) => Err(HasherError::from(e)),
            },
            Err(e) => Err(HasherError::from(e)),
        }
    }
}

impl From<()> for HasherError {
    fn from(_: ()) -> Self {
        HasherError::HasherError {
            message: String::from(""),
        }
    }
}

impl From<std::str::Utf8Error> for HasherError {
    fn from(cause: std::str::Utf8Error) -> Self {
        HasherError::HasherError {
            message: format!("{}", cause),
        }
    }
}

#[async_trait]
pub trait UserRepo {
    async fn create(&self, user: User) -> Result<User, UserRepoError>;
}

#[derive(Debug)]
pub enum UserRepoError {
    UserAlreadyExistsError { field: String, value: String },
    UserRepoError { message: String },
}

impl fmt::Display for UserRepoError {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        match *&self {
            UserRepoError::UserAlreadyExistsError { field, value } => {
                f.write_str(&format!("User with {}={} already exists", field, value))
            }
            UserRepoError::UserRepoError { message } => f.write_str(&message),
        }
    }
}

pub struct PGUserRepo {
    conn_pool: PgPool,
    hasher: &'static dyn Hasher,
}

impl PGUserRepo {
    pub fn new(conn_pool: PgPool, hasher: &'static dyn Hasher) -> Self {
        PGUserRepo { conn_pool, hasher }
    }
}

#[async_trait]
impl UserRepo for PGUserRepo {
    async fn create(&self, user: User) -> Result<User, UserRepoError> {
    # Compiler error is on this function
    # hasher is not even used in this function yet, it's just a field on PGuserRepo
}

Bonus: I don't really need the Hasher trait hash to have a reference to self but without it I get "error[E0038]: the trait domain::hasher::Hasher cannot be made into an object".

A: The marker trait Send is used to indicate when a type is safe to be transferred between threads. It is implemented by default when the compiler deems it to be safe. However, you have a trait object hasher that has no constraint on if it can be shared between threads safely.
This comes up here because async code is usually handled via multiple threads and the async_trait enforces that.
The fix is to indicate that only Hashers that can be shared between threads are allowed. You can do this by using the Sync trait:
pub struct PGUserRepo {
    conn_pool: PgPool,
    hasher: &'static (dyn Hasher + Sync),
}

See Understanding the Send trait to learn more about the difference between Sync and Send and their purpose.


text: Q: How process the information send by google api on the sign-up to under of cognito with boto3 whitout hosted UI? Now I have the google response,  but  What I do what these  information?  How send to cognito across  python to register users with google account?


text:
Q: Caching UITableViewCells I have a view with UITableView in it which can display 4 typles of UITableViewCell's (custom ones). Basically, two of them are with media (image, move, sound) and 2 of them have additionally users avatars.
Let's generalize that cells with media will display only images (thumbnails). Of course those images are dynamically downloaded when cell is created. It could be harmful to download those images everytime user scrolls the table view so I use EGOCache to cache those images but... This ain't helping with scrolling issues!! I thought that caching will store pionter to those images but everytime cell is recreated it takes this image from disk (so Intruments are telling me that this method is killing my performace).
My question is: How to cache UITableViewCell so it's not created everytime I scroll UITableView a little bit?

Here are samples from my code so you can imagine point of my question:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    Event *event = [self.events objectAtIndex:indexPath.row];

    if ([event.type isEqualToString:@"camp"]) {
        if (!event.mediaType) {
            CampCell *cell = [self.tableView dequeueReusableCellWithIdentifier:[CampCell identifier]];
            [cell configureWithModel:event];
            return cell;
        } else {
            CampMediaCell *cell = [self.tableView dequeueReusableCellWithIdentifier:[CampMediaCell identifier]];
            [cell configureWithModel:event];
            return cell;
        }
    } else {
        if (!event.mediaType) {
            StatusCell * cell = [self.tableView dequeueReusableCellWithIdentifier:[StatusCell identifier]];
            [cell configureWithModel:event];
            return cell;
        } else {
            StatusMediaCell *cell = [self.tableView dequeueReusableCellWithIdentifier:[StatusMediaCell identifier]];
            [cell configureWithModel:event];
            return cell;
        }
    }
}

And this is how configureWithModel: looks like:
- (void)configureWithModel:(id)model {
    if ([model isKindOfClass:[Event class]]) {
        Event *event = model;
        self.titleLabel.text = event.title;
        self.locationLabel.text = event.address;
        self.timeLabel.text = [self hoursLeftToDate:event.expirationDate];

        UIImageView *imageAttachedToStatus = [[UIImageView alloc] initWithFrame:CGRectMake(0.0, 0.0, self.mediaContainerView.frame.size.width, self.mediaContainerView.frame.size.height)];
        imageAttachedToStatus.contentMode = UIViewContentModeScaleAspectFill;
        imageAttachedToStatus.clipsToBounds = YES;

        [self getMediaAttachmentForModel:model completion:^(id attachment) {
            if (attachment) {
                imageAttachedToStatus.image = (UIImage *)attachment;
            }
        }];

        [self.mediaContainerView addSubview:imageAttachedToStatus];
    }
}

And, of course, you may wonder how getMediaAttachmentForModel:completion: looks like...
- (void)getMediaAttachmentForModel:(Event *)model completion:(void (^)(id attachment))completion {
    NSString *mediaID = [NSString stringWithFormat:@"media%li", (long)model.eventID];

    if ([[EGOCache globalCache] hasCacheForKey:mediaID]) {
        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
            id cachedAttachment =[[EGOCache globalCache] objectForKey:mediaID];
            dispatch_async(dispatch_get_main_queue(), ^{
                completion(cachedAttachment);
            });
        });
    } else {
        [[Client sharedClient] fetchMediaThumbnailForEvent:model completion:^(id attachment, NSError *error) {
            dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
                [[EGOCache globalCache] setObject:attachment forKey:mediaID];

                dispatch_async(dispatch_get_main_queue(), ^{
                    completion(attachment);
                });
            });
        }];
    }
}

A: The proper solution would be to find/implement a cache that is able to cache images in memory, without fetching them from disk every time.
Take a look at Path's FastImageCache


text:
Q: In a rail application i want to authorize admin to create a new record in particular module.not any user Requirement:
I have  a deal module in my rail application. when the user click on create new deal link  it will check chat whether the user is admin or not.if the user is admin i want to allow
it to create a new deal otherwise it will display a flash message that you are not allowed and redirect the user to signin page to login as admin.if the user sign in as admin i want to redirect it to  a page from where it previously comes.

A: Devise and cancan should help


text:
Q: Calculate heading for kml in php/mysql I have a table in mysql with 4 columns:

*

*Latitude_1

*Longitude_1

*Latitude_2

*Longitude_2

Now I want to calculate the heading for all rows to be used in a kml file.
I found this function:
// Takes two sets of geographic coordinates in decimal degrees and produces bearing (azimuth) from the first set of coordinates to the second set.//
public static function bearing($lat1, $lon1, $lat2, $lon2) {
        $lat1 = deg2rad($lat1);
        $lon1 = deg2rad($lon1);
        $lat2 = deg2rad($lat2);
        $lon2 = deg2rad($lon2);
        $lonDelta = $lon2 - $lon1;
        $y = sin($lonDelta) * cos($lat2);
        $x = cos($lat1) * sin($lat2) - sin($lat1) * cos($lat2) * cos($lonDelta);
        $brng = atan2($y, $x);
        $brng = $brng * (180 / pi());

        if ( $brng < 0 ) { $brng += 360; }

        return $brng;
    }

Now I hope that someone shows me a query that echoes all headings (bearings) of the table based on the above mentioned function

A: *

*To combine an expression expr, take a look to the mysql math functions and find proper equivalents for php ones - https://dev.mysql.com/doc/refman/5.0/en/mathematical-functions.html

*Simplify your expr if possible

*Use your result expression expr in following query SELECT expr FROM your_table

*Profit


text:
Q: How to create a DialogFragment layout with multiple pages or tabs In my application, I want to implement a dialog fragment in which the user configures 1 to 4 sets of data (for lack of a better phrase).  The number of "pages" to be set up is up to the user, so I would like the dialog fragment display to respond dynamically to the number requested by the user, by varying the number of viewable "screens".
My first thought was to implement a tabbed display with the tabs displayed or hidden as requested, but the way Android seems to think about tabs seems to be way more complicated than this.  (Like this over-the-top example: How to create an Android Tabbed Dialog containing fragments?)
Is there a simple layout technique I'm missing that I could use for this?  Perhaps a nice example somewhere on the web??

A: I think you can try and use a ViewPager - http://developer.android.com/training/animation/screen-slide.html
It supports sliding pages in both directions. You can add custom animation to it - using buttons or whatever views to achieve the desired effect.


text:
Q: Using English macros in French version Excel I am currently in France and am using a computer on which all Office programs are in French.
I need to use a Macro which has been written in English VBA, but it fails.
I assume the issue a language issue as the same thing occurs when I try using English Excel formulas in the French version (e.g. =sum is =somme)
Is there a way of doing this?

A: You have two options that involve rewriting your VBA code.

*

*First option: whenever accessing the Range.Formula property, replace it for the Range.FormulaLocal property. The localized version of the formulas will be translated by Excel into the English version it uses internally. This will of course make your macros only work in the French locale/language.

*Second option: manually translate every formula hardcoded in your VBA into English. This will make your macros work in any Excel locales/languages.

A: I had a similar problem with a Excel Macro tool written in the USA and I wanted to use it with in Germany. The tool seemed to get locked in a loop after starting so it didn't come to an end.
I could finally solve this issue with changing the windows default for date, time, and number format, into US-standard like described here .
So probably the VBA code of the tool works with some data in US standard formats and it won't work in foreign format systems.


text:
Q: ASP.NET MVC 5 Identity userManager.IsInRole The following code does not work, and I can't explain why... My user manager is causing significant distress in that it creates users and roles just fine but when I run this code userManager.IsInRole is always returning false, so the second time I run my seed I am hitting errors because it is trying to create the record despite the fact it already exists!
Please note that this is occurring when I am running update-database against my migrations project, is the fact this is a non ASP project causing issues, if so why? shouldn't an error be thrown.
This is the first project I have used Identity and although when it works it seems good, there is very little up to date good quality documentation available, so if anyone has any sources for this I would be grateful.
    public void Run(BlogContext blogContext)
    {
        var userStore = new UserStore<User>((BlogContext) blogContext);
        var userManager = new UserManager<User>(userStore);

        var userRoles = new List<UserRole>()
        {
            new UserRole() {Username = "SysAdmin@test.com", Role = "SysAdmin"},
            new UserRole() {Username = "testAdmin@test.com", Role = "Admin"},
            new UserRole() {Username = "testAuthor@test.com", Role = "Author"}
        };

        foreach (var userRole in userRoles)
        {
            var userId = userManager.FindByName(userRole.Username).Id;

            if (!userManager.IsInRole(userId, userRole.Role))
                userManager.AddToRole(userId, userRole.Role);
        }

        blogContext.SaveChanges();
    }

A: So I will answer this myself to save anyone the hours of pain I suffered because of this.
The reason for this occurring was that I had lazy loading disabled, I have enabled this to be on in my Migrations project like so.
protected override void Seed(BlogContext blogContext)
    {
        AutomaticMigrationsEnabled = true;
        blogContext.Configuration.LazyLoadingEnabled = true;
        //Add seed classes here!
    }


text:
Q: No provisioning profiles have been detected. Please visit the iOS Provisioning Portal I just got a new OSX machine and decided to start fresh.
Setting up everything went relatively straight forwards (Xcode, Xamarin, Calabash...). However, when it came to the provisioning profile I got the following error:

No provisioning profiles have been detected. Please visit the iOS Provisioning Portal at https://developer.apple.com to create one.Build: 1 error, 0 warnings

I somehow tend to always have problems when it comes to provisioning profiles... What I did:

*

*Created new certificates

*Created new provisioning profiles

*Download provisioning profiles and double click on them

*Add them in Xcode-> Devices -> (right click on device)Show Provisioning Profiles...

Needless to say the problem is still there

A: So I found the answer on Xamarin's website, in case other people have the same problem and got here follow this link.
Reason:

WARNING: Because of changes that Apple recently made to the way
  provisioning works, Xamarin Studio currently is unable to refresh
  changes or additions to iOS Provisioning profiles directly.

Solution from Xamarin website:


text:
Q: cannot read property of 'get' undefined in the express router My code is as shown below:
app.js
const app = express();
const itemsRouter = require('./routes/items.js');

app.use(bodyParser.urlencoded({
    extended: true
}));

app.use('/items', itemsRouter);

items.js
const router = require('express').router;

router.get('/itemTest', (req, res) => {
    res.json({
        sucess: true
    });

    console.log(`the parametrs are ${req.body.item_name}  ${req.body.item_post}`);
});

module.exports = router;

But here somehow, I am not able to get the router working and it says that can not read property 'get' of undefined.
the error stack is as shown below:
TypeError: Cannot read property 'get' of undefined
    at Object.<anonymous> (C:\Users\anand\quFlipApi\routes\items.js:5:7)
    at Module._compile (module.js:570:32)
    at Object.Module._extensions..js (module.js:579:10)
    at Module.load (module.js:487:32)
    at tryModuleLoad (module.js:446:12)
    at Function.Module._load (module.js:438:3)
    at Module.require (module.js:497:17)
    at require (internal/module.js:20:19)
    at Object.<anonymous> (C:\Users\anand\quFlipApi\app.js:33:19)
    at Module._compile (module.js:570:32)
    at Object.Module._extensions..js (module.js:579:10)
    at Module.load (module.js:487:32)
    at tryModuleLoad (module.js:446:12)
    at Function.Module._load (module.js:438:3)
    at Module.runMain (module.js:604:10)
    at run (bootstrap_node.js:394:7)

A: There are two problems here:

*

*It's express.Router and not express.router.

*You need to create a new instance of express.Router (e.g. var router = new express.Router()) instead of trying to using the constructor directly as an instance.


text:
Q: Multicast OnExceptionAspect is logging bubbling exceptions I have a multicast OnExceptionAspect from Postsharp which is applied on the assembly level.  This naturally means that all methods, upon throwing an exception, will invoke the Aspect.
Within the Aspect I'm logging the exception details including the values of the parameters passed when the exception occured, this is working properly.
However because this is applied to all methods in the assembly a log entry is created for each method in the stack as the exception bubbles up through each.
I'm out of ideas on how to prevent this, initially I was going to compare the exception (to see if it's the same one) but this just seems messy.  Someone must have had this problem before, any ideas?

A: There are two solutions to this problem.
A. Use a thread-static field to store any exception that has already been logged.
[Serializable]
public class MyAspect : OnExceptionAspect
{
    [ThreadStatic]
    private static Exception lastException;

    public override void OnException(MethodExecutionArgs args)
    {
      if(args.Exception != lastException)
      {
        string msg = string.Format("{0} had an error @ {1}: {2}\n{3}",
            args.Method.Name, DateTime.Now,
            args.Exception.Message, args.Exception.StackTrace);

        Trace.WriteLine(msg);
        lastException = args.Exception;
      }

    }
}

B. Add a tag to the Exception object.
[Serializable]
public class MyAspect : OnExceptionAspect
{
    private static object marker = new object();

    public override void OnException(MethodExecutionArgs args)
    {
      if(!args.Exception.Data.Contains(marker))
      {
        string msg = string.Format("{0} had an error @ {1}: {2}\n{3}",
            args.Method.Name, DateTime.Now,
            args.Exception.Message, args.Exception.StackTrace);

        Trace.WriteLine(msg);
        args.Exception.Data.Add(marker, marker);
      }

    }
}

A: FYI--Gael is a PostSharp guru because he is employed there...just so you are aware.
For what it is worth you can always tell where the exception originated by examining the StackTrace.  The StackTrace is made available via args.Exception.StackTrace.  You may try what Dustin Davis (another PostSharp employee) recommends here: PostSharp - OnExceptionAspect - Get line number of exception
Parse the StackTrace (via the method outlined here: How to split a stacktrace line into namespace, class, method file and line number?) then compare the args.Method.Name with the parsed results.  If your args.Method.Name is the same as the originating method (found via parsing the StackTrace) then you know you should log it otherwise ignore.
Here is some code to make my solution more concrete (building on the prior two solutions cited):
[Serializable]
public class ExceptionWrapper : OnExceptionAspect
{
    public override void OnException(MethodExecutionArgs args)
    {
        var st = new StackTrace(args.Exception, true);
        var frame = st.GetFrame(0);
        var lineNumber = frame.GetFileLineNumber();
        var methodName = frame.GetMethod().Name;
        if(methodName.Equals(args.Method.Name))
        {
            string msg = string.Format("{0} had an error @ {1}: {2}\n{3}",
                args.Method.Name, DateTime.Now,
                args.Exception.Message, args.Exception.StackTrace);

            Trace.WriteLine(msg);
        }
    }
}

(Or, honestly, you could just use one of Gael's recommended solutions.)

A: One way i could see this being done would be to define a custom exception and just throw that one in your aspect. then also in your aspect check the exception before loggin, if it's not your custom exception log it, otherwise don't log it and (re-throw?).
That's what the example code would look like:
[Serializable]
public class DatabaseExceptionWrapper : OnExceptionAspect
{
    public override void OnException(MethodExecutionArgs args)
    {
      if(!(args.Exception is CustomException))
      {
        string msg = string.Format("{0} had an error @ {1}: {2}\n{3}",
            args.Method.Name, DateTime.Now,
            args.Exception.Message, args.Exception.StackTrace);

        Trace.WriteLine(msg);
      }

      throw new CustomException("There was a problem");
    }
}

Of course you'd still have to define that exception and everything. :)


text:
Q: When to use unsigned values over signed ones (how do)? When is it appropriate to use an unsigned variable over a signed one? What about in a for loop?
I hear a lot of opinions about this and I wanted to see if there was anything resembling a consensus.
for (unsigned int i = 0; i < someThing.length(); i++) {
    SomeThing var = someThing.at(i);
    // You get the idea.   }

A: In your specific case, you should use the type which does not generate an implicit type conversion in this expression:
i < someThing.length();

i.e. you should use the exact type of someThing.length(). Look at its signature and use its return type for your local variable i.
Don't think of loop variables as something special. If you're working with length, use the type of length. Try to be as consistent as possible within your project, avoiding unnecessary type conversions.

A: You should use a signed variable when the value can be negative.
A length should always be positive and is because of this usually represented with an unsigned type. It is the consensus as far as I can see in the standard library and other big libraries (often named size_t for example ).
It is better to use unsigned int for i because in case the length is big you won't have overflow problems but usually it makes no difference.
Many compilers will also give you a warning if you compare a int (signed) with and unsigned int because of this issue.

A: Obviously you should use a signed type when negative numbers are involved - the interesting question is whether it's still good to do so when the value is known to be non-negative but clearly doesn't need the extra range the equivalent unsigned type offers.
There is no concensus.  Some considerations:

*

*the real-world import of some variables is inherently signed (e.g. a person's age), unsigned variables can encode/communicate that to a programmer reading the source code

*I'm not aware of any compiler that warns if you pass unsigned types into functions expecting signed or vice versa; claims that the choice of type can enforce correctness are dubious

*many compilers do warn if signed and unsigned types are compared

*some specific variables/types in libraries are either signed or unsigned, and it may make sense to use the same types for variables interacting with them, ensuring the representable range is the same

*code like while (n-- >= 0) and abs(a - b) may not do what's wanted given unsigned types, which is one reason to have a general preference for signed types


text:
Q: Where is the Javadoc plugin settings in Intellij Idea? The javadoc plugin generated default javadocs, how to set them ? Where is the Javadoc plugin settings in Intellij Idea ?

A: IntelliJ has built-in support for generating JavaDocs so unless there's something missing from that feature you won't need a plugin.
You can access this feature from Tools > Generate JavaDoc ...

More details in the docs here and here.
Edit 1: Based on your last comment I think you want to create the JavaDocs rather than generate the JavaDoc output. If so, then IntelliJ will create a Javadoc for you when you:

*

*Place the caret in an empty line immediately above a method

*Type /**

*Hit the ENTER key

Given this method:
public void run(long distance) throws ExtremeFatigueException {

}

The /** + ENTER keystroke combination will generate this skeleton JavaDoc:
/**
 *
 * @param distance
 * @throws ExtremeFatigueException
 */

The format of the JavaDocs in IntelliJ is controlled in Preferences > Editor > Code Style > Java then click on the JavaDoc tab.


text:
Q: Adding 'Getters' and 'Setters' for the sake of unit testing? I am currently working with some pretty iffy code. The code itself is not legacy, but the framework it uses is legacy and is pretty bad.
I want to start writing some junit tests for a class (for a change!) but in order to do so effectively I would need to add some getters and setters.
I need the setters so I can check the state of the private variables in the class (a kind of state machine design pattern going on here) and I need the getters to mock what the private variables in some methods are.
Would you guys say its bad, good or simply acceptable to add getters and setters to a class for the sake of being able to write unit tests?

A: Adding code to production code solely for unit tests is something which I try to avoid.
An alternative for your case would be to retrieve the values via reflection, as it is possible to access even private members.
Field field = object.getClass().getDeclaredField("member");
field.setAccessible(true);
Object value = field.get(object);

A: I prefer having all dependencies passed into the constructor, but assuming that would be too difficult to add to your existing system, just ensure the getters and setters are package private and clearly label them (annotation or javadoc) that they are visible purely for testing. Even better if you could add some static analysis tools to ensure the getters and setters are not called from production code only from test.

A: I would avoid it.  Generally speaking, you should structure things as best you can to avoid needing to test private variables and stick with the interactions that the rest of the application will be exposed to.  This is typically public methods/properties and protected methods by using fakes/doubles.
The purpose of the unit tests are to verify how the object under test is interacted with, not necessarily it's implementation details.  Basically, with input x, I should get output/effect y.  If you get hung up on testing exactly how x produces y, you run the risk of making your classes inflexible to change.  Every refactor of your class is likely to break your tests, even if the output and end result is the same.


text:
Q: The .fadeIn function isn't working I am very new to jQuery, so please be patient.
I´d like to fade in a list step by step. But anything is wrong with my function. Please can somebody help me?
Thanks a lot!
Edit: I have take a look on everything and can´t find any mistakes. The body have the needed class.

$(".sideThree ul").children().each(function(i) {
  if ($('body').hasClass("content-three-has-open")){
    $(".sideThree ul").css('display','block');
    $(this).fadeIn((i++) * 500);
  }
});
.sideThree ul {
  list-style-type: none;
  margin: 0;
  padding: 0;
}
.sideThree ul li {
  list-style-type: none;
  margin-bottom: 15px;
  float: left;
  padding: 25px;
  background: #2b2b2b;
  width: 49%;
  margin-right: 1%;
  display: none;
}

// some content

// some content

// some content

// some content

// some content

// some content

// some content

A: You just need to call .fadeIn and pass your delay value as a parameter, e.g. $(this).fadeIn((i++) * 500);.
Here is a Codepen: https://codepen.io/anon/pen/xXrNLr
(I'm presuming it's intentional that you want the delay to increment per list item, if not you'd just do i * 500 as the delay).
Edit: If your list is initially set to display: none, you can add this line inside your if statement:
$(".sideThree ul").children().each(function(i) {
  if ($('body').hasClass("content-three-has-open")){
    $(".sideThree ul").css('display','block');
    $(this).fadeIn((i++) * 500);
  }
});

Alternatively change the CSS so it's the list items that are display: none, I believe fadeIn() will set them to display prior to fading.


text:
Q: If I had time so much to do... vs If I managed so much to do Are both sentences correct? Have they got the same meaning? Which one is better to use?

I have a lot to do today. If I had time so much to do, we could go out.
I have a lot to do today. If I managed so much to do, we could go out.

TIA


text:
Q: Accessing a dictionary from angular controller I'm trying to do the following.
Angular controller calls and MVC controller GET method. This method then calls into a REST API on the web which returns a list of configuration items. I then turn this into a dictionary so I can look up configuration values based on the key, and then I want to pass this back to the Angular controller and store it there in a variable that I can access from many different scenarios, eg displaying them in grids, updating values, changing and updating them back to the REST API etc. I have tried to set up the pipes but I can't seem to get the data in a readable/usable format in the Angular controller.
My controller
app.controller("SEFlexHomeController", ["$scope", "$http", "$modal", "$log", "$element", "$rootScope", "AlertsService", "AuthService", "SEApplicationService", function ($scope, $http, $modal, $log, $element, $rootScope, AlertsService, AuthService, SEApplicationService) {
        $rootScope.closeAlert = AlertsService.closeAlert;
        $scope.isDataLoading = false;
        $scope.AuthService = AuthService;
        $scope.configvalues = angular.fromJson(SEApplicationService.getCloudConfigParams());
    }
]);

My Angular Service
app.factory("SEApplicationService", ["$log", "$http", "$timeout", function($log, $http, $timeout) {

    var appService = {};

    appService.getCloudConfigParams = function () {
        return $http.get("/SEFlex/SEFlexAdmin/GetCloudConfigValues");
    }

    return appService;
}]);

My MVC controller
public ActionResult GetCloudConfigValues()
        {
            try
            {
                var helper = new ApplicationServiceHelper();
                var dictionary = helper.GetCloudConfigValues()
                    .ToList()
                    .ToDictionary(item => item.ConfigKey, item => item.ConfigValue);

                var returnData = JsonConvert.SerializeObject(dictionary);

                return Json(new
                {
                    success = true,
                    data = returnData
                }, JsonRequestBehavior.AllowGet);

            }
            catch (Exception exception)
            {
                return Json(new
                {
                    success = false,
                    errors = new[] { exception.Message }
                });
            }
        }

I can confirm at the time of creating the Dictionary in the MVC controller, the dictionary looks as expected for a .NET dictionary. What do I need to do to convert this either before transmission back or back in Angular, so that I can access it in angular as

$scope.configvalues["keyName"]

A: The $http.get() call returns a promise. You should change the
$scope.configvalues = angular.fromJson(SEApplicationService.getCloudConfigParams());

to
SEApplicationService.getCloudConfigParams().then(function(config) {
    $scope.configvalues = config;
});


text:
Q: Select all values of a specific column associated with the max value of another column I want to pull data from my table.
  line          Entryid
  hello           1
  world           1
  this            1
  is              1
  hello           2
  again           2
  world           2

I want to select all the information associated with Entryid 2. Note i cannot say WHERE Project id = 2. I need something like where MAX(Entryid). So the information pulled will be hello  again   world

A: You can do what you want using join or a subquery:
select t.*
from t
where t.entryid = (select max(t2.entryid) from t t2);

A: You can use a sub query.
         Select * From yourTable Where Entryid = (Select  max (Entryid) From yourTable)


text:
Q: regular expression negation In my current regular expression, I am negating digits:
$(function(){
  $("#somewhat").bind("keyup",
   function(event) {
     var regex = /^[\D]*$/;
     alert(regex.test($("#somewhat").val()));
  });
});

What I have in my mind is to add some special characters on which I should negate, !@#$%^&*()_+=<>.?/~`:;" , and leaving dash, apostrophe ( -' ) to the valid list. I'm still kind of dizzy on this regular expression thing. To test with, I added + on the regex,
var regex = /^[\D+]*$/;

When I test it, the alert box returns TRUE, which is not I am expecting.

A: Inside [ ] please add all the characters you don't want to allow.
/^((?![\d!@#$%^&*()_+=<>.?/~`:;"]).)*$/

But can we rely on negating given characters ? because user will be able to enter any character other than these. If you want to allow non-English characters, I would suggest you to use Unicode ranges
see this : http://kourge.net/projects/regexp-unicode-block

A: [\D+] means "any character that is +, or that is not a digit"; so it's actually equivalent to plain old \D or [\D], since + itself isn't a digit.
To get the meaning of "any character that is neither + nor a digit", you'd have to write [^\d+].
(\D or [\D] is equivalent to [^\d], but its negative-ness doesn't extend beyond that.)


text:
Q: Assigning one type of object to other type of reference variable not working Consider the following code:
#include <iostream>
using namespace std;
class B{
public:
  B(){}
};
class A
{
public:
A(){}
A(B &b){

}
A(const B &b){
       cout<<"cccddd"<<endl;
}
};
int main()
{
   B b;
   A c(b);
   A a;
   a=b; //ok
   A &ref = b; //error and why???
}

why b assigned to a is ok,but b assigned to ref is illegal???

A: A(const B &b){
       cout<<"cccddd"<<endl;
}

This will enable you to convert an object of type B into an object of type A. However, a reference T& cannot be created from another type L.

8.5.3 References [dcl.init.ref]

*

*A variable declared to be a T& or T&&, that is, "reference to type T" (8.3.2), shall be initialized by an object, or function, of type T or by an object that can be converted into a T.

*[...]

*[...]

*Given types "cv1 T1" and "cv2 T2," "cv1 T1" is reference-related to "cv2 T2" if T1 is the same type as T2, or T1 is a base class of T2. "cv1 T1" is reference-compatible with "cv2 T2" if T1 is reference-related to T2 and cv1 is the same cv-qualification as, or greater cv-qualification than, cv2 [...].

In your example neither are A and B the same type, nor is A a base class of B, thus both classes aren't reference-related.
Why won't A &ref = (A)b work?
The expression (A) b will actually create a temporary, which cannot be bound to a normal reference:

error: invalid initialization of non-const reference of type 'A&' from a temporary of type 'B'

You would need to a const reference A const & ref = (A)b for this.


text:
Q: Docker run SED command before container starts I'm running Rundeck with docker-compose and Dockerfile and i need to modify a value inside a file which is inside the container.
I can copy the modified file from another place (local) and place it inside the container while the build phase is in process but somehow the file gets replaced by the original one and that approach doesn't work.
I've also tried to run SED command (so i can modify the exact line of the file) inside Dockerfile but again that doesn't work and the container shows the original file with nothing modified inside.
So, I know that the image is inn mutable and cannot be modified (also is not a good practice).
What can I do here?. What is the best approach to every time I run a new Rundeck image apply that modification I need within the file?.
Replication escenario:
Dockerfile
FROM rundeck/rundeck:4.2.3-rc1-20220712
WORKDIR /home/rundeck
RUN sudo apt-get update
RUN sudo apt-get install nano

Docker-compose (be aware of yml format!)
version: '3.4'
services:
rundeck:
    restart: always
    build: .
    container_name: rundeck
    links:
      - mysql
    tty: true
    ports:
      - 4444:4440
    environment:
        RUNDECK_GRAILS_URL: http://192.168.1.5:4444
        RUNDECK_SERVER_FORWARDED: 'true'
        RUNDECK_DATABASE_DRIVER: org.mariadb.jdbc.Driver
        RUNDECK_DATABASE_USERNAME: rundeck
        RUNDECK_DATABASE_PASSWORD: rundeck
        RUNDECK_LOGLEVEL_DEFAULT: info
        RUNDECK_DATABASE_URL: jdbc:mysql://mysql/rundeck?autoReconnect=true&useSSL=false
    volumes:
      -  /run/docker.sock:/var/run/docker.sock
      -  /home/ubuntu/.ssh:/home/rundeck/.ssh
      - ./rundeck_data:/home/rundeck/server/data
      - ./rundeck_config:/home/rundeck/server/config

Once the container is up, look up the file located at /home/rundeck/server/config "rundeck-config.properties" inside the container. On line 42 i need to change value 30d (actual) by 0d.
Any help will be really appreciated!.

A: You don't need to run sed before the container starts.
If you read through the documentation for the rundeck docker image, it says that:

Remco is used to generate the Rundeck configuration files from templates. It supports different key/value sources such as vault, etcd, and dynamodb. All configuration backends are combined into a unified keyspace. This allows storing parts of the configuration space in different backends. The default configuration uses environment variables.

This suggests we can achieve your desired configuration using environment variables, and indeed, if we set RUNDECK_API_TOKENS_DURATION_MAX to 0d...
version: '3.4'
services:
  mysql:
    image: docker.io/mariadb:10
    environment:
      MARIADB_ROOT_PASSWORD: secret
      MARIADB_DATABASE: rundeck
      MARIADB_USER: rundeck
      MARIADB_PASSWORD: rundeck

  rundeck:
    restart: on-failure
    build: .
    container_name: rundeck
    ports:
      - 4444:4440
    environment:
      RUNDECK_GRAILS_URL: http://localhost:4444
      RUNDECK_SERVER_FORWARDED: 'true'
      RUNDECK_DATABASE_DRIVER: org.mariadb.jdbc.Driver
      RUNDECK_DATABASE_USERNAME: rundeck
      RUNDECK_DATABASE_PASSWORD: rundeck
      RUNDECK_LOGLEVEL_DEFAULT: info
      RUNDECK_DATABASE_URL: jdbc:mysql://mysql/rundeck?autoReconnect=true&useSSL=false
      RUNDECK_API_TOKENS_DURATION_MAX: 0d
    volumes:
      - rundeck_data:/home/rundeck/server/data
      - rundeck_config:/home/rundeck/server/config

volumes:
  rundeck_data:
  rundeck_config:

Then the result rundeck-config.properties contains:
rundeck@f9b1ceaaff8e:~$ grep tokens.duration.max server/config/rundeck-config.properties
rundeck.api.tokens.duration.max=0d

In the container, you can find the template sources in /etc/remco/templates. I was able to determine the correct environment variable name by inspecting /etc/remco/templates/rundeck-config.properties, which contains:
rundeck.api.tokens.duration.max={{ getv("/rundeck/api/tokens/duration/max", "30d") }}

In the above example docker-compose.yaml file, note also that I've removed the links entry, which has been deprecated for quite a while. Your containers can refer to other containers in the same compose file by name without the use of links.


text:
Q: Is it required to implement In-App-Purchase or can I simply add the paid version as a new app? I already have a free version of my app in App Store. Now I want to add a completely new paid version of the same app (with extra features).
Is it required to implement In-App-Purchase or can I simply add the paid version as a new app?

A: You can create a paid version of your app with no problem. It will get approved. So it's really up to you. But using in-app purchase makes it more convenient to the user. They will be able to switch to full version of the app without losing any data (like achievements for a game, or documents created with the free app).

A: If you look at the app store, you'll see both options. There are many free "lite" versions of an app, and the full versions which you need to pay for.
In-App purchases are also common, yet they need more effort to develop.


text:
Q: Rails JSON/JSONP and JBuilder. How to get the correct MIME type / content type? If I render the whole record to JSON is works fine for both JSON and JSONP, but I want to customize the response (ideally via JBuilder). But when using JBuilder the MIME type / content-type goes to application/json and I need text/javascript
The JS code is a standard jquery ajax dataType: 'jsonp'
controller:
format.json { render json: @event, callback: params[:callback] }

This works and correctly switched content-type depending on if the request has a callback or not, but I want to do a lot of JSON customization. Is there a way to do this via JBuilder?
I tried JPBuilder Gem, but it didn't correct the content-type (it stayed at application/json)

A: Ok, I got it to work with an after_filter. Is there a better way to do this?
controller:
class EventsController < ApplicationController
  after_filter { |controller| handle_jsonp(controller) }

   def show
     ...
     respond_to do |format|
       format.json
       format.html
     end
   end

   private

   def handle_jsonp(controller)
     if controller.params[:callback]
       controller.response['Content-Type'] = 'application/javascript'
       controller.response.body = "/**/#{controller.params[:callback]}(#{controller.response.body})"
     end
   end
end

Source: Stephen Paul Suarez's comment on this RailsCast


text:
Q: C#, Inserting Multiple Rows Into An SQL Database I have an Access database. I'm using C# and Visual Studio  I'm attempting to insert several rows within a transaction.  However, instead of inserting each row, I end up with the first element inserted multiple times.
I can insert the data into the "Invoices" table one row at a time, so the table is in working order.  I included the code below.  The rows do have varied data.  The debugger shows that.
private void insertInvoiceItemsIntoDatabase(int tableNumber)
{
    string category, food;
    double price
    string connectionString = _databaseConnectionString;

    using (OleDbConnection connection =
               new OleDbConnection(connectionString))
    {
        OleDbCommand command = new OleDbCommand();
        OleDbTransaction transaction = null;

        // Set the Connection to the new OleDbConnection.
        command.Connection = connection;

        // Open the connection and execute the transaction.
        try
        {
            connection.Open();

            // Start a local transaction with ReadCommitted isolation level.
            transaction = connection.BeginTransaction(IsolationLevel.ReadCommitted);

            command.Connection = connection;
            command.Transaction = transaction;

            command.CommandText = "Insert into Invoices (TableNumber, Category, Food, Price) VALUES (?,?,?,?)";

            command.CommandType = CommandType.Text;

            Order order;
            order = tables[tableNumber - 1].getOrder();
            List<MenuItem> items = order.deepCopyMenuItems();
            for (int i = 0; i < items.Count(); i++)
            {
                FoodType ft =  items[i].getFoodType();
                category = "Main Course";
                if(ft == FoodType.maincourse)
                {
                    category = "Main Course";
                }else if(ft == FoodType.drink)
                {
                    category = "Drink";
                }else if(ft == FoodType.dessert)
                {
                    category = "Dessert";
                }

                food = items[i].getItemName();
                price = items[i].getItemPrice();

                command.Parameters.AddWithValue("TableNumber", tableNumber);
                command.Parameters.AddWithValue("Category", category);
                command.Parameters.AddWithValue("Food", food);
                command.Parameters.AddWithValue("Price", price);
                command.ExecuteNonQuery();
            }

            transaction.Commit();
        }
        catch (Exception ex)
        {
            Console.WriteLine(ex.Message);
            try
            {
                // Attempt to roll back the transaction.
                transaction.Rollback();
            }
            catch
            {
                // Do nothing here; transaction is not active.
            }
        }
    }
}

A: Create params with a proper type before the loop. Set values in loop.
        ...
        command.CommandText = "Insert into Invoices (TableNumber, Category, Food, Price) VALUES (?,?,?,?)";

        command.CommandType = CommandType.Text;
        command.Parameters.Add("TableNumber", /*param type*/);
        command.Parameters.Add("Category", /*param type*/);
        command.Parameters.Add("Food", /*param type*/);
        command.Parameters.Add("Price", /*param type*/);

        Order order;
        order = tables[tableNumber - 1].getOrder();
        List<MenuItem> items = order.deepCopyMenuItems();
        for (int i = 0; i < items.Count(); i++)
        {
            FoodType ft =  items[i].getFoodType();
            category = "Main Course";
            if(ft == FoodType.maincourse)
            {
                category = "Main Course";
            }else if(ft == FoodType.drink)
            {
                category = "Drink";
            }else if(ft == FoodType.dessert)
            {
                category = "Dessert";
            }

            food = items[i].getItemName();
            price = items[i].getItemPrice();

            command.Parameters["TableNumber"].Value = tableNumber;
            command.Parameters["Category"].Value =  category;
            command.Parameters["Food"].Value =  food;
            command.Parameters["Price"].Value =  price;
            command.ExecuteNonQuery();
        }
        ...


text:
Q: Run cronjobs in different timezones I have some cronjobs that I want to run. I want two of my scripts to run in UTC and the rest in CET. I have tried with cron_tz but it does not seem to work.

A: CRON_TZ=Europe/Amsterdam

works. Mind though that it could be that specific Ubuntu's do not work with CRON_TZ. man 5 crontab tells you if it is supported. If it does not have this, then yours does not support it:

The CRON_TZ variable specifies the time zone specific for the cron table. The user should enter a time according to the specified time zone into the table. The time used for writing into a log file is taken from the local time zone, where the daemon is running.

It probably does not and you should be using systemd.timer and systemd.time and calendar events. Each unit holds its own timezomne so that will fix your problem.

A: Preface the command with TZ=CET, or set the TZ environment variable
[~]$ TZ=UTC date
Thu Dec 15 14:53:51 UTC 2022
[~]$ TZ=CET date
Thu Dec 15 15:53:54 CET 2022


text: Q: Is there a way to create custom network throttling profiles from a Chrome extension? I know that Chrome now supports network throttling form the Network tab of DevTools, but I want to create a Chrome extension that either does this itself or utilizes the existing DevTool to create a custom throttling speed. What would be the best way to go about this?


text:
Q: Sampling pandas DF to match a second DF within error Suppose I have two DFs, say df1,df2 as follows:
import pandas as pd
import numpy as np
df1 = pd.DataFrame([[0,1,100],[1,1.1,120],[2,0.8,102]],columns=['id','a','b'])
df2 = pd.DataFrame([[0,0.5,110],[1,1.05,94],[2,0.96,145],[3,0.86,112],[4,1.3,97]],
                    columns=['id','a','b'])

print(df1)
   id    a    b
0   0  1.0  100
1   1  1.1  120
2   2  0.8  102
print(df2)
   id     a    b
0   0  0.50  110
1   1  1.05   94
2   2  0.96  145
3   3  0.86  112
4   4  1.30   97

Now, suppose I choose some interval size da,db. I want, for each row in df1, to pick a random row from df2, such that abs(a1-a2)<da,abs(b1-b2)<db. What I am currently doing is very brute force:
da = 0.2
db = 25
df2_list=[]
nbad = 0
for rid,row in df1.iterrows():
    ca = row['a']
    cb = row['b']
    c_df2 = df2[np.abs(df2['a']-ca)<da]\
            [np.abs(df2['b']-cb)<db]
    if len(c_df2) == 0:
        nbad+=1
        continue
    c_df2 = c_df2.sample()
    df2_list.append(c_df2['id'].values[0])

matched_df = df2[df2['id'].isin(df2_list)]
print(matched_df)

   id     a    b
1   1  1.05   94
3   3  0.86  112
4   4  1.30   97

However, for my real purpose, where my DF is really big, this is very slow.
Is there a faster way to achieve this result?

A: Here's a solution:
da = 0.2
db = 25

res = pd.merge(df1.assign(dummy = 1), df2.assign(dummy = 1), on = "dummy").drop("dummy", axis = 1)
res = res[(np.abs(res.a_x - res.a_y) < da) & (np.abs(res.b_x - res.b_y) < db)]
res = res.groupby("id_x").apply(lambda x: x.sample(1))[["id_y", "a_y", "b_y"]]
res.index = res.index.droplevel(1)
print(res)

The output is:
      id_y   a_y  b_y
id_x
0        1  1.05   94
1        4  1.30   97
2        3  0.86  112


text:
Q: Beautiful Soup not parsing all tags I have attached a screenshot of the HTML of the website I am trying to scrape, there is a table and within it I want to get some of the data from the rows which are within body (they clearly exist), however, it was not working so I decided to print tbody which revealed that the parsing found the table and tbody but not the rows within. I don't know how to fix this any help would be appreciated.HTML from wesbite
Output when printing body
This is the beginning of my code:
url = "https://superfpl.com/player_stats"

results = requests.get(url)

soup = BeautifulSoup(results.text, "html.parser")

players = []

teams = []

positions = []

ownerships = []

print(soup.find("tbody"))

player_div = soup.find_all('tr', role_="row",  class_="odd")

A: The data is loaded dynamically through JavaScript. But you can simulate it with the requests module:
import requests

url = 'https://superfpl.com/ajax/player_stats'
data = requests.get(url).json()

# uncomment this to see all data (WARNING, huge list!):
# import json
# print(json.dumps(data, indent=4))

# pretty print some data to screen:
for row in data['data']:
    print('{:<20}{:<20}{:<20}'.format(row['web_name'], row['position'], row['points_per_game']))

Prints:
Connolly            FWD                 2.4
Cresswell           DEF                 2.7
Lennon              MID                 0.9
Mooy                MID                 2.9
Ramsdale            GKP                 3.4
Wan-Bissaka         DEF                 3.3
Koiki               DEF                 0.0
Doucouré            MID                 3.3
Idah                FWD                 1.3
Lallana             MID                 1.8
Masina              DEF                 2.8
Adam Smith          DEF                 2.2

... and so on.


text:
Q: Manually adding spatial reference information for FEWS rainfall data using QGIS I am trying to match rainfall data from USGS/FEWS to coordinate locations of survey households in Ethiopia, so I will need to be able to project the rainfall data.  I downloaded the East Africa rainfall estimate from [USGS/FEWS]. So far, I downloaded the dekadal RFE 2.0 files for East Africa (bulk by year), and for each dekadal, there are five files: .bil, .blw, .clr, .hdr, and .stx. I first added the data (the .bil file) to QGIS, using Africa Albers Equal Area Conic as Projected Coordinate Systems. And then, I opened CSV data of village latitude and longitude and saved it to Africa Albers Equal Area Conic.They looked fine and I could extract point values using point sampling tool.
However, there was wide dispersion from the precipitation data provided by survey. The survey uses the same USGS/FEWS rainfall data as I did, but uses household location rather than village location information. Since dispersion is so wide, I suspect that dispersion came from CRS I chose, rather than household/village level difference. From the USGS/FEWS website, I know following projection information:
 Coordinates for corners:

 Lower left lat : -42.243 deg
 Lower left lon : -23.490 deg
 Upper left lat : 43.711 deg
 Upper left lon : -24.600 deg
 Lower right lat : -42.242 deg
 Lower right lon : 63.414 deg
 Upper right lat : 43.712 deg
 Upper right lon : 64.523 deg

 Image size : 1152 rows x 1152 cols
 Center lat,lon : 1.000000, 20.000000
 Pixel size h x w : 8.000000 km x 8.000000 km
 Origin of latitudes : 1.000000 deg
 Central meridian : 20.000000 deg
 First std parallel : -19.000000 deg
 Second std parallel : 21.000000 deg
 Projection = ALBERS Conical Equal-area projection uses the clarke 1866 spheroid

Using this information, I am trying to custom projection as follows:
+proj=aea +lat_1=-19 +lat_2=21 +lat_0=1 +lon_0=20 +x_0=0 +y_0=0 +datum=NAD83 +units=m +no_defs +ellps=clrk66

Can anybody confirm whether this projection is correct?
I am beginner of QGIS user and only know the following basic parameters.

*

*lat_1 : First std parallel

*lat_2 : 2nd std paralell

*lat_0 : Origin of latitudes

*lon_0 : Central meridian

But I am not sure about +datum and +units.

I re-did all the process using projection I made above:

*

*Add dekadal rainfall data as raster layer using projection I customed.

*Add Ethiopia administrative data as vector layer. I downloaded it from the website of Global Administrative Areas. This layer appeared as a small point on QGIS screen because Ethiopia administrative data is provided as WGS84 projection.

*Save Ethiopia administrative data to the projection I customed.

*Add village longitude and latitude csv data as delimited text layer using WGS84.

*Save village longitude and latitude data as ESRI shapefile to the projection I customed.

*Extract rainfall data using point sampling tool. Save the newly created layer as csv.

And I got exactly the same attribute table I got with Africa Albers Equal Area Conic projection. So, I do not know why the rainfall data I extracted do not match the survey rainfall data.
Is my entire procedure correct?
Below is the table I made with survey data and extracted rainfall data; h2011_tot (annual total rainfall of 2011 from the survey) and total2011 (sum of all the 36 dekadal data I extracted as above). The survey data contain 2011's annual total rainfall as well as village level longitude and latitude information which I used above. I wanted to produce 2012's annual total rainfall but I first made 2011's annual total rainfall to confirm it matches with survey rainfall data. And I found they do not match each other.
As we can see below, there is wide dispersion between h2011_tot and total2011, although their means and standard deviations seem very close to each other.
Do you have any idea why h2011_tot and total2011 look so different?

A: I downloaded some East Africa rainfall data and set that projection for it in QGIS. It was definitely in East Africa but seemed to reach further west than in the red box outlining the data area on the web page. So I downloaded a rainfall file for Africa as a whole, and set the same projection for it. This lines up exactly with the East Africa raster, and seems to cover Africa correctly. So I think its correct.
This image shows the Africa rainfall (blue-green) and the East Africa rainfall raster (grey) over an OpenStreetMap world. The extent of the Africa raster looks correct, and I can toggle the East Africa on and off and it matches the underlying continental rain exactly. So if Africa rain is in the right place, then East Africa rain is in the right place.

The corners of my Africa raster don't match the ones given above, but then this raster is 994x1089 and not 1152x1152, so I suspect that refers to a larger raster.
I would suggest you proceed with caution, and if possible keep looking to try and find a definitive description of what the file's metadata are. Also, my QGIS map looks almost exactly like the rainfall map in the "Product" section (except it is cropped to the land), which further makes me think you've got this right.

So the African rain is in the right place, so therefore the East African rain raster is in the right place. Just apply that projection to the raster and you should be good to go.


text:
Q: Failed to read auto-increment value from storage engine catalog_product_entity_varchar Can't add a new product and get an error.
SQLSTATE[HY000]: General error: 1467 Failed to read auto-increment value from storage engine, query was: INSERT IGNORE INTO catalog_product_entity_varchar (entity_id,attribute_id,store_id,value) VALUES (?, ?, ?, ?), (?, ?, ?, ?), (?, ?, ?, ?), (?, ?, ?, ?), (?, ?, ?, ?)
Similar issue: https://github.com/magento/magento2/issues/21890

Please help us to solve this.
Thanks

A: Run this query on your database
ALTER TABLE `catalog_product_entity_varchar` AUTO_INCREMENT = // last record's value_id+1 which is currently present in your table e.g if value_id is 5 than AUTO_INCREMENT = 6. If table is empty than put AUTO_INCREMENT = 1;

Don't forget to create a backup of your DB first.


text:
Q: Check ReadKey only for letters (alphabet) in string i am doing game "Hangman" but i have a problem. I am using ReadKey to find the guess of player, but he can use even numbers or buttons like "Enter" etc. I want to stop this, but i don't know how :/ Can you help me please? I want control, if in result of ReadKey is letter from alphabet or no (but it must be in "string" format, cuz i am working later with string). Thank you very much guys, here is my code :)
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Hangman
{
    class MainClass
    {
        /// <summary>
        /// Hra Oběšenec
        /// </summary>
        /// <param name="args"></param>
        static void Main(string[] args)
        {

            Console.WriteLine("Vítejte ve hře Oběšenec!");
            //List slov, které bude hráč hádat
            string[] words = new string[5];
            words[0] = "car";
            words[1] = "school";
            words[2] = "apple";
            words[3] = "orange";
            words[4] = "xamarin";
            //Získávám délku slova (hádaného slova)

            for (int X = 0; X < words.Length; X++)
            {
                string guessWord = words[X];
                short lifes = 5;
                short guessedLetters = 0;
                char GuessingLetter;
                char[] lettersOfWord = new char[guessWord.Length];
                //
                for (int I = 0; I < guessWord.Length; I++)
                {
                    //Length of word is changing to *
                    lettersOfWord[I] = '*';
                }
                bool InGame = true;
                //When this while is true, the game is still going, when it will be false, the game will end
                while (InGame)
                {
                    //Ochrana proti špatnému inputu
                    try
                    {

                        Console.WriteLine(lettersOfWord);
                        Console.WriteLine("Stiskněte klávesu. Životy:" + lifes);
                        ConsoleKeyInfo result_guess = Console.ReadKey(true);
                        string result = result_guess.KeyChar.ToString();

                    if (result.Length == 0)
                    {
                        continue;
                    }
                    //Hráč hádá slovo
                    GuessingLetter = result[0];
                    lifes--;
                    for (int I = 0; I < lettersOfWord.Length; I++)
                    {
                        if (lettersOfWord[I] == '*')
                        {
                            //Pokud hráč uhádne písmenko ve slově
                            if (guessWord[I] == GuessingLetter)
                            {
                                lettersOfWord[I] = GuessingLetter;
                                guessedLetters++;
                                lifes++;
                                Console.WriteLine("Správně!");
                            }
                        }
                    }
                    }
                    catch (Exception e)
                    {
                        Console.WriteLine("Nastala neočekávaná chyba!" + e);
                    }
                    //Pokud prohraje(promrhá všechny pokusy) hra skončí, avšak pokud slovo uhádne (a zůstane alespoň jeden život) vyhrál hru
                    if (lifes== 0 || guessedLetters == guessWord.Length)
                    {
                        //Konec hry
                        InGame = false;
                        if (lifes == 0)
                        {
                            Console.WriteLine("Smůla prohrál jsi!");
                            Console.ReadKey();
                            break;
                        }
                        else
                        {
                            //Vítězství nad levlem
                            Console.WriteLine("Uhodnul jsi celé slovo! Gratuluji!!");
                        }
                    }
                }
            }
        }
    }
}

A: Check if the keychar is a letter with the IsLetter method and keep asking for letters if it doesn't. Something like this:
private char GetLetter()
{
    while (true)
    {
        Console.WriteLine("Please input a letter.");
        var character = Console.ReadKey().KeyChar;
        if (char.IsLetter(character))
            return character;
    }
}


text:
Q: homogeneous differential equations 5 Hi how do i solve the following ODE
$$(x+y)y'= 3y-x$$given $y(2)=1$.
So here's what I was thinking this is non-linear but I can see it looks like a homogeneous first order ODE so fiddling around I get:
$$y'=\frac{3\frac{y}{x}-1}{1+\frac{y}{x}}$$.
But i have no idea how to do go ahead. Any help appreciated.

A: substituting $$\frac{y}{x}=u$$ then we get $$y=ux$$ and we get $$y'=u'x+u$$
can you finish?
and you will get
$$\frac{du}{dx}x=\frac{-u^2+2u-1}{u+1}$$ this is separable
and now you can write
$$-\frac{u+1}{(u-1)^2}du=\frac{dx}{x}$$
does it work now?


text:
Q: how to optimize react app for real time Data streaming I am working on a project which involves real-time data streaming from node js servers to react js. This data is further used to display real-time charts. I am using socket io for real-time data stream .my code for the app
const socket = io.connect("http://localhost:4000")
function App() {
const [showModal, setShowModal] = useState(false)

const [count, setCount] = useState(0)

const [GD, setGD] = useState([])
const dataGather = (data1) => {
var len = GD.length;

if (len >50) {
  var array = GD; // make a separate copy of the array
  console.log(len)
  var index = array.indexOf(len);
    array.splice(index, 1);
    setGD(array);

} else {
  setGD(GD => [data1, ...GD])
}

}

useEffect(() => {
socket.on("connect", () => {
  console.log("connected Successfully");
});

socket.on('wave', (data1) => {

  //i  want to run this part only one time so i used count here
  if (count < 1) {
    setCount(1)

    setShowModal(true);
  }
  dataGather(data1);
})
},[]);
return (

  {showModal == true ? <Example hideModal={hideModal} GD={GD} showModal={showModal} /> : <></>}

);

In this code, I want to display when new data arrives I call a function which helps to open MODAL BOX.inside Modal my graph component is called and display the graph.
key problems:

*

*Datastream is so fast

*when I open the modal the other back UI
stops working.

*when I close the Modal data takes time to stop.

*I also want to empty my last index of the array every time so that every new entry is appended at the start.

My Modal Component
useEffect(() => {
handleChannelId();
}, [GD])
return (
<>

  {
    ch > 0 ?
      <Modal size="lg" aria-labelledby="contained-modal-title-vcenter" backdrop="static" keyboard={false} centered show={show} onHide={handleClose}  >
        <Modal.Header closeButton className=" text-dark py-1 header-bg bg-light">
          <Modal.Title>Channel ID: {ch}</Modal.Title>
        </Modal.Header>

        <Modal.Body className="p-0" style={{ backgroundColor: "#062F2E" }}>
          <Row>
            <Col lg={11} className="p-2">

                <Graph GD={GD} zoom={zoom} />

            </Col><Col lg={1} style={{ padding: "30px" }}>
              <input className="pl-3" type="range" value={zoom} class="form-range" orient="vertical" onChange={(e)=>setZoom(e.target.value)} min={-250} max={250} step={50} id="customRange3"></input>

            </Col>
          </Row>
        </Modal.Body>
      </Modal>
      : <></>}
</>
);
}


text:
Q: Translating and Rotating without Push/Pop Matrix I'm working on an OpenGL application, specifically for Android with OpenGL ES (2.0 I think). I can currently draw objects independently and rotate the scene all at once. I need to be able to translate/rotate individual objects independently and then rotate/translate the whole scene together. How can I accomplish this? I've read several threads explaining how to push/pop matrices but I'm pretty sure this functionality was deprecated along with the fixed function pipeline of OpenGL 1.1.
To give some perspective, below is the onDrawFrame method for my renderer. Field, Background and Track are all classes I've made that encapsulate vertex data and the draw method draws the appropriate matrices to the supplied context, in this case GL10 'gl'.
        //clear the screen
    gl.glClear(GL10.GL_COLOR_BUFFER_BIT |GL10.GL_DEPTH_BUFFER_BIT);
    // TODO Auto-generated method stub

    gl.glMatrixMode(GL10.GL_MODELVIEW);
    gl.glLoadIdentity();
    GLU.gluLookAt(gl, 0, 0, 60, 0, 0, 0, 0, 2, 0);//setup camera

    //apply rotations
    long time = SystemClock.uptimeMillis();
    float angle =  ((int)time)/150.0f;
    gl.glRotatef(55.0f, -1, 0, 0);//rotates whole scene
    gl.glRotatef(angle, 0, 0, -1);//rotates whole scene

    MainActivity.Background.draw(gl);
    MainActivity.Track.draw(gl);
    MainActivity.Field.draw(gl);

*Update: As it turns out, I can push and pop matrices. Is there anything wrong with the pushing/popping method? It seems to be a very simple way of independently rotating and translating objects which is exactly what I need. *

A: There should be nothing wrong with using glPushMatrix and glPopMatrix. The Android implementation of ES 2.0, to my understanding, has default shaders which behave exactly like the default fixed-function pipeline, and you can use the fixed-function pipeline functions. They will behave identically.


text:
Q: Can one have multiple name servers that don't all belong to the same TLD/provider? In light of the GoDaddy outage we updated our name server list for our domain to include an additional name server provider. The list looks something like this:

*

*ns61.domaincontrol.com

*ns54.domaincontrol.com

*ns1.dreamhost.com

*ns2.dreamhost.com

Both Godaddy and Dreamhost have zone entries to handle the A and MX records. The idea is that if one provider goes out the other will be a fall-back.
However, when I tested my config with http://www.intodns.com/ I am getting a warning about SOA serials not being agreed.
Have I misunderstood some fundamentals in name-server config? What can I do to prevent future problems?

A: You sure can.
For example, where I work, we have 4 name servers, 2 hosted with one DNS host, one hosted by us, and the other one hosted by a second external DNS host.
The SOA (start of authority) serials not being agreed indicates that there's [most likely] a sync issue with your DNS - not all the name servers are serving up the same version of your DNS records.  This may be an actual problem, or it may indicate that DNS hasn't fully propagated from your authoritative name server(s) to the rest.
Here's a quick KB I found from MS about the structure of an SOA record.  Hopefully that will help clarify what's going on for you.

Serial number - The revision number of this zone file. Increment this number each time the zone file is changed. It is important to increment this value each time a change is made, so that the changes will be distributed to any secondary DNS servers.

A: The fact that the SOA serial numbers don't match makes perfect sense due to the fact that you're using different DNS providers. The SOA serial numbers between providers isn't going to match unless one provider supports zone transfers to the other, which isn't likely...but that's OK. The serial numbers don't have any bearing on name resolution for your domain, they have meaning only for the name servers hosting the zone, either at the same provider or amongst all of the name servers hosting the zone if zone transfers are allowed to all of them. What you need to make sure is that when you add, change or delete a record at one provider that you do the same at the other provider. The master/slave mechanism that keeps DNS records in sync at one provider isn't going to keep your records in sync at the other provider, you're going to have to manually do that yourself by updating the zone at each provider with the same records.


text:
Q: What does >+ and >- mean in C# I had accidentally tried this, which compiles! So I was wondering what could this possibly mean.. google didnt help..
if (3 >+ 4)
   dothis() //this is never hit btw..

if (3 >- 4)
   dothis() //this is hit.

Both the code compile btw..

A: Is 3 greater than 4?
Is 3 greather than -4?
If you're ever in doubt about what something is doing, write a little test app:
  int i = +3;
  int j = -4;

  Console.WriteLine(i);
  Console.WriteLine(j);

  Console.WriteLine((3 > +4));
  Console.WriteLine((3 > -4));

A: Try putting a semicolon after dothis() like
dothis();

Then watch what happens to the + and - operator. They will be shifted away from greater or less than sigh and move nearer to 4.
if (3 > +4)
   dothis() //this is never hit btw..
            //will never hit in the entire universe

if (3 > -4)
   dothis() //this is hit
            //will always be a hit

First becomes if 3 > +4 (Positive 4) which will always result in false.
Second becomes if 3 > -4 (Negative 4) which will always result in true.

A: It parses as
3 > +4

and
3 > -4

So into the unary + and unary - operators.
If you want an interesting way to explore this, write
Expression<Func<int, int, bool>> func = (x, y) => x >+ y;

and then explore the resulting expression tree func in the debugger. You'll see the unary operator in the tree.


text:
Q: How do you calculate latitude and longitude of a point in a static map? Background: I have generated a static map (map.png) of a particular city using mapnik and osm data of the highest zoom level. I am able to zoom in and zoom out successfully using my Java program. It is an offline desktop application.
Question: I want to represent a point at a particular latitude and longitude on this map. How do I do it?
I went through the following references:
http://wiki.openstreetmap.org/wiki/Zoom_levels
http://wiki.openstreetmap.org/wiki/Slippy_map_tilenames#Resolution_and_Scale
How to plot a point on a static Google map [png]?
I'm still not able to understand how to plot it on a static map by calculating a specific latitude and longitude at a particular zoom level with the image having a specific pixel width and height.

A: from what I understand, you have a single ungeoreferenced image, and you want to find the extent.
This can be done in QGIS
QGIS - Using Capture Coordinate
If this is an urban map with details in the corners, you can manually match up the corners using the Capture coordinate plugin.

*

*start with an empty project

*Install the OpenLayers plugin (this goes in the Web menu), and use this to show OSM for the region around your city

*Install the "Capture coordinate" capture plugin, and bring up the Capture coordinate panel using the Vector > Coordinate Capture. You might want to set the sampling to EPSG:4326 to get traditional latitude, longitude coordinates

*For two corner points on your png (diagonally opposite), look at the corner of your png and find its position in OSM, panning and zooming as required.

*click on 'start capture', then click on the point corresponding to the corner of your image

*once you have two diagonally opposite corners' coordinates, it's now simple maths to interpolate a pixel position to/from lat, lon
QGIS - Using georeferencing
This is a little more advanced, but will give you results if it's not possible to exactly pick out where the corners are (for example, if it's empty ground or in the sea)

*

*start with empty project

*use OpenLayers plugin to display OSM as before

*install the Georeferencer plugin

*start it up with Raster > Georeferencer

*load in your png raster (first icon)

*find some landmark on your png as close as possible to one corner- a building, for example, or a road junction

*click on add point, and in the dialog check 'from map canvas'. If you have a mouse wheel you can pan with that. Click on the corresponding place in the OSM map.

*repeat for the other 3 corners

*see the GCP table? Those are your coordinates ('ground control points')

*click on Transformation settings, and set up where you want to save the raster. You might want to change the crs to EPSG:4326 if you want lat,lon.

*click on the Run icon (green arrow)

*you'll now have a georeferenced tiff.

There's quite a good step-by-step guide here, although it's a bit out of date.
Now if you open this geotiff (add as a raster layer) you go into properties and you'll see your extent.