text:
Q: Is there a classification of ideals of $\mathcal O_K$ ($K$ quadratic) over ramified and split primes depending on $d \pmod 4$? I am unsure if the following argument is correct. I have not seen something like this in my course, so I'm a bit skeptical, since this seems like a very simple way of computing norms of ideals.

If $a \in I \trianglelefteq \mathcal O_K$ then $(a)\subseteq I$ and so $$\frac{I}{(a)}\trianglelefteq \frac{\mathcal O_K}{(a)} \implies \frac{\mathcal O_K /(a)}{I/(a)}\cong \frac{\mathcal O_K}{I} \implies \left| \frac{\mathcal O_K}{I} \right| \left| \frac{I}{(a)} \right| = \left| \frac{\mathcal O_K}{(a)} \right| \implies  \left| \frac{\mathcal O_K}{I} \right| \leq \left| \frac{\mathcal O_K}{(a)} \right| $$ with equality iff $I=(a)$. Hence $N(a)$ is a proper divisor of $ Norm(I)$ if $I \supsetneq (a)$. Hence, in the example $I=(7, 1+\sqrt{15})\trianglelefteq \mathcal{O}_{\mathbb Q(\sqrt {15})} $, $ 7 \in I \implies Norm(I)$ properly divides $49$. So it has norm $1$ or $7$. But clearly $1 \notin I$ so it has norm $7$.

I am wondering, because of this, if there is a simple classification of the prime ideals over ramified, split and inert primes. Is the following true:

Let $K=\mathbb Q(\sqrt d)$. First let $d \equiv 2,3 \pmod 4$. If $p$ is a ramified prime and $p|d$ then the unique ideal of norm $p$ in $\mathcal O_K$ is $(p,\sqrt d)$ and if $p\nmid d$ then necessarily $p=2$, $d\equiv 3 \mod 4$ and the unique ideal is $(2,1+\sqrt{d})$. If $p$ is split then the two ideals of norm $p$ are given by $(p, a \pm \sqrt d)$ where $a$ is the smallest natural number such that $p|Norm( a + \sqrt d).$

Now if $d\equiv 1 \pmod 4$ then I'm not really sure how to proceed. E.g. if $K=\mathbb Q(\sqrt{-59}), \, 3$ splits in $\mathcal O_K$ but are the two ideals of norm $3$ equal to $(3,1\pm\sqrt{-59})$ or $(3,\frac{1\pm \sqrt{-59}}{2})$? When I'm thinking of norms of ideals $I$ in terms of $|\mathcal O_K/I|$ it seems like it's probably the second pair, but when I think of the above argument, it seems like both cases could work as $3|N(1\pm\sqrt{-59})=60$ and $3|N(\frac{1\pm \sqrt{-59}}{2})=15$.

Edit: $(\frac{1\pm \sqrt{-59}}{2})\cdot 3-(1\pm \sqrt{-59})=\frac{1\pm \sqrt{-59}}{2}$, so actually $(3,1\pm\sqrt{-59})=(3,\frac{1\pm \sqrt{-59}}{2})$ from the start. Should I have been able to deduce that these ideals are the same from the above argument, without spotting this little bit of arithmetic?

Does this generalise beyond this example? What happens in the ramified case? Is it perhaps the case that the norm of an element $r$ does not equal the norm of the ideal it generates (defined as $|\mathcal O_K/(r)|$) if $d \equiv 1 \pmod 4$?
I'm sorry this question is so long, but I felt like I needed to include all of my reasoning to explain my confusion. (If someone with more experience on this site thinks I should delete the question and post this as multiple questions, then comment below and I'll do so.) Feel free to answer a small part of the question if you don't want to tackle the whole thing at once. Any help would be much appreciated.


text:
Q: Failed to init Reactor's debug agent I'm getting an error with intellij when running a spring boot application. Using mvn spring-boot:run works fine, however running with the intellij run/debug mode both return this exception.
java.lang.RuntimeException: Failed to init Reactor's debug agent
    at org.springframework.boot.reactor.DebugAgentEnvironmentPostProcessor.postProcessEnvironment(DebugAgentEnvironmentPostProcessor.java:52)
    at org.springframework.boot.context.config.ConfigFileApplicationListener.onApplicationEnvironmentPreparedEvent(ConfigFileApplicationListener.java:188)
    at org.springframework.boot.context.config.ConfigFileApplicationListener.onApplicationEvent(ConfigFileApplicationListener.java:176)
    at org.springframework.context.event.SimpleApplicationEventMulticaster.doInvokeListener(SimpleApplicationEventMulticaster.java:172)
    at org.springframework.context.event.SimpleApplicationEventMulticaster.invokeListener(SimpleApplicationEventMulticaster.java:165)
    at org.springframework.context.event.SimpleApplicationEventMulticaster.multicastEvent(SimpleApplicationEventMulticaster.java:139)
    at org.springframework.context.event.SimpleApplicationEventMulticaster.multicastEvent(SimpleApplicationEventMulticaster.java:127)
    at org.springframework.boot.context.event.EventPublishingRunListener.environmentPrepared(EventPublishingRunListener.java:76)
    at org.springframework.boot.SpringApplicationRunListeners.environmentPrepared(SpringApplicationRunListeners.java:53)
    at org.springframework.boot.SpringApplication.prepareEnvironment(SpringApplication.java:345)
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:308)
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:1226)
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:1215)

Removing this dependency causes it to run properly in intellij
    <dependency>
      <groupId>io.projectreactor</groupId>
      <artifactId>reactor-tools</artifactId>
    </dependency>

redpajama_set_name: RedPajamaStackExchange


text:
Q: undefined is not an object(singleValue.StopTracking) on Swipe animation I have a Delete on Swipe function that returns TypeError: undefined is not an object(evaluating 'singleValue.StopTracking')
Im using expo to run the project
After I swipe, expo returns the error, I click dismiss and the product disappears from my cart
I don't know what any more information to give

const rowTranslateAnimatedValues = {};
      Array(20)
      .fill('')
      .forEach((_, i) => {
          rowTranslateAnimatedValues[${i}] = new Animated.Value(1);
      });
const [cart, setCart] = useState([]);

const [products, setProducts] = useState([]);

const [valueInput, setValueInput] = useState(1);

const [listData, setListData] = useState(
    Array(4)
        .fill('')
        .map((_, i) => ({ key: `${i}`, text: `item #${i}` }))
);

const onSwipeValueChange = swipeData => {
  const { key, value } = swipeData;
  if (
      value < -Dimensions.get('window').width &&
      !this.animationIsRunning
  ) {
      this.animationIsRunning = true;
      Animated.timing(rowTranslateAnimatedValues[key], {
          toValue: 0,
          duration: 500,
      })
      .start(() => {
          const newData = [...listData];
          const prevIndex = listData.findIndex(item => item.key === key);
          newData.splice(prevIndex, 1);
          setListData(newData);
          this.animationIsRunning = false;

      });
  }
};

const renderItem = data => (
  <Animated.View
  >
      <TouchableHighlight
          onPress={() => console.log('You touched me')}
          style={styles.rowFront}
          underlayColor={'#AAA'}
      >
          <View>
              <Text>I am {data.item.text} in a SwipeListView</Text>
          </View>
      </TouchableHighlight>
  </Animated.View>
);

const renderHiddenItem = () => (
  <View style={styles.rowBack}>
      <View style={[styles.backRightBtn, styles.backRightBtnRight]}>
          <Text style={styles.backTextWhite}>Delete</Text>
      </View>
  </View>
);

return (
    <Block flex center style={styles.cart}>

<View style={styles.container}>
            <SwipeListView
                disableRightSwipe
                data={cart}
                renderItem={renderProduct}
                showsVerticalScrollIndicator={false}
                keyExtractor={(item, index) => `${index}-${item.title}`}
                ListEmptyComponent={renderEmpty()}
                ListHeaderComponent={renderHeader()}
                ListFooterComponent={renderFooter()}

                renderHiddenItem={renderHiddenItem}
                rightOpenValue={-Dimensions.get('window').width}
                onSwipeValueChange={onSwipeValueChange}
            />
        </View>
    </Block>
  );
}

A: For anyone who faces this problem,
you can just think this.animationIsRunning of a variable that manages the start and the end of animation.
So you can just use const animationIsRunning = useRef(false) to manage the animation state.
You can use animationIsRunning.current instead of this.animationIsRunning.
Also, this.animationIsRunning = true or false can be changed into animationIsRunning.current = true or false
See code at
https://github.com/jemise111/react-native-swipe-list-view/pull/521/commits/2946e3a123f26ef5292a3884e0aec58436386e18


text:
Q: Warning Implicit conversion loses integer precision I have this code:
//getIndividualWords(..) basically splits a sentence based on a specified delimiter: here delimiter is SPACE

vector<string> getIndividualWords(string line, string delimiter)
{
    int startingPosition = 0, endingPosition = 0, delimiterLength = delimiter.length();

    string words;
    vector<string> wordList; //stores all the words received by splitting the sentence

    while ((endingPosition = line.find (delimiter, startingPosition)) != string::npos) //the loop continues till it finds SPACES in the sentence
    {
        words = line.substr (startingPosition, endingPosition - startingPosition);
        startingPosition = endingPosition + delimiterLength;
        wordList.push_back (words);
    }

    wordList.push_back (line.substr (startingPosition)); //inserts the words into a vector container
    return wordList;
}

And I am getting this warning:

Implicit conversion loses integer precision

A: All of the std::string methods that deal with sizes and indexes operate on std::string::size_type values, not int values.  The size_type is usually std::size_t, which is an unsigned integer.  Converting an unsigned integer to a signed integer can lose precision.
So, startingPosition, endingPosition, and delimiterLength need to be declared as std::string::size_type to match what std::string actually uses.
Try this:
vector<string> getIndividualWords(const string &line, const string &delimiter)
{
    string::size_type startingPosition = 0, endingPosition, delimiterLength = delimiter.length();
    string words;
    vector<string> wordList;

    while ((endingPosition = line.find (delimiter, startingPosition)) != string::npos)
    {
        words = line.substr (startingPosition, endingPosition - startingPosition);
        startingPosition = endingPosition + delimiterLength;
        wordList.push_back (words);
    }

    if (startingPosition < line.length())
        wordList.push_back (line.substr (startingPosition));

    return wordList;
}


text:
Q: Parsing a XML string with no sense of keys I'm using OpenUri and RSS in Rails 5.2.3 and Ruby 2.6.1 to do this.
I'm trying to parse WeWorkRemotely's RSS feed, however, they have one field description that contains all the information in a string. For example, when I parse it in Rails it returns:
"\n\n
\n  Headquarters: San Francisco \n
URL: http://www.loom.com\n
\n\n
About Loom

Loom is a new kind of work communication tool, already helping over a million people get their message across through instantly shareable videos. Our users work at companies like HubSpot, Square, Uber, GrubHub and LinkedIn. Our mission is to be the global leader in human workplace communication. Founded in 2016, Loom has raised $15 million from top-tier investors including Kleiner Perkins, General Catalyst and Slack Fund.

The Role

As a Technical Support Engineer, you will be a key part of Loom's support experience at scale and provide timely and effective resolution to customer issues by applying your technical and troubleshooting skills.

We are looking for support champions who are genuinely happy to help others. If this sounds like you, you came to the right place!

As a Technical Support Engineer, you  will…\n

\n
Help customers through email to ensure they are successful with our product
\n
Leverage effective troubleshooting to quickly identify the source of customer issues and provide a prompt and appropriate solution
\n
Troubleshoot, investigate, and create detailed bug reports for our Engineering team
\n
Jump on ad-hoc calls with customers to troubleshoot issues live, as necessary
\n
Identify bugs, test, report, and working with our Engineering team to assist with a fix
\n
Actively collect insights from customers and focus on closing the communication loop by providing product feedback to the team
\n
Provide timely updates to the Support and Engineering Managers regarding new trends in issues
\n
Develop and document best practices to enhance SL2 troubleshooting processes
\n
Create technical documentation such as FAQs, guides, knowledge-base articles and how-to's for Loom customers
\n
Help the Engineering team develop tools to help our Support team work quickly and efficiently
\n
Dive into the codebase and gaining domain knowledge of different parts of Loom
\n
Make efficient changes to the codebase to solve small and quick tasks/issues
\n

\n
You could be a good fit if you have..\n

\n
Previous experience delivering excellent support experiences with respect, empathy and understanding
\n
A minimum of 4+ years of Technical Support and Customer Support experience
\n
Gained experience/proficiency in Saas solutions and electron apps (CSS, JavaScript, HTML) or have earned a degree in a technical field like computer science
\n
Technical understanding and ability to troubleshoot and resolve technical problems on your own
\n
The ability to handle high volume of support conversations
\n
Excellent written and spoken English
\n
Are available to work in the Central or Pacific Time Zone and on a full-time schedule that may span weekends and may include holidays as our customers need us
\n

\n
A bonus if you have experience with...\n

\n
Installation, configuration, and troubleshooting of Windows and Mac
\n
Troubleshooting protocols like HTTP, HTTPS, WebSockets, DNS
\n
Understanding of TCP/IP and ARP to run packet traces and troubleshoot network issues
\n
Any of these certifications: Cisco CCNA, Microsoft Certified Solutions Expert (MCSE), Apple Certified System Administrator, CompTIAA+, CompTIA Network+
\n

Perks at Loom

* Competitive compensation and equity package

* Medical, dental, and vision coverage (US-based team), healthcare reimbursement (non-US based team)

* Unlimited PTO

* Remote-first team

* Paid parental leave

* Yearly off-site retreats (this year we went to Costa Rica for a week!)

* Learning & Development reimbursement

* Wellness reimbursement

SF office perks

* Remote weeks every other month

* Daily in-office lunch, unlimited snacks & drinks

Remote-specific perks

* Home office & technology stipends

* New Hire Onboarding in SF

Loom is an equal opportunity employer.

We are actively seeking to create a diverse work environment because teams are stronger with different perspectives and experiences.

We value a diverse workplace and encourage women, people of color, LGBTQIA individuals, people with disabilities, members of ethnic minorities, foreign-born residents, older members of society, and others from minority groups and diverse backgrounds to apply. We do not discriminate on the basis of race, gender, religion, color, national origin, sexual orientation, age, marital status, veteran status, or disability status. All employees and contractors of Loom are responsible for maintaining a work culture free from discrimination and harassment by treating others with kindness and respect.
\n\n
To apply: https://jobs.lever.co/useloom/15398ec6-b2c1-4f95-9ef5-8fa2a62c1bed?lever-origin=applied&lever-source%5B%5D=WeWorkRemotely
\n"

What would be the best way for me to actually grab data from this block? Even if I try to pick things up like img src, head quarters, or a href links, it's a big string where I can't easily split that makes sense.

A: Don't treat it as a string, treat it as an HTML document. Then you can employ the full power of CSS or XPath selectors (or even manual traversal using Ruby methods).
require 'nokogiri'
doc = Nokogiri::HTML.fragment(str)

# img src
doc.at_css('img')["src"]
# => "https://we-work-remotely.imgix.net/logos/0015/9022/logo.gif?ixlib=rails-2.1.3&w=50&h=50&dpr=2&fit=fill&auto=compress"

# headquarters
doc.at_xpath('.//strong[contains(text(), "Headquarters")]/following-sibling::text()').text.strip
# => "San Francisco"


text:
Q: Looking for title/author of fantasy trilogy where man is transported via some sort of fairie circle Some time in the 90s, I think mid, there was a fantasy trilogy where a man was transported in some sort of fairie circle from the woods near his home to a type of medieval world. I know that the characters that knocked him out used darts to knock him out and those characters were small, more what would be considered "brownies" or such if discussing fairies. He had to do some sort of quests in all three books. I also remember that he aged in the medieval world but not his own, so if he stayed too long, it would be noticeable when he returned home. In I think the 3rd book of the series, he had a fiancee that the brownies also knocked out but weren't going to take but he grabbed one and threatened to crush its head if they didn't but would never do it.
I know this isn't a whole lot of detail, but if anyone has any idea of the series or author, please let me know.

A: It sounds like you're thinking of the Spearwielder's Tale series by R.A. Salvatore.
Wikipedia summary of the first book, The Woods Out Back:

Gary Leger works at a plastic manufacturing factory. Every day he has the same boring routine. Gary constantly refers to The Hobbit as his favorite book and reads it all the time. In the blueberry patch that is near his house through a steadily receding woodline, he sees a pixie holding a small bow before he passes out on the ground. He then awakes in the mystical forest of Tir'na'nog in the presence of the leprechaun Mickey McMickey. After being seduced by a nymph (Leshiye), he is rescued by the elf Kelsenellenelvial Gil-Ravardy (Kelsey for short), who takes Gary on a quest to re-forge the spear of the legendary hero Cedric Donigarten. There are however two problems. The first is that to re-forge the spear, they require the services of the finest blacksmith alive, the dwarf Geno Hammerthrower. To solve this problem they capture him in his home. The second problem is that it must be forged in the flames of a dragon. On their way to visit the dragon Robert they are captured by the witch Ceridwen. Gary and company, through a plan developed by Gary, escape Ynis Gwydrin with the help of a giant named Tommy and make it to the lair of Robert. Kelsey (or rather an image of Kelsey conjured by Mickey) defeats Robert in single combat and convinces him to reforge the spear. Upon returning home, Gary is assured of the reality of all the events in the book when he sees that his book is still in the script of Mickey McMickey.

In the third book his wife Diane is with him - that may be the "fiancee" part you're remembering.


text:
Q: Mysql add auto increment column I am trying to add column to a table in mysql with increment numbers, no matter if some of the rows would be deleted.
For example:
id  name   surname  question/column
1   Peter  Peterson       1
5   Mike   Nikolson       2
11  Selena Selenson       3

The point is to get in every moment increment values, cause I need a list with numbers.
Hope that is no big deal for much experiences database brains.

A: If you are trying to add an enumerated column to a result set, then use variables:
select jb, (@rn := @rn + 1) as seqnum
from justbrackets jb cross join
      (select @rn := 0) vars
order by id;


text:
Q: Xcode: Array Count not Empty, but Array index is empty? I recently notice that my app started to crash when loading the UIImageView*SideButton1, due to that "index 2 beyond bounds for empty array".
So I did NSLog to check whether I have the downloaded the data and put into the array correctly.
Below NSLog(@"topbanner1 %lu ",sizeof(delegate.sidebannerDetailsArray)) returns 8, but NSLog(@"topbanner1:%@",delegate.sidebannerDetailsArray) return empty.
2018-01-04 12:18:03.320192+0800  topbanner1 8

2018-01-04 12:18:03.320429+0800  topbanner1:()

    NSLog(@"topbanner1 %lu ",sizeof(delegate.sidebannerDetailsArray));
    NSLog(@"topbanner1:%@",delegate.sidebannerDetailsArray);

    UIImageView * SideButton1 = [UIImageView new];

    [SideButton1 sd_setImageWithURL:[NSURL URLWithString:[[delegate.sidebannerDetailsArray objectAtIndex:2]objectForKey:@"bannerImage"]]];

    }

    [SideButton1 setContentMode:UIViewContentModeScaleAspectFit];
    [SideButton1 setFrame:CGRectMake(itemPriceLabel.frame.size.width-160,ItemTitleLabel.frame.size.height+ItemTitleLabel.frame.origin.y+10,180,45)];
    UITapGestureRecognizer *singletap1 = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(openSideButton1URL:)];
    [ItemTitleView addSubview:SideButton1];

I am not sure why the count is 8 but there are no data in the array.
I tried to do this to work around but its not working:
if([[delegate.sidebannerDetailsArray objectAtIndex:2]objectForKey:@"bannerImage"] == NULL){
        [SideButton1 sd_setImageWithURL:[NSURL URLWithString:@"https://xxxxx.com//sidebanners/sidebanner3.gif"]];
    }else{
    [SideButton1 sd_setImageWithURL:[NSURL URLWithString:[[delegate.sidebannerDetailsArray objectAtIndex:2]objectForKey:@"bannerImage"]]];
    }

Any Suggestion?


text:
Q: How to Retrieve image from database? In my Database, the images(jpeg,bmp format) are stored in bytea datatype, showing up in binary code in the database. Now I want to retrieve the images from the database. But i could not get the image in the web page. When i retrieve using this code given below, it shows the binary code value.(ie combination of numbers,characters,symbols). My code was
$dbconn = pg_connect("host=localhost user=xxxx password=xxxx dbname=xxxx")
 or die('Could not connect: ' .pg_last_error());

$rs = pg_query($dbconn, "select scan_image from image where cno='4' and imageno='1'");

$image = pg_escape_bytea(pg_fetch_result($rs, 0));

echo $image;

Am i correct with this code? Please help me to find the solution.

A: Before you echo out the image content, you need to set the headers like:
header('Content-type: image/jpeg');

Then you can call your script in an image tag of the page where you want the fetched image to be displayed:
<img src="name_of_your_script.php">

This link will help you: Managing Images With a Web Database Application

A: U can use Blob to retrieve image from database. And to store image u have convert image to byte using filestream.
This link may help you - http://www.itpian.com/Coding/6298-How-to-retrieve-the-image-to-database-coding.aspx


text:
Q: Como mudar a cor do símbolo $ da variável PHP em um tema instalado no VS CODE alguém sabe como modifica a cor daquele símbolo da variável do PHP, o simbolo de dólar($).
 Já procurei e não achei nada a respeito, nem na documentação.

A: Fuçando os package.json de outros temas, acabei descobrindo, segue o código abaixo.
"editor.tokenColorCustomizations": {
    "textMateRules": [
        {
            "name": "Variaveis",
            "scope": "punctuation.definition.variable.php",
            "settings": {
                "foreground": "#ff8a04",
                "fontStyle": "italic bold"
            }
        }
    ]
}


text:
Q: What would be the bottleneck (slowing/blocking operation) of a parallel mymapreduce() implementation ? Why? We are learning about mapreduce in Python and I got this question in the test. I was googling for an hour but did not really succeed.
I am not sure whether I got it correctly:
My insight is that when we launch a pool, mapreduce partition large amount of data and bottleneck could be in reducing all data then. For example, (it was also given as a hint: professor can evaluate tests in parallel but he can't calculate GPA until he finishes the process.
P.S. Sorry if question repeats


text:
Q: is it possible to overwrite a error or success message generated by the magento? Is it possible to overwrite a error/success message generated by the magento system?
For example if we add a product the success message is
"Laptop is added to your cart..!", what if i would like to add my client's name like "Josh you had added Laptop to your cart"
Thanks,
Balan

A: It's easy enough to add your custom message to the stack when an item is added. Add an event listener for checkout_cart_add_product_complete which does this:
public function observeAddToCart($observer) {
    $product = $observer->getEvent()->getProduct(); // you may need to play with this
    $session = Mage::getSingleton("checkout/session")->addSuccess($message);
    $message = Mage::helper("yourmodule")->__('%s, you added %s to your shopping cart.', Mage::helper('core')->htmlEscape($product->getName()));
    $session->addSuccess($message);
}

That leaves the problem of removing the old message. The closest that I see right now is that you can clear all other messages on command by retrieving them. So you could clear the Magento-set message afterwards like so:
Mage::getSingleton("checkout/session")->getMessages(true);

You would need to do this after Magento's message has been added, however. Hope that gives you a start!
Thanks,
Joe

A: I've written a helper function that allows you to search for a specific message with an option to remove if found.  It's a bit disappointing this isn't available in core..
/**
 * Searches messages for @param $string.
 * Will remove the message if $remove is true.
 *
 * @param string $string
 * @param boolean $remove: false
 * @param string $which: core/session
 * @return true|false, found|not found
 * @access public
 */
public function message_search( $string, $remove = false, $which = 'core/session' ) {

  $found = false;

  $messages = Mage::getSingleton( $which )->getMessages();
  foreach( $messages->getItems() as $message )
    if( stristr( $message->getText(), $string ) ) {
      $found = true;
      if( $remove ) $message->setIdentifier( 'this_message_will_be_removed' );
    }

  if( $remove ) $messages->deleteMessageByIdentifier( 'this_message_will_be_removed' );
  return $found;

}


text:
Q: Montmort's card matching problem: Distribution of the number of matching cards?
(Introduction to Probability, Blitzstein and Nwang)
Recall de Montmort's matching problem from Chapter 1: in a deck of n cards labeled 1
  through n, a match occurs when the number on the card matches the card's position in
  the deck. Let X be the number of matching cards. Is X Binomial? Is X Hypergeometric?

Again stuck at a textbook problem that was probability designed for 2 minutes...
It's clearly not binomial, as the 'draws' are not independent, but I can't see why it should be hypergeometric. As I understand it, the story behind the hypergeomtric was that there is a urn with black and white balls, we take a sample of size n without replacement and count the number of white (or black) balls we see. But where are the black and white ball analogues in the card matching problem?
To get the PMF, I would have guess something like
$$
P(X=k) = \frac{\binom{n}{k} !(n-k)}{n!},
$$
where $n!$ is the number of possible card arrangements, $\binom{n}{k}$ the number of possibilities to have $k$ matching cards out of $n$ and the subfactorial $!(n-k)$ the number of possibilities to derange the remaining cards such that there is no additional match.

*

*What is the 'Hypergeometric story' behind the card matching problem?

*How to derive the hypergeometric distribution from the problem?

A: I guess the correct answer is "neither".
Blitzstein discusses the case P(X=1).
The general answer P(X=k) is given here https://probabilityandstats.wordpress.com/2010/05/02/more-about-the-matching-problem/
\begin{aligned}P(X_n=k)&=\displaystyle \binom{n}{k}\displaystyle \biggl(\sum \limits_{i=0}^{n-k} (-1)^{i} \frac{(n-k)!}{i!}\biggr) \frac{1}{n!}\\&=\frac{1}{k!}\sum \limits_{i=0}^{n-k} \frac{(-1)^{i}}{i!}\end{aligned}


text:
Q: Counting X's and O's in a string in Ruby I'm not sure why my code is not working, I think my logic is right?
Have the function ExOh(str) take the str parameter being passed and return the string true if there is an equal number of x's and o's, otherwise return the string false. Only these two letters will be entered in the string, no punctuation or numbers. For example: if str is "xooxxxxooxo" then the output should return false because there are 6 x's and 5 o's.
ExOh(str)
i = 0
length = str.length
count_x = 0
count_o = 0

while i < length
if str[i] == "x"
    count_x += 1
elsif str[i] == "o"
    count_o += 1
end
i+=1
end
    if (count_o == count_x)
        true
    elsif (count_o != count_x)
    false
end
end

A: The problem with your code is the function declaration. Use def ExOh(str) at the start. It may help if you indented also.
def ExOh(str)
  i = 0
  length = str.length
  count_x = 0
  count_o = 0

  while i < length
    if str[i] == "x"
        count_x += 1
    elsif str[i] == "o"
        count_o += 1
    end
    i+=1
  end

  if (count_o == count_x)
    true
  elsif (count_o != count_x)
    false
  end
end

By the way, a simpler solution using the standard library #count https://ruby-doc.org/core-2.2.0/String.html#method-i-count
def ExOh(str)
  str.count('x') == str.count('o')
end


text:
Q: Opening a java JAR file from python I am trying to open a JAR file from python and running into problems. I am using..
import os
os.system(r"X:\file.jar")

it appears to open the window then it shuts right away, I know I am missing a simple command but not sure what it is, thanks for the help

A: Do you want to execute code from .jar, or open it?
If open, then .jar file is the same format as .zip files and you can use zipfile module to manipulate it. Example:
def show_jar_classes(jar_file):
    """prints out .class files from jar_file"""
    zf = zipfile.ZipFile(jar_file, 'r')
    try:
        lst = zf.infolist()
        for zi in lst:
            fn = zi.filename
            if fn.endswith('.class'):
                print(fn)
    finally:
        zf.close()

If you want to execute it then I prefer creating simple batch/shell script which execute java with some parameters like -Xmx and with environment settings required by application.

A: For the previous question, Executing it is easy.
import os
os.system('start X:\file.jar')


text:
Q: Getting Mixlib::ShellOut::ShellCommandFailed I get the following error while starting one of the instances on OpsWorks. Does anyone have any ideas about this error?
This is printed before the official error announcement (based on request by sethvargo):
[2014-08-13T17:27:08+00:00] INFO: Processing directory[/srv/www/instance/shared/cached-copy] action
delete (opsworks_delayed_job::deploy line 48)
[2014-08-13T17:27:08+00:00] INFO: Processing ruby_block[change HOME to /home/deploy for source checkout] action run (opsworks_delayed_job::deploy line 56)
[2014-08-13T17:27:08+00:00] INFO: ruby_block[change HOME to /home/deploy for source checkout] called
[2014-08-13T17:27:08+00:00] INFO: Processing deploy[/srv/www/instance] action deploy (opsworks_delayed_job::deploy line 65)
[2014-08-13T17:27:09+00:00] INFO: deploy[/srv/www/instance] cloning repo git@github.com:xx/xx.git to /srv/www/instance/shared/cached-copy
[2014-08-13T17:27:17+00:00] INFO: deploy[/srv/www/instance] checked out branch: master onto: deploy reference: 714153bbb6a37f0484526cf4da3eda4fcd8df977
[2014-08-13T17:27:17+00:00] INFO: deploy[/srv/www/instance] synchronizing git submodules
[2014-08-13T17:27:17+00:00] INFO: deploy[/srv/www/instance] enabling git submodules
[2014-08-13T17:27:18+00:00] INFO: deploy[/srv/www/instance] set user to deploy
[2014-08-13T17:27:18+00:00] INFO: deploy[/srv/www/instance] set group to www-data
[2014-08-13T17:27:22+00:00] INFO: deploy[/srv/www/instance] copied the cached checkout to /srv/www/instance/releases/20140813172708
[2014-08-13T17:27:23+00:00] INFO: deploy[/srv/www/instance] set user to deploy
[2014-08-13T17:27:23+00:00] INFO: deploy[/srv/www/instance] set group to www-data
[2014-08-13T17:27:23+00:00] INFO: deploy[/srv/www/instance] running callback before_migrate
[2014-08-13T17:27:23+00:00] INFO: deploy[/srv/www/instance] created directories before symlinking: tmp,public,config
[2014-08-13T17:27:23+00:00] INFO: deploy[/srv/www/instance] linked shared paths into current release: system => public/system, pids => tmp/pids, log => log
[2014-08-13T17:27:23+00:00] INFO: deploy[/srv/www/instance] made pre-migration symlinks
[2014-08-13T17:27:24+00:00] INFO: deploy[/srv/www/instance] set user to deploy
[2014-08-13T17:27:24+00:00] INFO: deploy[/srv/www/instance] set group to www-data
[2014-08-13T17:27:24+00:00] INFO: Gemfile detected. Running bundle install.
[2014-08-13T17:27:24+00:00] INFO: sudo su - deploy -c 'cd /srv/www/instance/releases/20140813172708 && /usr/local/bin/bundle install --path /home/deploy/.bundler/instance --without=test development'

Here is the error:
================================================================================
Error executing action `deploy` on resource 'deploy[/srv/www/instance]'
================================================================================

Mixlib::ShellOut::ShellCommandFailed
------------------------------------
Expected process to exit with [0], but received '127'

Cookbook Trace:
Cookbook Trace:
---------------
/var/lib/aws/opsworks/cache.stage2/cookbooks/opsworks_commons/libraries/shellout.rb:8:in `shellout'
/var/lib/aws/opsworks/cache.stage2/cookbooks/rails/libraries/rails_configuration.rb:41:in `bundle'
/var/lib/aws/opsworks/cache.stage2/cookbooks/deploy/definitions/opsworks_deploy.rb:103:in `block (3 levels) in from_file'

Resource declaration is:
Resource Declaration:
---------------------
# In /var/lib/aws/opsworks/cache.stage2/cookbooks/deploy/definitions/opsworks_deploy.rb

65:     deploy deploy[:deploy_to] do
66:       provider Chef::Provider::Deploy.const_get(deploy[:chef_provider])
67:       keep_releases deploy[:keep_releases]
68:       repository deploy[:scm][:repository]
69:       user deploy[:user]
70:       group deploy[:group]
71:       revision deploy[:scm][:revision]
72:       migrate deploy[:migrate]
73:       migration_command deploy[:migrate_command]
74:       environment deploy[:environment].to_hash
75:       create_dirs_before_symlink( deploy[:create_dirs_before_symlink] )
76:       symlink_before_migrate( deploy[:symlink_before_migrate] )
77:       action deploy[:action]
78:
79:       if deploy[:application_type] == 'rails'
80:         restart_command "sleep #{deploy[:sleep_before_restart]} && #{node[:opsworks][:rails_stack][:restart_command]}"
81:       end
82:

A: With credit to Seth Vargo, the problem was that the bundler gem was not being installed by OpsWorks. The Chef version is 11.10. We had to add the bundler gem manually to the default Chef setup file.

A: Faced the same issue while booting an instance under Opsworks.
After debugging, found the reason for the issue was: The Chef version wasn't mentioned anywhere in Stack or Layer settings. Thus, while running the recipes, some default version of chef was being picked up, which did not have bundler installed on it by default. So, when the recipe was trying to run "run bundle install" , it was exiting with an error.
Simple solution is to explicitly add the chef version along other settings(if any) as below under stack or layer settings:
{

 <other settings>

 "opsworks_bundler": {
    "manage_package": "true",
    "version": "1.16.3"
  }
 }


text:
Q: Capturing checkbox values to table I'm trying to create a form that will capture input, select and checkbox values and post them to a table. Everything seems to be working fine, with the exception of the checkboxes. What am I doing wrong?
https://jsfiddle.net/mujaji/uvkzmyox/8/
var app = angular.module("myapp", []);
app.controller("ListController", ['$scope', function($scope) {
    $scope.jobtypes = ['accountant', 'janitor', 'ceo', 'receptionist'];
    $scope.hobbies = [{name: "long walks on the beach", id: "1", isChecked: false},{name: "eating cheese", id: "2", isChecked: false},{name: "writing haikus", id: "3", isChecked: false},{name: "looking for bigfoot", id: "4", isChecked: false},{name: "watching police academy", id: "5", isChecked: false}];
$scope.personalDetails = [
    {
        'fname':'Muhammed',
        'lname':'Shanid',
        'jobtype': 'ceo',
        'email':'shanid@shanid.com',
        'active': true,
        'hobbies': [{name: "long walks on the beach", id: "1"},{name: "watching police academy", id: "5"}]
    },
    {
        'fname':'John',
        'lname':'Abraham',
        'jobtype': 'accountant',
        'email':'john@john.com',
        'active': true,
        'hobbies': [{name: "writing haikus", id: "3"},{name: "looking for bigfoot", id: "4"}]
    },
    {
        'fname':'Roy',
        'lname':'Mathew',
        'jobtype': 'janitor',
        'email':'roy@roy.com',
        'active': false,
        'hobbies': [{name: "eating cheese", id: "2"}]
    }];

    $scope.addNew = function(personalDetails){
        $scope.personalDetails.push({
            'fname': personalDetails.fname,
            'lname': personalDetails.lname,
            'email': personalDetails.email,
            'jobtype': personalDetails.jobtype,
        });
        $scope.PD = {};
    };

    $scope.remove = function(){
        var newDataList=[];
        $scope.selectedAll = false;
        angular.forEach($scope.personalDetails, function(selected){
            if(!selected.selected){
                newDataList.push(selected);
            }
        });
        $scope.personalDetails = newDataList;
    };

    $scope.checkAll = function () {
        if (!$scope.selectedAll) {
            $scope.selectedAll = true;
        } else {
            $scope.selectedAll = false;
        }
        angular.forEach($scope.personalDetails, function (personalDetails) {
            personalDetails.selected = $scope.selectedAll;
        });
    };

}]);

A: The problem your facing is caused by the fact that hobbies and their checked state is outside the scope of your addNew(personalDetails) function.
Although not ideal for angular, something like this would work:
$scope.addNew = function(personalDetails) {
    //get all checked hobbies
    let selectedHobbies = [];
    $scope.hobbies.forEach(function(hobby) {
        if (hobby.isChecked) selectedHobbies.push(hobby);
    });

        $scope.personalDetails.push({
            'fname': personalDetails.fname,
            'lname': personalDetails.lname,
            'email': personalDetails.email,
            'jobtype': personalDetails.jobtype,
            'hobbies': selectedHobbies
        });
        $scope.PD = {};
    };

EDIT
The answer above is really a pure javascript approach to filtering by selected hobbies.  A more 'angular' approach would be to break your filter logic out into its own function so that you're not mixing concerns.  For example:
Add the 'filterFilter' dependency to your controller:
app.controller("ListController", ['$scope','filterFilter',
    function($scope, filterFilter) { ... }

then in your controller, define an array to hold your selected hobbies and add a filter helper to filter by isChecked:
$scope.hobbiesSelection = [];
$scope.selectedHobbies = function selectedHobbies() {
    return filterFilter($scope.hobbies, { selected: true });
};

place a watch on the hobbies object to watch for changes to selected hobbies:
$scope.$watch('hobbies|filter:{isChecked: true}', function (hobbies) {
    $scope.hobbiesSelection = hobbies;
}, true);

and finally, you can update your addNew() method to simply be:
$scope.addNew = function(personalDetails){
    $scope.personalDetails.push({
        'fname': personalDetails.fname,
        'lname': personalDetails.lname,
        'email': personalDetails.email,
        'jobtype': personalDetails.jobtype,
        'hobbies': $scope.selectedHobbies
    });
    $scope.PD = {};
};

So while there is a bit more code (and complexity) there for this example, you are separating the logic from the data a bit better.  There is working example here: https://jsfiddle.net/mt0tvkwm/


text:
Q: How to encircle two neighbors node using forest? I fail to encircle two node
\documentclass{standalone}
\usepackage[utf8]{inputenc} %unicode support
\usepackage{lmodern}
\usepackage{tikz}
\usetikzlibrary{fit}

\usepackage{forest}
\usetikzlibrary{arrows.meta, angles}

\begin{document}
    \forestset{
        circ/.style={
            label={[circle, draw, anchor=south]south:#1}
        }
    }
    \begin{forest}
      for tree={
        edge={-},
        l sep+=7.5pt
      },
        [Foo
            [Bar1, circ=T, name=b1]
            [Bar2, circ=F, name=b2]
            [qux1, circ=T, name=q1]
        ]
    \node[draw,rounded rectangle,fit={ (b1) (b2) }, yshift=-0.5cm] {};
    \end{forest}
\end{document}

I would like to encircle Bar1, Bar2 and their corresponding circle
Thanks for your help

A: You could do something like this, although it is rather awkward and not very intuitive because of the difficulties involved in getting things executed in the correct order when they are specified at TikZ options (either implicitly or explicitly). So it is rather messy.
Probably I'm missing a much more obvious strategy. (I think I must be missing a much more obvious strategy!)
\documentclass[border=10pt,tikz,multi]{standalone}
\usepackage{forest}
\usetikzlibrary{fit}
\begin{document}
\forestset{%
  declare count register={clabel},
  clabel'=0,
  circ/.style={%
    clabel'+=1,
    tikz+/.wrap pgfmath arg={%
      \node (label ##1) [circle, draw, anchor=north] at (.south) {#1};
    }{clabel()},
  },
}
\begin{forest}
  for tree={%
    l sep+=7.5pt,
    delay={%
      content/.wrap value={\strut #1},
    }
  },
  [Foo
    [Bar1, circ=T, name=b1]
    [Bar2, circ=F, name=b2]
    [qux1, circ=T, name=q1, tikz+={\node[draw, rounded rectangle, fit=(b1) (b2) (label 1) (label 2), inner xsep=-5pt, inner ysep=1pt] {};}]
  ]
\end{forest}
\end{document}


text:
Q: How to print multiple pages in c#? Using datagridview There are no issues or errors in the code, but I am trying to print a sales report that contains a lot of data. I only want to print what's displayed on the Datagridview because I have filters for date, month, and year. can someone please help me?
This is what I have:
 private void printBtn_Click(object sender, EventArgs e)
        {
            printDialog1.Document = printDocument1;
            DialogResult result = printDialog1.ShowDialog();
            if (result == DialogResult.OK)
            {
                printDocument1.DefaultPageSettings.Landscape = true;
                printDocument1.Print();
            }
        }

        private void printDocument1_PrintPage(object sender, System.Drawing.Printing.PrintPageEventArgs e)
        {
            Graphics graphics = e.Graphics;
            Font font = new Font("Courier New", 14);
            //float fontweight = font.GetHeight();
            float pageWidth = e.PageSettings.PrintableArea.Width;
            float pageHeight = e.PageSettings.PrintableArea.Height;

            float currentY = 60;// declare  one variable for height measurement
            e.Graphics.DrawString("SONNY INN", font, Brushes.Black, 40, currentY);//this will print one heading/title in every page of the document
            currentY += 15;
            e.Graphics.DrawString("\r\nPhilippines\r\nContact No: 0945 678 8057\r\n\r\n\r\n", font, Brushes.Black, 40, currentY);
            currentY += 15;
            string top = "Date: " + DateTime.Now.ToString("MM/dd/yyyy hh:mm tt");
            graphics.DrawString(top + "\r\nLegend : RA - Room Accomodation\r\nAO - Add-Ons", font, new SolidBrush(Color.Black), 600, 60);
            currentY += 60;
            e.Graphics.DrawString("------------------------------------------------------------------------------------", font, Brushes.Black, 40, currentY);
            currentY += 30;
            e.Graphics.DrawString("Transaction Date\tGuest\t\t\t\tRoom No.\t\tDetails\t\tAmount\t\t\tBalance Due", new Font("Courier New", 10), Brushes.Black, 50, currentY);
            currentY += 30;
            e.Graphics.DrawString("------------------------------------------------------------------------------------", font, new SolidBrush(Color.Black), 40, 750);
            e.Graphics.DrawString("TOTAL AMOUNT: PHP  \t\t\t\t\t\t" + totamtxtbox.Text, font, new SolidBrush(Color.Black), 50, 780);
            e.Graphics.DrawString("TOTAL BALANCE: PHP  \t\t\t\t\t" + balduetxt.Text, font, new SolidBrush(Color.Black), 50, 800);
            e.Graphics.DrawString("GRAND TOTAL: PHP  \t\t\t\t\t\t" + gtotaltxt.Text, font, new SolidBrush(Color.Black), 50, 820);

            int offsetY = 40;
            int y = 0;
            int cnt = reportgrid.Rows.Count;

                foreach (DataGridViewRow dr in reportgrid.Rows)
                {
                    string transd = Convert.ToString(dr.Cells["Transaction Date"].Value);
                    string guest = Convert.ToString(dr.Cells["Guest"].Value);
                    string roomno = Convert.ToString(dr.Cells["Room No."].Value);
                    string deets = Convert.ToString(dr.Cells["Details"].Value);
                    string amount = Convert.ToString(dr.Cells["Amount"].Value);
                    string baldue = Convert.ToString(dr.Cells["Balance Due"].Value);
                    graphics.DrawString(transd + "\t" + guest + "\t\t\t" + roomno + "\t\t\t" + deets + "\t\t\t" + amount + "\t\t\t" + baldue, new Font("Courier New", 10), new SolidBrush(Color.Red), 50, currentY);
                    currentY += 20;
                }

            MessageBox.Show("Printing in progress.", "Print Sales Report", MessageBoxButtons.OK, MessageBoxIcon.Information);

}

A: It's not the easiest thing to print multiple pages from a DataGridView so I recommend you to use one of the existing code samples. Here's couple good ones which are easy to use and can print multiple pages:
Another DataGridView Printer
DataGridView Print/Print Preview Solution - Part I
The DataGridViewPrinter Class


text:
Q: Unit tests for deep cloning Let's say I have a complex .NET class, with lots of arrays and other class object members.  I need to be able to generate a deep clone of this object - so I write a Clone() method, and implement it with a simple BinaryFormatter serialize/deserialize - or perhaps I do the deep clone using some other technique which is more error prone and I'd like to make sure is tested.
OK, so now (ok, I should have done it first) I'd like write tests which cover the cloning.  All the members of the class are private, and my architecture is so good (!) that I haven't needed to write hundreds of public properties or other accessors.  The class isn't IComparable or IEquatable, because that's not needed by the application.  My unit tests are in a separate assembly to the production code.
What approaches do people take to testing that the cloned object is a good copy?   Do you write (or rewrite once you discover the need for the clone) all your unit tests for the class so that they can be invoked with either a 'virgin' object or with a clone of it?   How would you test if part of the cloning wasn't deep enough - as this is just the kind of problem which can give hideous-to-find bugs later?

A: You method of testing will depend on the type of solution you come up with.  If you write some custom cloning code and have to manually implement that in each cloneable type then you should really test the cloning of each one of those types.  Alternatively, if you decide to go a more generic route (where the aforementioned reflection would likely fit in), your tests would only need to test the specific scenarios that you cloning system will have to deal with.
To answer your specific questions:

Do you write (or rewrite once you discover the need for the clone) all your unit tests for the class so that they can be invoked with either a 'virgin' object or with a clone of it?

You should have tests for all the methods that can be performed on both the original and cloned objects.  Note that it should be pretty easy to set up a simple test design to support this without manually updating the logic for each test.

How would you test if part of the cloning wasn't deep enough - as this is just the kind of problem which can give hideous-to-find bugs later?

It depends on the cloning method you choose.  If you have to manually update the cloneable types then you should test that each type is cloning all (and only) the members you expect.  Whereas, if you are testing a cloning framework I would create some test cloneable types to test each scenario you need to support.

A: There's a really obvious solution that doesn't take nearly as much work:

*

*Serialize the object into a binary format.

*Clone the object.

*Serialize the clone into a binary format.

*Compare the bytes.

Assuming that serialization works - and it better because you are using it to clone - this should be easy to maintain.  In fact, it will be encapsulated from changes to the structure of your class completely.

A: I'd just write a single test to determine if the clone was correct or not.  If the class isn't sealed, you can create a harness for it by extending it, and then exposing all your internals within the child class.  Alternatively, you could use reflection (yech), or use MSTest's Accessor generators.
You need to clone your object and then go through every single property and variable that your object has and determine if it was copied correctly or cloned correctly.

A: I like to write unit tests that use one of the builtin serializers on the original and the cloned object and then check the serialized representations for equality (for a binary formatter, I can just compare the byte arrays).  This works great in cases where the object is still serializable, and I'm only changing to a custom deep clone for perf reasons.
Furthermore, I like to add a debug mode check to all of my Clone implementations using something like this
[Conditional("DEBUG")]
public static void DebugAssertValueEquality<T>(T current, T other, bool expected,
                                               params string[] ignoredFields) {
    if (null == current)
    { throw new ArgumentNullException("current"); }
    if (null == ignoredFields)
    { ignoredFields = new string[] { }; }

    FieldInfo lastField = null;
    bool test;
    if (object.ReferenceEquals(other, null))
    { Debug.Assert(false == expected, "The other object was null"); return; }
    test = true;
    foreach (FieldInfo fi in current.GetType().GetFields(BindingFlags.Instance)) {
        if (test = false) { break; }
        if (0 <= Array.IndexOf<string>(ignoredFields, fi.Name))
        { continue; }
        lastField = fi;
        object leftValue = fi.GetValue(current);
        object rightValue = fi.GetValue(other);
        if (object.ReferenceEquals(null, leftValue)) {
            if (!object.ReferenceEquals(null, rightValue))
            { test = false; }
        }
        else if (object.ReferenceEquals(null, rightValue))
        { test = false; }
        else {
            if (!leftValue.Equals(rightValue))
            { test = false; }
        }
    }
    Debug.Assert(test == expected, string.Format("field: {0}", lastField));
}

This method relies on an accurate implementation of Equals on any nested members, but in my case anything that is cloneable is also equatable

A: I would usually implement Equals() for comparing the two objects in depth. You might not need it in your production code but it might still come in handy later and the test code is much cleaner.

A: Here is a sample of how I implemented this a while back, although this will need to be tailored to the scenario. In this case we had a nasty object chain that could easily change and the clone was used as a very critical prototype implementation and so I had to patch (hack) this test together.
public static class TestDeepClone
    {
        private static readonly List<long> objectIDs = new List<long>();
        private static readonly ObjectIDGenerator objectIdGenerator = new ObjectIDGenerator();

        public static bool DefaultCloneExclusionsCheck(Object obj)
        {
            return
                obj is ValueType ||
                obj is string ||
                obj is Delegate ||
                obj is IEnumerable;
        }

        /// <summary>
        /// Executes various assertions to ensure the validity of a deep copy for any object including its compositions
        /// </summary>
        /// <param name="original">The original object</param>
        /// <param name="copy">The cloned object</param>
        /// <param name="checkExclude">A predicate for any exclusions to be done, i.e not to expect IPolicy items to be cloned</param>
        public static void AssertDeepClone(this Object original, Object copy, Predicate<object> checkExclude)
        {
            bool isKnown;
            if (original == null) return;
            if (copy == null) Assert.Fail("Copy is null while original is not", original, copy);

            var id = objectIdGenerator.GetId(original, out isKnown); //Avoid checking the same object more than once
            if (!objectIDs.Contains(id))
            {
                objectIDs.Add(id);
            }
            else
            {
                return;
            }

            if (!checkExclude(original))
            {
                Assert.That(ReferenceEquals(original, copy) == false);
            }

            Type type = original.GetType();
            PropertyInfo[] propertyInfos = type.GetProperties(BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Public);
            FieldInfo[] fieldInfos = type.GetFields(BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Public);

            foreach (PropertyInfo memberInfo in propertyInfos)
            {
                var getmethod = memberInfo.GetGetMethod();
                if (getmethod == null) continue;
                var originalValue = getmethod.Invoke(original, new object[] { });
                var copyValue = getmethod.Invoke(copy, new object[] { });
                if (originalValue == null) continue;
                if (!checkExclude(originalValue))
                {
                    Assert.That(ReferenceEquals(originalValue, copyValue) == false);
                }

                if (originalValue is IEnumerable && !(originalValue is string))
                {
                    var originalValueEnumerable = originalValue as IEnumerable;
                    var copyValueEnumerable = copyValue as IEnumerable;
                    if (copyValueEnumerable == null) Assert.Fail("Copy is null while original is not", new[] { original, copy });
                    int count = 0;
                    List<object> items = copyValueEnumerable.Cast<object>().ToList();
                    foreach (object o in originalValueEnumerable)
                    {
                        AssertDeepClone(o, items[count], checkExclude);
                        count++;
                    }
                }
                else
                {
                    //Recurse over reference types to check deep clone success
                    if (!checkExclude(originalValue))
                    {
                        AssertDeepClone(originalValue, copyValue, checkExclude);
                    }

                    if (originalValue is ValueType && !(originalValue is Guid))
                    {
                        //check value of non reference type
                        Assert.That(originalValue.Equals(copyValue));
                    }
                }

            }

            foreach (FieldInfo fieldInfo in fieldInfos)
            {
                var originalValue = fieldInfo.GetValue(original);
                var copyValue = fieldInfo.GetValue(copy);
                if (originalValue == null) continue;
                if (!checkExclude(originalValue))
                {
                    Assert.That(ReferenceEquals(originalValue, copyValue) == false);
                }

                if (originalValue is IEnumerable && !(originalValue is string))
                {
                    var originalValueEnumerable = originalValue as IEnumerable;
                    var copyValueEnumerable = copyValue as IEnumerable;
                    if (copyValueEnumerable == null) Assert.Fail("Copy is null while original is not", new[] { original, copy });
                    int count = 0;
                    List<object> items = copyValueEnumerable.Cast<object>().ToList();
                    foreach (object o in originalValueEnumerable)
                    {
                        AssertDeepClone(o, items[count], checkExclude);
                        count++;
                    }
                }
                else
                {
                    //Recurse over reference types to check deep clone success
                    if (!checkExclude(originalValue))
                    {
                        AssertDeepClone(originalValue, copyValue, checkExclude);
                    }
                    if (originalValue is ValueType && !(originalValue is Guid))
                    {
                        //check value of non reference type
                        Assert.That(originalValue.Equals(copyValue));
                    }
                }
            }
        }
    }


text:
Q: FirebaseRecycleAdapter with Glide(or Picasso) load image in wrong place I use FirebaseRecycleAdapter to load chat data from Firebase RealtimeDatabase.
I want to show the message on two way, so the left image different the right image.
But the image sometimes misplace like the picture.

Here is my code:
mFirebaseAdapter = new FirebaseRecyclerAdapter<Message, MessageViewHolder>(
                Message.class,
                R.layout.item_message_onetoone,
                MessageViewHolder.class,
                databaseReference.child(Constant.CHILD_CHATONETOONE).child(myUid).child(clientUid)) {

            @Override
            protected void populateViewHolder(MessageViewHolder viewHolder, Message message, int position) {
                String senderUid= message.getSenderUid();

                LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(RecyclerView.LayoutParams.WRAP_CONTENT, ActionBar.LayoutParams.WRAP_CONTENT);
                lp.leftMargin= 10;
                lp.rightMargin= 10;

                viewHolder.messageTextView.setText(message.getMessage());
                if (senderUid.equals(myUid)){
                    lp.gravity= Gravity.RIGHT;
                    viewHolder.linearLayout.setLayoutParams(lp);

                    Glide.with(OneToOneConversationActivity.this).load(myPhotoURL).into(viewHolder.messengerImageView);
                    viewHolder.messengerTextView.setText(myName);

                }
                else if(senderUid.equals(clientUid)){
                    lp.gravity= Gravity.LEFT;
                    viewHolder.linearLayout.setLayoutParams(lp);

                    viewHolder.messengerTextView.setText(clientName);

                }

            }
        };

MessageViewHolder class:
public static class MessageViewHolder extends RecyclerView.ViewHolder {
        public TextView messageTextView;
        public TextView messengerTextView;
        public CircleImageView messengerImageView;
        public LinearLayout linearLayout;

        public MessageViewHolder(View v) {
            super(v);
            messageTextView = (TextView) itemView.findViewById(R.id.messageTextView);
            messengerTextView = (TextView) itemView.findViewById(R.id.messengerTextView);
            messengerImageView = (CircleImageView) itemView.findViewById(R.id.messengerImageView);
            linearLayout= (LinearLayout) itemView.findViewById(R.id.llOneToOneChat);
        }
    }

The linearlayout and textViews works fine exept CircleImageView. It seems like context: OneToOneChatActivity.this when i use code : Glide.with(....) is wrong, but I cant figure out solution.
How can I make it work property?

A: I found my problem. There is two way to solve the problem

*

*One:
Use solution in this post: Android, Glide shows wrong image for about one second
so in this post, in "else" case, you can set a transparent color to imageView to avoid the problem

*

*Two:
You can use two library to load these images, for example: Glide and Piccaso.


text:
Q: What is the difference between packages.dhall and spago.dhall files? spago docs state:

packages.dhall: this file is meant to contain the totality of the packages available to your project (that is, any package you might want to import).
In practice it pulls in the official package-set as a base, and you are then able to add any package that might not be in the package set, or override existing ones.
spago.dhall: this is your project configuration. It includes the above package set, the list of your dependencies, the source paths that will be used to build, and any other project-wide setting that spago will use. (my emphasis)

Why do both files have the notion/concept of dependencies? Example: packages.dhall and spago.dhall from the ebook.
spago.dhall dependencies can be found in the project .spago folder. But I cannot locate the ones from packages.dhall. Others are common like aff. A different perspective:

[...] what you choose is a "snapshot", which is a collection of certain versions of all available packages that are guaranteed to compile and work together.
The snapshot is defined in your packages.dhall file, and then you specify the specific packages that you want to use in spago.dhall. The version for each package comes from the snapshot.

That sounds, like spago.dhall is an excerpt of packages from packages.dhall.The note about versions is a bit confusing, as there aren't version specifiers in both files.
So, why two files? What is the mental model for someone coming from npm ecosystem with package.json (which might be present as well)?

A: The mental model is that of a Haskell developer, which is what most PureScript developers used to be, and many still are. :-)
But more seriously, the mental model is having multiple "projects" in a "solution", which is the model of Haskell's de-facto standard package manager, Stack. In Haskell this situation is very common, in PureScript - much less so, but still not unheard of.
In a situation like this it's usually beneficial to have all the "projects" to share a common set of packages, which are all guaranteed to be "compatible" with each other, which simply means that they all compile together and their tests pass. In Haskell Stack this common set of packages is defined in stack.yaml. In Spago - it's packages.dhall.
Once you have this common base set of packages established, each individual project may pick and choose the particular packages that it uses. In Haskell Stack this is specified either in package.yaml or in <project-name>.cabal (the latter being phased out). In Spago - it's spago.dhall.
But of course, when you have just the one project, having both packages.dhall to establish the "base set" of packages and then, separately, spago.dhall to pick some particular packages from that set - may seem a bit redundant. And indeed, it's possible to do without the packages.dhall file completely: just specify the URL of the package set directly in spago.dhall, as the value of the packages property:
{ name = "my-project"
, dependencies = [ ... ]
, license = "..."
, packages = https://github.com/purescript/package-sets/releases/download/psc-0.13.8-20201223/packages.dhall
, repository = "..."
, sources = [ "src/**/*.purs" ]
}

This will work, but there is one important caveat: hashing. When the URL of the package set is specified in packages.dhall, running spago install will compute a hash of that package set and put it inside packages.dhall, right next to the URL. Here's what mine looks like:
let upstream =
      https://github.com/purescript/package-sets/releases/download/psc-0.13.8-20201222/packages.dhall sha256:620d0e4090cf1216b3bcbe7dd070b981a9f5578c38e810bbd71ece1794bfe13b

Then, if maintainers of the package set become evil and change the contents of that file, Spago will be able to notice that, recompute the hash, and reinstall the packages.
If you put the URL directly in spago.dhall, this doesn't happen, and you're left with the slight possibility of your dependencies getting out of sync.

Now to address this point separately:

Why do both files have the notion/concept of dependencies? Example: packages.dhall and spago.dhall from the ebook.

If you look closer at the examples you linked, you'll see that these are not the same dependencies. The ones in spago.dhall are dependencies of your package - the one where spago.dhall lives.
But dependencies in packages.dhall are dependencies of the test-unit package, which is being added to the package set as an override, presumably because we want to use the special version stackless-default, which isn't present in the official package set. When you override a package like this, you can override any fields specified in that package's own spago.dhall, and in this case we're overriding dependencies, repo, and version.


text:
Q: Setting option SO_SETFIB on boost sockets I do not see any option to set SO_SETFIB on boost sockets.  Anyone has any idea or point me in right direction how to achieve that?

A: If Boost.Asio does not support a socket option, then one can create models of either GettableSocketOption and/or SettableSocketOption type requirements to meet ones needs.
The  socket::set_option() accepts an object that models the SettableSocketOption type requirement.  The SettableSocketOption type requirement documents that models must provide a few functions that return values suitable to be passed to POSIX setsockopt():
class option
{
  int level(Protocol) const;       // The 'level' argument.
  int name(Protocol) const;        // The 'name' argument.
  const int* data(Protocol) const  // The 'option_value' argument.
  std::size_t size(Protocol) const // The 'option_len' argument.
};

One can think of socket.set_option(option) as if it was:
setsocketopt(socket.native_handle(), option.level(protocol),
             option.name(protocol), option.data(protocol),
             option.size(protocol));

The Protocol passed to the functions is a model of the Protocol type requirement.

Here is a set_fib class that is a model of SettableSocketOption:
class set_fib
{
public:
  // Construct option with specific value.
  explicit set_fib(int value)
    : value_(value)
  {}

  // Get the level of the socket option.
  template <typename Protocol>
  int level(const Protocol&) const { return SOL_SOCKET; }

  // Get the name of the socket option.
  template <typename Protocol>
  int name(const Protocol&) const { return SO_SETFIB; }

  // Get the address of the option value.
  template <typename Protocol>
  const int* data(const Protocol&) const { return &value_; }

  // Get the size of the option.
  template <typename Protocol>
  std::size_t size(const Protocol&) const { return sizeof(value_);  }

private:
  int value_;
};

Usage:
boost::asio::ip::tcp::socket socket(io_service);
// ...
set_fib option(42);
socket.set_option(option);

A: You would use the boost::asio::detail::socket_option::integer socket option helper template:
typedef boost::asio::detail::socket_option::integer<SOL_SOCKET, SO_SETFIB> set_fib;

// ...
sock.set_option(set_fib(42));


text:
Q: Testing with google and cmake Colleagues !
I try to write simple application with google test and cmake. I do as written in documentation. My CMakeLists.txt is
cmake_minimum_required (VERSION 2.6)
project (foo_d-google-test)
add_executable (foo_d-google-test main.cpp)
enable_testing()
find_package(GTest REQUIRED)
if (NOT GTest_FOUND)
    message(FATAL_ERROR "Cannot find Google Test Framework!")
endif()

and main.cpp is
#include <math.h>
#include <gtest/gtest.h>

TEST (SquareRootTest, PositiveNos) {
    EXPECT_EQ (18.0, sqrt (324.0));
    EXPECT_EQ (25.4, sqrt (645.16));
    EXPECT_EQ (50.3321, sqrt (2533.310224));
}

TEST (SquareRootTest, ZeroAndNegativeNos) {
    ASSERT_EQ (0.0, sqrt (0.0));
    ASSERT_EQ (-1, sqrt (-22.0));
 }

 int main(int argc, char* argv[])
 {
    testing::InitGoogleTest(&argc, argv);
    int ret = RUN_ALL_TESTS();
    return ret;
 }

And I receive an error

CMake Error at /usr/share/cmake-3.7/Modules/FindPackageHandleStandardArgs.cmake:138 (message):
    Could NOT find GTest (missing: GTEST_LIBRARY GTEST_MAIN_LIBRARY)

My platform is Debian Linux 9, and library googletest was installed. Any idea ?
Thanks a lot.


text:
Q: What are the factors for Bad Ethernet connection? I just made someone install RJ45 from my Living Room to my Office on two floors above the current one. Cable is Cat6 for what is worth.
Thing is that when I put cables on the two ends (one to the router and another one to another device), the light on the router lights up but a lot often it comes down and keeps off.
I tried several cables in both ends and even tried to connect the computer directly to it but it doesn't get IP.
I read the specs on the Cat 6 and even to get 10GBASE-T I need 33 meters (or 108ft) at the worst conditions (which I don't think I am) and I don't think I'm near that, yet, it doesn't work.
For what is worth, the router does work. I'm able to get medium strength wifi signal from it, and directly connecting to the router itself (without the new cable that goes through the walls) works perfectly. Things just doesn't show up on the DHCP table of the router when connected with this new cable.
Main reason for asking this is cause I can see a light turning on (though it's not 100% consistent) which means network activity going on.
So, here's my question:
What are the factors for a lousy connection? What should I be looking for in order to fix this?
Thanks


text:
Q: Set Tkinter entry with tuple I have a askopenfilenames() function which returns a tuple and puts it in a variable called files.
When I do print files it prints it like so:
('/home/hoeter/PycharmProjects/Renpy/rpatool.py', '/home/hoeter/PycharmProjects/Renpy/unrpa.py', '/home/hoeter/PycharmProjects/Renpy/window.py')

Now what I want it is to put this value in a entry with the , but without the (), I'm trying the following:
files_path.set(files)
entry3 = Entry(f3, width=50, textvariable=files_path)

But in the entry it comes out like:
/home/hoeter/PycharmProjects/Renpy/rpatool.py /home/hoeter/PycharmProjects/Renpy/unrpa.py /home/hoeter/PycharmProjects/Renpy/window.py

However I expected it to come out like it did in the print. Why didn't it?
In short, my desired output in the entry is:
'/home/hoeter/PycharmProjects/Renpy/rpatool.py', '/home/hoeter/PycharmProjects/Renpy/unrpa.py', '/home/hoeter/PycharmProjects/Renpy/window.py'

My current output in the entry is:
/home/hoeter/PycharmProjects/Renpy/rpatool.py /home/hoeter/PycharmProjects/Renpy/unrpa.py /home/hoeter/PycharmProjects/Renpy/window.py

And what I expect to be in the entry right now, but isn't, is:
('/home/hoeter/PycharmProjects/Renpy/rpatool.py', '/home/hoeter/PycharmProjects/Renpy/unrpa.py', '/home/hoeter/PycharmProjects/Renpy/window.py')

A: Frankly, I'm a little surprised that StringVar.set accepts a tuple.
The simple way to get the string you want is by converting the tuple to a string and slicing it to remove the parentheses:
files_path.set(str(files)[1:-1])

Another way is to use the str.join method, passing it a generator expression which produces the representation of each item in the tuple.
s = ', '.join(repr(u) for u in files)
files_path.set(s)

But there's really no need to do this, since the first version is essentially doing the same thing.
Note that with both versions if any file name contains single-quote chars the representation will be quoted with double-quotes. And if a file name contains both single and double quotes then its representation will be single-quoted and the internal single quotes will be backslash-escaped, like this: \'. But hopefully you won't need to deal with such evil file names. :)

A: Brackets and commas are not part of the string they are just visual part of List.
Do you want something like this?
list_of_string = ('/home/hoeter/PycharmProjects/Renpy/rpatool.py', '/home/hoeter/PycharmProjects/Renpy/unrpa.py',
        '/home/hoeter/PycharmProjects/Renpy/window.py')

output = ""
for string in list_of_string:
    output += "('"+string+"')" + ", "

print(output)

Output:
('/home/hoeter/PycharmProjects/Renpy/rpatool.py'), ('/home/hoeter/PycharmProjects/Renpy/unrpa.py'), ('/home/hoeter/PycharmProjects/Renpy/window.py'),

A: Try this:
from tkinter import *

root = Tk()
entries = []
entries2 = []

#--------------1st row input----------------

for i in range(4):
    entry = IntVar()
    entry.set("")

    en = Entry(root,textvariable=entry)
    en.grid(row=i+1, column=0)

    entries.append(en)

#----------------2nd row output -------------

for i in range(4):
    entry = IntVar()

    en2 = Entry(root,textvariable=entry)
    en2.grid(row=i+1, column=2)

    entries2.append(en2)

def saveData():
    entrylist = []

    for entry in entries:
        getentry = int(entry.get())
        entrylist.append(getentry)

        print(entrylist)

    for entry in entries2:
            for x in entrylist:
                entry.set(x)

button = Button(root, text = "summit", command = saveData).grid(row = 12, column = 0)

root.mainloop()


text:
Q: What is wrong with this call to schtasks on Win 7? I'm trying to run this in a Win 7 Professional admin console:
schtasks /create /tn "Task at 16:40 on 10/27/2012"
    /sc "once" /st "16:40" /sd "10/27/2012"
    /tr "c:\python27\python.exe c:\users\jost\Desktop\executeScript.py"

All referenced files exist. The error message I get is
ERROR: The filename, directory name, or volume label syntax is incorrect.

What is wrong? Running the command directly on the command line works fine.

A: It has nothing to do with your target, it means that schtasks cannot create a task with a given name. That's because task is stored in a filesystem and you cannot use : or / in a file name.
Thank you Microsoft for meaningful error messages! What's interesting, previous (xp) version simply prints:

ERROR: The creation of the scheduled task failed. Reason: The Task
  Name may not contain the characters: <, >, :, /, \,|

What the hell was wrong with that?


text:
Q: invalid composer file installing dependancy I am trying to install a package found here :
https://cartalyst.com/manual/data-grid/3.0
my composer file is as follows :
{
    "name": "laravel/laravel",
    "description": "The Laravel Framework.",
    "keywords": ["framework", "laravel"],
    "license": "MIT",
    "type": "project",
    "require": {
        "laravel/framework": "4.2.*"
,  "barryvdh/laravel-migration-generator": "dev-master", "fzaninotto/faker": "1.2.*@dev", "aws/aws-sdk-php": "2.*", "cartalyst/data-grid": "3.0.*"  },

"repositories": [
    {
        "type": "composer",
        "url": "https://packages.cartalyst.com"
    }
]

    "autoload": {
        "classmap": [
            "app/commands",
            "app/controllers",
            "app/models",
            "app/database/migrations",
            "app/database/seeds",
            "app/tests/TestCase.php"
        ]
    },

    "scripts": {
        "post-install-cmd": [
            "php artisan clear-compiled",
            "php artisan optimize"
        ],
        "post-update-cmd": [
            "php artisan clear-compiled",
            "php artisan optimize"
        ],
        "post-create-project-cmd": [
            "php artisan key:generate"
        ]
    },
    "config": {
        "preferred-install": "dist"
    },
    "minimum-stability": "stable"
}

unfortunately my json is invalid and I am having trouble fixing it I have followed the installation instructions as per the link at the start of the question thanks

A: You need a comma between the repositories array and the autoload object.
...
"repositories": [
    {
        "type": "composer",
        "url": "https://packages.cartalyst.com"
    }
],
"autoload": {
    "classmap": [
        "app/commands",
        "app/controllers",
        "app/models",
        "app/database/migrations",
        "app/database/seeds",
        "app/tests/TestCase.php"
    ]
},
...


text:
Q: Windows server and telnet, what can you do? On a Windows Server 2008, can you even telnet into the server? (not remote desktop, but via the command line)
If yes, is there much control really?
How do people automate if you can't telnet? (assuming you can't)

A: There is basically nothing you cannot configure using the command line in Windows these days. There's netsh to manage network interfaces and the firewall for instance, and appcmd to handle an IIS instance.
Using Powershell (which currently excludes Server Core) even more options are available like an Add-Computer cmdlet for joining a machine to the domain with additional options over the old netdom.
If you stumble upon something that cannot be done from the command line, there's bound to be a 3rd party tool to do it - or you could roll your own given the knowledge of what to actually poke at on the system (generally application-specific files or registry settings).
WinRM
Since Server 2008/Vista you have Windows Remote Management which is Microsofts implementation of the open web service standard WS-Management which uses SOAP and thus can be protected with TLS/SSL and a number of authentication options.
CMD and Powershell can invoke WinRM to execute stuff on remote machines so it's easily scriptable. As far as I recall, WinRM can be installed on XP and 2003 machines as well - and it can be used to manage other platforms which implements WS-Management, like Linux running OpenWSMan.
Telnet
Not enabled by default (not even the client, thankfully!) but can be if you want to.
3rd party tools
Seems one of the more popular options - tools like psexec or 3rd party SSH servers are all available if that floats your boat.
Management suits
Any decent management solution will let you handle thousands of Windows hosts with a few clicks in a comfortable client tool. Microsoft System Center series is probably the most well-known but the other big ones I hope someone can edit in here.
UI Tools for adhoc administration
Most if not all administrative tools you find on a Windows machine can connect remotely to another Windows host for ad-hoc management. If you install the RSAT features on a Vista or Windows 7 desktop you will get most of the standard UI tools to manage AD, infrastructure, replication, Hyper-V and so on with no need whatsoever to open an interactive session with the servers in question.
Interactive desktop
Using Remote Desktop you get an interactive session to the server which can be configured to be as secure as any SSH solution or whatnot. In my opinion, using Remote Desktop to a Windows Server is out-of-the-ordinary. If you must do that, then there's something wrong (and yes, things sometimes wrong so nothing wrong with that, pun not intended) that you're fixing while doing it.
UI tools and interactive desktop could be crudely automated using AutoIT or something similar - if you really want to push it into the absurd ^^

A: The fallacy in this question lies in assuming that some form of remote command-line is required to manage or automate tasks on a Windows server (possibly as a result of coming from a Unix background?)
Even in the old days of 2000 Server and Server 2003 virtually every admin tool or scripting interface provided by Microsoft was capable of connecting to a remote machine as well as to the local machine.  You going literally almost manage an entire network without ever once actually "being on" a server.  This has always been building up and improving over the years - and aside from a brief disconnect where the XP client was available before the server admin tools that worked with it were - serves to demonstrate the real power and flexibility of a true native Windows setup.

A: I'll start be saying that Telnet should not be enabled. I can't understand why it's even installed, as it was designed for a closed environment where security was not an issue and has no reason to exist in today's world.
There are many ways to remotely manage a Windows server from the command line. There is WMI for starters. There are also tools such as the pstools suite, most notably psexec.
Perhaps the simplest way to get a secure command line on a remote server is to install and use one of the SSH servers. This will give you a command line exactly like opening a "DOS" prompt on the machine itself. You may however need to fiddle with the terminal emulation mode of the client (e.g. putty) to get it to look right, as they are generally intended to connect to a *nix host.

A: Windows has an entire suite of tools to remotely administer Windows machines. In addition to the remote administration tools in the admin toolpack, you can use something like psexec or even powershell to issue remote commands.
As for automation, I'd recommend powershell. All of my Windows-admin buddies swear by it.

A: Yes, you can enable telnet server.  See:
http://www.windowsnetworking.com/articles_tutorials/configure-telnet-Server-Windows-Server-2008.html
Windows Server 2008 added support for the "Core" server installations -- which essentially give you little or no GUI for configuring the server, aside from very basic things like setting the IP and adding it to a domain.  To allow those servers to be managed (and also the Full Server 2008 installations), Microsoft provides the Remote Server Administration Tools for Windows 7 which essentially gives you a GUI on your desktop to control most aspects of the server:
http://www.microsoft.com/downloads/details.aspx?FamilyID=7D2F6AD7-656B-4313-A005-4E344E43997D&displaylang=en
As a side note, I am aware of several reputable hosting providers (including Rackspace) that by default support remote administration via a wide-open RDP port.  In my opinion, RDP is no less secure than a wide-open SSH port into a server -- in either case, the traffic is encrypted, but if you have the login/password (assuming you're not using certificates) you can pwn the server.

A: powershell and sysinternals tools are your friends.
mh01 makes a valid point that many of the MMC based tools allow for the attachment of remote machines so they can be administered from the local GUI.    As an old-timer (literally) Im accustomed to the command line, and think that powershell is one of the best tools MSFT has ever built.


text:
Q: TableView, handle clicks error I have an IOS example project which i downloaded from internet. This project is only a tableview filled up with names. When you click on a name a dialog opens. Pretty simple. When i try to move the code over to my "main project" (A TAB-based application) it wont work. I paste the exact same code in the m and h files.
Could it be something in my layout file?
#import "SecondViewController.h"

@implementation TableViewViewController
@synthesize tableViewArray;

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
NSString *message = [NSString stringWithFormat:@"%@",[tableViewArray objectAtIndex:indexPath.row]];
NSString *focus = [NSString stringWithFormat:@"Focus"];
if ([focus isEqualToString:message]) {
    // ...

    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Alert"
                                                    message: message delegate:self cancelButtonTitle:@"Sebastian :)" otherButtonTitles:nil];
    [alert show];
    [alert release];
}

//NSString *message = [NSString stringWithFormat:@"You selected %@",[tableViewArray objectAtIndex:indexPath.row]];
/*NSString *message = [NSString stringWithFormat:@"You selected %@",[tableViewArray objectAtIndex:indexPath.row]];
 UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Alert"
 message: message delegate:self cancelButtonTitle:@"Close" otherButtonTitles:nil];
 [alert show];
 [alert release];*/
}

   - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
return [tableViewArray count];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"SimpleTableIdentifier"];
if (cell == nil) {
    cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:@"SimpleTableIdentifier"]autorelease];
}

cell.textLabel.text = [tableViewArray objectAtIndex:indexPath.row];

return cell;
}

// Implement viewDidLoad to do additional setup after loading the view, typically from a   nib.
- (void)viewDidLoad {
[super viewDidLoad];
NSArray *array = [[NSArray alloc] initWithObjects:@"1",@"2",@"3",@"4 ",@"5",@"6",@"Sko-7",@"",@"8",@"9",nil];

self.tableViewArray = array;
[array release];
}

- (void)didReceiveMemoryWarning {
// Releases the view if it doesn't have a superview.
[super didReceiveMemoryWarning];

// Release any cached data, images, etc that aren't in use.
}

- (void)viewDidUnload {
// Release any retained subviews of the main view.
// e.g. self.myOutlet = nil;
}

- (void)dealloc {
[super dealloc];
}

@end

Thanks :)

A: The usual suspect in a case like that is hooking up outlets in the nib or - even more likely - hooking up tableView delegate and datasource in the nib.  Can you double check to see that you did that?


text:
Q: An unauthenticated user can still see the "/account" page An unauthenticated user can still see the "/account" page for a few seconds I mean there is still a delay of a few seconds before the unauthenticated user is completely redirected to another page. even though I have used ProtectedRoute, how can I make unauthenticated users unable to see the "/account" page at all without delay? i use react-router-dom 6.6.1 and firebase auth
here is for the app.js
import { ThemeProvider } from '@mui/material/styles';
import React from 'react';
import { BrowserRouter as Router, Route, Routes, Navigate} from 'react-router-dom'
import Home from './components/Home'
import Account from './components/Account';
import Signin from './components/Home/Signin';
import theme from './theme';
import { AuthContextProvider } from './components/Context/AuthContext';
import ProtectedRoute from './components/ProtectedRoute';

function App() {

  return (
    <ThemeProvider theme={theme}>
      <AuthContextProvider>
    <Router>
      <Routes>
        <Route path='/' element={<Home />} />
        <Route path='/signin' element={<Signin />} />
        <Route path='/account' element={<ProtectedRoute><Account /></ProtectedRoute>} />
      </Routes>
      </Router>
      </AuthContextProvider>
      </ThemeProvider>

  )
}

export default App

and this is for the ProtectedRoute.js
import React from 'react';
import { Navigate } from 'react-router-dom';
import { UserAuth } from './Context/AuthContext';

const ProtectedRoute = ({ children }) => {
  const { user } = UserAuth();

  if (!user) {
    return <Navigate to='/' />;
  }
  return children;
};

export default ProtectedRoute;

this if for the UserAuth :

import { createContext, useContext, useEffect, useState } from 'react';
import {
  createUserWithEmailAndPassword,
  signInWithEmailAndPassword,
  onAuthStateChanged,
} from 'firebase/auth';
import { auth } from '../../firebase';

const UserContext = createContext();

export const AuthContextProvider = ({ children }) => {
  const [user, setUser] = useState({});

  const createUser = (email, password) => {
    return createUserWithEmailAndPassword(auth, email, password);
  };

   const signIn = (email, password) =>  {
    return signInWithEmailAndPassword(auth, email, password)
   }

  useEffect(() => {
    const unsubscribe = onAuthStateChanged(auth, (currentUser) => {
      setUser(currentUser);
    });
    return () => {
      unsubscribe();
    };
  }, []);

  return (
    <UserContext.Provider value={{ createUser, user, signIn }}>
      {children}
    </UserContext.Provider>
  );
};

export const UserAuth = () => {
  return useContext(UserContext);
};

I want to redirect unauthenticated users to the main page without delay

A: it's probably due to the fact that your guard is validating off of !user however your initial auth state has user as {}. In this case an empty object will validate as truthy.
You could either set the initial state of user as null or you could update th guard validation to check for a value on user like if (!user.id) …

A: Render Protected and Base routes conditional so unauthenticated user never have access of Protected routes.
Use the following code.
Always make separate file for routing for better code readability and Separation of concerns.
BaseRoutes.js
import React from 'react'
import { Route } from 'react-router-dom'

import Home from './components/Home'
import Signin from './components/Home/Signin';

const BaseRoutes = (
  <>
    <Route path='/' element={<Home />} />
    <Route path='/signin' element={<Signin />} />
  </>
)

export default BaseRoutes

ProtectedRoutes.js
import React from 'react';
import { Route } from 'react-router-dom';

import Account from './components/Account';

const ProtectedRoutes = () => {
  return (
    <>
      <Route path='/account' element={<Account />} />
    </>
  )
};

export default ProtectedRoutes;

Routes.js
import React from 'react'
import { Navigate, Route, Routes, BrowserRouter } from 'react-router-dom'
import { UserAuth } from './Context/AuthContext';

import ProtectedRoutes from './components/ProtectedRoutes';
import BaseRoutes from './components/BaseRoutes';

const Router = () => {

  const { user } = UserAuth();
  const isUser = Boolean(user)
  const redirectUrl = isUser ? '/account' : '/signin'

  return (
    <BrowserRouter>
      <Routes>
        {isUser ? <BaseRoutes /> : <ProtectedRoutes />}
        <Route
          path="*"
          element={<Navigate to={redirectUrl} />}
        />
      </Routes>
    </BrowserRouter>
  )
}

export default Router

app.js
import React from 'react';
import { AuthContextProvider } from './components/Context/AuthContext';
import { ThemeProvider } from '@mui/material/styles';
import theme from './theme';
import Router from './routes'

function App() {

  return (
    <ThemeProvider theme={theme}>
      <AuthContextProvider>
        <Router />
      </AuthContextProvider>
    </ThemeProvider>
  )
}

export default App


text:
Q: vue js realtime chat app without refreshing / firebase
I'm creating a chat app,
If the user enter message and press send button, the app is working fine. The informations going to the database and im taking a datas.
When the user refresh the page, so there is no problem, in mounted() instance im taking the datas from database(firebase) and im showing on the app. If another user comes to the chat, also there is no problem, all messages are appearing.
The problem is that:  If the new message is coming, another user can not see it without refresh or without send message button. When the another user send a message then the user see all messages.
I explain the problem with a gif, if you help me i will be glad.

<template>

Group Chat

Welcome, {{this.username }}

{{ message.msg }}
   {{ message.name }} - {{ message.time }}

            <form @submit.prevent="sendFunc">

    <input type="text" class="form-control" placeholder="Enter message.." v-model="msgInput">
    <button class="btn">Send </button>

            </form>

  <form @submit.prevent="joinFunc">

    <input type="text" class="form-control" placeholder="Enter username.." v-model="username">
    <button class="btn">Join to Group </button>

  </form>

</template>

A: You're using get() to read the data from Firestore. As the documentation I linked explains, that reads the value from the database once, and does nothing more.
If you want to continue listening for updates to the database, you'll want to use a realtime listener. By using onSnapshot() your code will get called with a querySnapshot of the current state of the database right away, and will then also be called whenever the database changes. This is the perfect way to then update your UI.
So instead of
...
.get()
.then((querySnapshot) => {
  querySnapshot.forEach((doc) => {

Do the following:
...
.onSnapshot((querySnapshot) => {
  querySnapshot.forEach((doc) => {


text:
Q: Taglib read ID3v2 tags from arbitrary file c++ I'm trying to use the TagLib C++ API to read ID3v2 metadata from an arbitrary audio file. This file is not necessarily an .mp3 file, and may be of the other common audio formats. I have the following:
std::string readId3v2Tag(std::string filePath, std::string tagName) {
    // read from file
    TagLib::FileRef f(filePath.c_str());
    if (!f.isNull() && f.file()) {
        // get tags from property map
        TagLib::PropertyMap tags = f.file()->properties();
        if (tags.find(tag) != tags.end()) {
            return std::string(tags[tag][0].toCString());
        }
    }
}

However, when I input an ID3v2 frame name, it doesn't return anything. I believe this is because the f.file()->properties() map contains TagLib's tag format. I must be able to access ID3v2 frames by name.
I have been told to use the ID3v2 class, however I don't see how to access this from a file, and am having trouble reading the API docs. Does anyone know how to do this?

A: Always read the manual: it tells you to not use the file() approach. Also properties() won't give you ID3v2 tag frames - you should iterate all of them to see their keys and values.
Instead

*

*use MPEG::File (see manual) and from there go/read on

*over ID3v2Tag() (see manual)

*to frameList() (see manual).

It's pretty straightforward once the terms are clear: a file can have zero to multiple tags, where a ID3v2 tag can have one to multiple frames. The file alone however can also have multiple properties that are unbound to tags (i.e. audio duration, bit depth...) - no wonder that none of your frame names you search for won't show up in the file's properties.


text:
Q: Changing Field Name in ArcGIS Desktop How can I change the field names (not the alias) in ArcGIS 10.2?
I already found this page on ArcGIS support: "Renaming shapefile fields (Defense Mapping)" but there is is not "Defense Mapping" on Customized Mode Categories In my ArcCatalog!
Without access to Defense Mapping, how can I change the field names?

A: You can import the shapefile into a file geodatabase, then change the field name.
Then export it back out to a shapefile.
EDIT in response to comment by @Anthony To
This is done via the Arc Catalog Window by:

*

*R-clicking on the Featureclass

*Select the "Fields" tab

*Change the appropriate Field Name

This still leaves the Field Alias as it was before but that is easily changed, as always.
And it leaves the Field in the same relative location when viewing the Attribute table, unlike the Alter Field Tool.

A: You can now rename a field using core ArcGIS Desktop GP tool - Alter Field (Data Management).

This tool provides the ability to rename fields or rename field
  aliases for any geodatabase table or feature class.

I have not installed 10.2.1 on a virtual machine yet (was released just a day ago), but my guess is that by feature class here Esri means both geodatabase feature classes and shapefiles, but I am not 100% on that.
This tool is available starting with 10.2.1.

A: In short you cannot change a field name in a shapefile. What you need to do is create a new field of the same type but with your new name then copy the contents of the old field into it, then delete the old field.

A: If you are willing to use other software to complement ArcGIS, you can use QGIS with the Table Manager Plugin (you can install it via Plugins > Install and Manage Plugins).
In QGIS:

*

*Add your shapefile with Layer > Add vector layer...;

*Select your layer in the "table of contents";

*Open the plugin via Vector > Table Manager;

*Select the desired field and press rename and choose the new name;

*Don't forget to save, and then close.

Note: You can also reorder all your fields. Nice and easy, with no need for data duplication or temporary fields.

A: I was having the same problem as Anthony To where I can only edit Alias in ArcCatalog, but when I closed the ArcMap where the same feature class is being used, I was now able to edit the Field in ArcCatalog.
In short, make sure the feature class is not being used in any open ArcMap.

A: You can import the Shape file to PERSONAL GDB, then open it with MS Access.
open the relevant table and change whatever you want.
after the change being made, you can either open the personal gdb directly in Arc, or you can export it back to shape.

A: I just used Alter Field in Arc Toolbox//Data Management Tool// Fields. Works perfectly you can change alias or field name

A: I used Arc Toolbox -> Data Management Tool -> Fields -> Add Field since I am using ArcGIS 10.1. This process can let you add a field where you can provide the Field Name you want with max of 10 characters. You can also delete a field using Delete Field if you want to remove one. I have not seen any option to edit or rename the Field Name in this version.

A: One smart move is to use the Spatial Join and rename all fields in once (just join it with another feature and delete the field immediatly). It works without just changing the "alias"!


text:
Q: Testing a component in Next.js with testing-library that relies on tRCP I was experimenting with tRCP and diligently followed the setup for my Next.js project described in the official docs over here: https://trpc.io/docs/nextjs
However I noticed that a simple component that relies on tRPC such as this
export const Sample = () => {
  const { data } = trpc.useQuery(['hello', { text: 'User' }]);
  if (data === undefined) {
    return
Loading...
;
  }
  return
{data.greeting}
;
};

cannot be properly tested since the following trivial test
describe('Sample', () => {
  it('should render successfully', () => {
    const { baseElement } = render(<Sample />);
    expect(baseElement).toBeTruthy();
  });
});

since there is no setup of provider such as the setup with the withTRCP HOC used for the application itself. As such the test fails claiming client (presumably the trcpClient, unlike the queryClient) is undefined.
I'd like to know how to setup the test correctly, in this case providing a correct client, as well as mocking the queries, since I don't have the respective server-side code running while invoking the tests.

A: Since you are getting undefined for the trpc client implementation, you can try spying on the query call.
import trpc from 'utils/trpc'; // This is the client implementation

describe('Sample', () => {
  it('should render successfully', () => {
    jest.spyOn(trpc, 'useQuery')
        .mockReturnValue({ greeting: "Greeting" });

    const { baseElement } = render(<Sample />);
    expect(baseElement).toBeTruthy();
  });
});

This is also possible with the mutations but you need to provide a mock implementation for the useMutation response for mutate property.