text:
Q: Count words and spaces in string C# I want to count words and spaces in my string. String looks like this:
Command do something ptuf(123) and bo(1).ctq[5] v:0,

I have something like this so far
int count = 0;
string mystring = "Command do something ptuf(123) and bo(1).ctq[5] v:0,";
foreach(char c in mystring)
{
if(char.IsLetter(c))
  {
     count++;
  }
}

What should I do to count spaces also?

A: int countSpaces = mystring.Count(Char.IsWhiteSpace); // 6
int countWords = mystring.Split().Length; // 7

Note that both use Char.IsWhiteSpace which assumes other characters than " " as white-space(like newline). Have a look at the remarks section to see which exactly .

A: you can use string.Split with a space
http://msdn.microsoft.com/en-us/library/system.string.split.aspx
When you get a string array the number of elements is the number of words, and the number of spaces is the number of words -1

A: if you want to count spaces you can use LINQ :
int count = mystring.Count(s => s == ' ');

A: Here's a method using regex. Just something else to consider. It is better if you have long strings with lots of different types of whitespace. Similar to Microsoft Word's WordCount.
var str = "Command do something ptuf(123) and bo(1).ctq[5] v:0,";
int count = Regex.Matches(str, @"[\S]+").Count; // count is 7

For comparison,
var str = "Command     do    something     ptuf(123) and bo(1).ctq[5] v:0,";

str.Count(char.IsWhiteSpace) is 17, while the regex count is still 7.

A: This will take into account:

*

*Strings starting or ending with a space.

*Double/triple/... spaces.

Assuming that the only word seperators are spaces and that your string is not null.
private static int CountWords(string S)
{
    if (S.Length == 0)
        return 0;

    S = S.Trim();
    while (S.Contains("  "))
        S = S.Replace("  "," ");
    return S.Split(' ').Length;
}

Note: the while loop can also be done with a regex: How do I replace multiple spaces with a single space in C#?

A: I've got some ready code to get a list of words in a string:
(extension methods, must be in a static class)
    /// <summary>
    /// Gets a list of words in the text. A word is any string sequence between two separators.
    /// No word is added if separators are consecutive (would mean zero length words).
    /// </summary>
    public static List<string> GetWords(this string Text, char WordSeparator)
    {
        List<int> SeparatorIndices = Text.IndicesOf(WordSeparator.ToString(), true);

        int LastIndexNext = 0;

        List<string> Result = new List<string>();
        foreach (int index in SeparatorIndices)
        {
            int WordLen = index - LastIndexNext;
            if (WordLen > 0)
            {
                Result.Add(Text.Substring(LastIndexNext, WordLen));
            }
            LastIndexNext = index + 1;
        }

        return Result;
    }

    /// <summary>
    /// returns all indices of the occurrences of a passed string in this string.
    /// </summary>
    public static List<int> IndicesOf(this string Text, string ToFind, bool IgnoreCase)
    {
        int Index = -1;
        List<int> Result = new List<int>();

        string T, F;

        if (IgnoreCase)
        {
            T = Text.ToUpperInvariant();
            F = ToFind.ToUpperInvariant();
        }
        else
        {
            T = Text;
            F = ToFind;
        }

        do
        {
            Index = T.IndexOf(F, Index + 1);
            Result.Add(Index);
        }
        while (Index != -1);

        Result.RemoveAt(Result.Count - 1);

        return Result;
    }

    /// <summary>
    /// Implemented - returns all the strings in uppercase invariant.
    /// </summary>
    public static string[] ToUpperAll(this string[] Strings)
    {
        string[] Result = new string[Strings.Length];
        Strings.ForEachIndex(i => Result[i] = Strings[i].ToUpperInvariant());
        return Result;
    }

A: In addition to Tim's entry, in case you have padding on either side, or multiple spaces beside each other:
Int32 words = somestring.Split(           // your string
    new[]{ ' ' },                         // break apart by spaces
    StringSplitOptions.RemoveEmptyEntries // remove empties (double spaces)
).Length;                                 // number of "words" remaining

A: using namespace;
namespace Application;
class classname
{
    static void Main(string[] args)
    {
        int count;
        string name = "I am the student";
        count = name.Split(' ').Length;
        Console.WriteLine("The count is " +count);
        Console.ReadLine();
    }
}

A: if you need whitespace count only try this.
string myString="I Love Programming";
var strArray=myString.Split(new char[] { ' ' });
int countSpace=strArray.Length-1;

A: How about indirectly?
int countl = 0, countt = 0, count = 0;

foreach(char c in str)
{
    countt++;
    if (char.IsLetter(c))
    {
        countl++;
    }
}
count = countt - countl;
Console.WriteLine("No. of spaces are: "+count);


text:
Q: React components not rendering from dependencies I'm following the React tutorial and building a React/Express app based on the repository in github.
In the tutorials index.html all React dependenices are listed in this file as:

<!DOCTYPE html>

    <meta charset="utf-8">
    <title>React Tutorial</title>

    <link rel="stylesheet" href="css/base.css" />

However when I add the React packages I need into the package.json dependencies as:
{
  "name": "react_example",
  "version": "1.0.0",
  "description": "A simple react example",
  "main": "server.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "start": "node server.js"
  },
  "author": "",
  "license": "ISC",
  "dependencies": {
    "axios": "^0.14.0",
    "babel-standalone": "^6.17.0",
    "body-parser": "^1.15.2",
    "express": "^4.14.0",
    "react": "^15.3.2",
    "react-dom": "^15.3.1"
  },
  "devDependencies": {}
}

I then include these in the example.js file as:
require('babel-standalone');
var React = require('react');
var ReactDOM = require('react-dom');
var axios = require('axios');

Nothing is rendered and in the browser console I get an error:
example.js:19 Uncaught SyntaxError: Unexpected token <
Where line 19 is:

I'm a novice with React and want to find out how I can render React components.

A: I have put together the steps to get React working with Webpack. If you follow the article, you will get a React application with minimal scaffolding.
babel-core is required for babel to work. babel-preset-react is for JSX compilation. babel-preset-es2015 is for transpilation from es6 to es5. babel-loader is required for webpack to build.
In your case, most likely babel-preset-react or equivalent script is not available for compiling JSX to JS.

A: You are mixing two methods of development together in one. The example mentioned here is compiling all JSX syntax and on the fly in the browser and contains compiled react scripts as below

In the example.js you are not required to require these as you can see here in which you have written import statements.
require('babel-standalone');
var React = require('react');
var ReactDOM = require('react-dom');
var axios = require('axios');

They have used npm to run a simple node server(and not to compile react/babel) that can serve as simple API endpoint. This example is only to learn react with minimal setup and hence i don't suggest you to use it to build any application.
I hope you are trying to use npm as the package manager/development environment and start developing. For this there are lots of tutorials like this.
EDIT
Remove the below scripts and i hope it should start rendering

EDIT 2
Change you index.html to something similar to below
  <!DOCTYPE html>

      <meta charset="utf-8">
      <title>React Tutorial</title>

      <link rel="stylesheet" href="css/base.css" />

redpajama_set_name: RedPajamaStackExchange


text:
Q: How do you access the $on, $emit, $broadcast methods with Controller as syntax? Using $scope it's easy to emit an event or watch for one.
(function() {
    "use strict";

    angular
        .module("app")
        .controller("Ctrl", [
            "$scope",
            CtrlDefinition
        ]);

    function CtrlDefinition($scope) {
        $scope.$on("change", listenForChange);

        function listenForChange(data) {
            //do something
        }
    }
})();

But if I try to use var vm = this syntax, I'm warned that $on, $emit, and $broadcast are not methods of this. How can I access them? Do I still need to inject $scope in the controller definition?
(function() {
    "use strict";

    angular
        .module("app")
        .controller("Ctrl", CtrlDefinition);

    function CtrlDefinition() {
        var vm = this;
        vm.$on("change", listenForChange); //$on is not a method of vm
    }

})();

You could do something like this, but wouldn't it defeat the purpose of not having to use $scope at all?
(function() {
    "use strict";

    angular
        .module("app")
        .controller("Ctrl", [
            "$scope",
            CtrlDefinition
        ]);

    function CtrlDefinition($scope) {
        var vm = this;
        vm.scope = $scope;
        vm.scope.$on("change", listenForChange);
    }

})();

How can you access watchers with controller as syntax?

A: In order to use anything that exists on $scope, you are forced to inject $scope.  It's unfortunately that straightforward, which is a shortcoming of the "as" syntax.
The good news however is that injecting $scope alongside this does not change how the controller as syntax functions, it simply gives you access to all of the event management that lives on  $scope.
It's worth noting that this is one of the primary reasons for what is coming in Angular 2.0...there is a real problem and discrepancy between $scope and the "Controller as" syntax that was bolted on to solve scoping issues in views.


text:
Q: Matlab: Resizing Matrices here's my matlab problem. I need to write a matlab function that copies all data from a struct datatype to a matrix. Problem is that each entry can have a different length. So what I've been doing so far is iterating through all these entries in order to precalculate the final size of the matrix.
%Calculate final size of Matrix
nFieldsY = length(CompleteData.Y);
nFieldsX = length(CompleteData.X);
maxRowNumber = 0;
maxColNumber = nFieldsY + nFieldsX;

for j = 1:nFieldsY
  l_x = length (CompleteData.X(1,j).Data);
  l_y = length (CompleteData.Y(1,j).Data);
  compAr = [maxRowNumber l_x l_y];
  maxRowNumber = max(compAr);
end

ResultMatrix = zeros(maxRowNumber, maxColNumber);

So "ResultMatrix" represents the maximum of data that could possibly be stored. Now I would like to replace the first n entries in column m of the matrix. The rest of the column should still be filled with zeros. Despite all my efforts I get the "dimension mismatch" error.
Appreciate any help. Thanks

A: Something like this
ResultMatrix(1:n,m) = n_entries

where n_entries is a n x 1 matrix of the values you want to put in the column.
The 1:n picks out rows 1 to n of ResultMatrix, and the m picks column m.


text:
Q: ggplot facetted geom_boxplot: reduce space between x-axis categories I am creating a boxplot using ggplot. When I reduce the width of the boxplot the space between the x-axis categories increases. I would like to be able to reduce the space between the x-axis categories and bring the box plots closer to each other.
p<-ggplot(data.plot1, aes(time2, Count))
p+geom_boxplot(outlier.shape = NA, width=0.3)+
  ggtitle("")+ylab("Cell Count (cells/mL) ")+ xlab("Time")  +
  theme_bw()+  coord_cartesian(ylim = c(0, 850))+
  geom_hline(data=normal1, aes(yintercept = val), linetype="dashed")+
  facet_grid(.~CellType1)

So, basically, reduce the space between Day 0, Day30, Day 100 and bring the boxplots closer to each other.

A: As mentioned in the comments, narrowing the graphics device is one way of doing it. Another way to do it without changing the size of the graphics device is to add spaces between your bars and the sides of the panels. Note: Since your question is not reproducible, I have used the build-in infert dataset, which serves demonstrative purposes. Assuming that this is your original facetted side-by-side boxplots:
p<-ggplot(infert, aes(as.factor(education), stratum))
p+geom_boxplot(outlier.shape = NA, width=0.3)+
  ggtitle("")+ylab("Cell Count (cells/mL) ")+ xlab("Time")  +
  theme_bw()+  coord_cartesian(ylim = c(0, 80))+
  # geom_hline(data=normal1, aes(yintercept = val), linetype="dashed")+
  facet_grid(.~induced)

This brings the categories together by adding white space on both ends of each panel:
p+geom_boxplot(outlier.shape = NA, width=0.6)+
  ggtitle("")+ylab("Cell Count (cells/mL) ")+ xlab("Time")  +
  theme_bw()+  coord_cartesian(ylim = c(0, 80))+
  # geom_hline(data=normal1, aes(yintercept = val), linetype="dashed")+
  facet_grid(.~induced) +
  scale_x_discrete(expand=c(0.8,0))

The two numbers in scale_x_discrete(expand=c(0.8,0)) indicate the multiplicative and additive expansion constant that "places some distance away from the axes". See ?scale_x_discrete. This effectively "squishes" the boxplots in each panel together, which also reduces the width of each boxplot. To compensate for that, I increased the width to width=0.6 in geom_boxplot. Notice that the x-axis labels are now overlapping. You will have to experiment with different expansion factors and width sizes to get exactly how you want it.
Also see this question for a related issue: Remove space between bars within a grid


text:
Q: Queue3 Chapter 19 in Programming in Scala 2nd edition Question I'm doing a code review for the Queue3 example in the Programming in Scala 2nd edition by Odersky et al. And I guess i'm stuck.
Here's the code:
http://booksites.artima.com/programming_in_scala_2ed/examples/type-parameterization/Queues3.scala
object Queues3 {
  class Queue[T](
    private val leading: List[T],
    private val trailing: List[T]
  ) {
    private def mirror =
      if (leading.isEmpty)
        new Queue(trailing.reverse, Nil)
      else
        this

    def head = mirror.leading.head

    def tail = {
      val q = mirror
      new Queue(q.leading.tail, q.trailing)
    }

    def enqueue(x: T) =
      new Queue(leading, x :: trailing)
    override def toString =
      leading ::: trailing.reverse mkString ("Queue(", ", ", ")")
  }

  object Queue {
    // constructs a queue with initial elements `xs'
    def apply[T](xs: T*) = new Queue[T](xs.toList, Nil)
  }

  def main(args: Array[String]) {
    val q = Queue[Int]() enqueue 1 enqueue 2
    println(q)
  }
}

So it's trying to implement a queue in a functional programming way with speed similar to the imperative way.
So to do this it'll split the queue into two part so we can append toward the end by constant speed. The whole queue is basically:
leading ::: trailing.reverse

The book is saying that worst case scenario is when the leading is empty.
So if code do this
val q = Queue[Int]() enqueue 1 enqueue 2

Then,
q.leading is List() and q.trailing is List(2,1)
So when I call q.head, the book stated that since leading is empty, mirror will copy everything from trailing, reverse it and set it as leading.
The problem is I don't think this work because it's a method? So it doesn't persist via state. Because I made the code properties public and checked q.leading and q.trailing and the value is the same. What I'm expecting after I do q.head is:
q.leading is List(1,2) and q.trailing is List()

But it is not, am I missing something? Is this some FP paradigm that I'm missing? Because I think it can work the way I think it should work if head and tail methods is change to var.
Thank you for your time.
Edit making the properties public:
private val leading: List[T],
private val trailing: List[T]
edit:
chapter 19 in 1st edition:
http://www.artima.com/pins1ed/type-parameterization.html

A: You problem is that head and tail methods doesn't return new Queue. And you are inspecting the old one. Checkout this versions of head and tail. Now they return new Queue in a tuple.
def head: (T, Queue[T]) = {
    val q = mirror
    (q.leading.head, q)
  }

def tail: (Queue[T], Queue[T]) = {
  val q = mirror
  (new Queue(q.leading.tail, q.trailing), q)
}

As you can see, mirror works fine.
val q = Queue[Int]() enqueue 1 enqueue 2
println(q)
printLT(q)
val q1 = q.head
println(q1._1)
printLT(q1._2)

def printLT[A](q: Queue[A]) {
  println("leading: " + q.leading)
  println("trailing: " + q.trailing)
}

Output:
Queue(1, 2)
leading: List()
trailing: List(2, 1)
1
leading: List(1, 2)
trailing: List()


text:
Q: Staying outside during the night Is it possible to survive outside the town during the night if my character is stuck (due to the lack of AP) on a square that has 0 zombies on it?

A: No. If your character is not inside the town when the zombies attack, you die.


text:
Q: Do i have to run garbage collection or something?   import android.app.Activity;

import android.graphics.drawable.AnimationDrawable;
import android.os.Bundle;

import android.widget.ImageView;

public class GenieComesOut extends Activity
{

ImageView genie;
AnimationDrawable genieout;

@Override
 public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.genie_out);
        genie = (ImageView)findViewById(R.id.genieout);

        genieout = (AnimationDrawable) genie.getDrawable();
        genie.post(new Runnable() {public void run() {genieout.start();}});
    }

I got the animations to start going, i can only fit 20 frames in one, more than that i get VM wont allocate, these are full screen images, i have about 50 frames left, so, can i make a new /anim/xml switch onto the ImageView garbage collect and runnable another 20 frames, what is the proper way to do this? Thank you for your time

A: You should consider converting your animation to a video if that is really fullscreen. Video can then be played easily and won't eat your memory.
Here is the list of supported formats: Android Supported Media Formats. You could use H264 or 3GP, try what looks best and performs better.


text:
Q: WordPress/WooCommerce URL for catgories We have always been able to determine two categories in the URL to filter the results to show items that meet both of the categories in the URL
For example: http://www.shoezies.co.nz/product-category/sale+shoes/
This would show only products that are in the 'sale' category and the 'shoes' category.
This is no longer working in the latest WordPress update. Does anyone have experince wiht this kind of thing.
I have contact WooCommerce support but they are extremely slow so hoping the community can help a brother out.

A: On new wordpress version,  old php and wordpress/woocommerce functions doesn't work.
So these problems often occurs after upgraded wordpress version.
In my thought,  some woocommerce functions related to product category will be changed.
If you let me know details info, I can fix them correctly
Or you can search positive solutions yourself on google depends on this answer

A: You've got an issue with your custom.js file, change your code to this.
(function( $ ) {
    'use strict';

    $(function() {
        $('.home-box:empty').hide();
    });
});

Also for multiple categories you can pass this URL, separate categories with a comma.
http://www.shoezies.co.nz/?product_cat=sale,shoes

I can't check if it's working because your site is not rendering because of the jQuery error.


text:
Q: laravel components not working on live server I'm new to vue.js, its my first experience for using Laravel and vue.js together.
Right now I have a problem for rendering vue.js externally.
It works in "localhost:8000" but it doesn't work in 192.168.100.34.
Additionally, I have already executed all cache clearing methods on Laravel, but I have the same issue.


text:
Q: Use named ranges in VBA How can I use a dynamic named range in VBA? For example now I use a named range called "Range1", but the user may choose a different name (I have to work with a lot of named ranges so I need something more general). I am new at this, but should I store the named range in a variable? Thanks in advance!
This is what I have so far:
Dim MyArray
Dim dctCol As dictionary
Dim strKey1 As String

Set dctCol = New dictionary
MyArray = Range(ActiveWorkbook.Names("Range1").RefersToRange.Address)
For j = 2 To UBound(MyArray , 2)
    strKey1 = Trim(MyArray (1, j)) & "," & Trim(MyArray (2, j)) & "," & Trim(MyArray (3, j))
    dctCol(strKey1) = j
Next

A: It is not quite clear what is needed. But if you just want to process all the named ranges in a book, regardless of their names, you can just go through the WB name collection:
Sub ListNamesAddresses()
    Dim nm As Name
    For Each nm In ActiveWorkbook.Names
        Debug.Print nm.Name, nm.RefersToRange.Address
        'do something with names and it's properties
    Next
End Sub

Output:
Name1         $D$4:$D$21
Name2         $E$4:$E$21
Name3         $F$4:$F$21
Name4         $G$4:$G$21
Name5         $H$4:$H$21
Name6         $I$4:$I$21


text:
Q: Android - why ContentObserver invokes itself? I am trying to delete received SMS in ContentObserver (on "content://sms/") onChange() method using  contentResolver.delete, but after deleting ContentObserver is invoked one more time.
Could you explaing my, whe ContentObserver invokes itself despite deliverSelfNotifications() returns false?
I foud soultion to uregister ContentObserver before deleting the sms and register again after, but is inelegant.
My code:
  private class SmsMmsContentObserver extends ContentObserver {
    public SmsMmsContentObserver(Handler handler)
    {
      super(handler);
    }

    @Override public boolean deliverSelfNotifications() {
        return false;
        }

    @Override
    public void onChange(boolean selfChange) {
      super.onChange(selfChange);

      Uri uriSMSURI = Uri.parse("content://sms/");
      Cursor cur = getContentResolver().query(uriSMSURI, null, null,
                   null, null);
      if (cur.moveToNext())
      {
        int threadIdIn = cur.getInt(cur.getColumnIndex("thread_id"));
           getContentResolver().delete(Uri.parse("content://sms/conversations/" + threadIdIn), null, null);
      }

    }
  }

Methods to register observer in on of services.
private void registerSmsMmsObserver()
  {
   if (observer == null)
   {
       observer = new SmsMmsContentObserver(new Handler());
       contentResolver = getContentResolver();
       contentResolver.registerContentObserver(uriSmsMms, true, observer);
   }
  }

  private void unregisterSmsMmsObserver()
  {
   if (contentResolver != null)
    contentResolver.unregisterContentObserver(observer);
   observer = null;
  }

A: If you want to delete the SMS when it arrives in the inbox, use a receiver for the orderedbroadcast that matches the SMS receive intent, get a higher priority than the regular inbox, and cancel the broadcast.
Also, the delete is sure to invoke an onChange on any contentObserver obsering this URI.
deliverSelfNotification does not do what you seem to think:

Returns true if this observer is interested in notifications for changes made through the cursor the observer is registered with.


text:
Q: Android ID as an alternative to Device ID My apps have always used DeviceId as a unique identifier and this, of course, requires READ_PHONE_STATE as a permission.  That has been ok in the past but now I have migrated to Marshmellow 23 where asking for this permission displays a very scary dialog at run time saying...
"Allow {my app} to make and manage phone calls?"
That's a pretty hideous message for an app that just wants to get deviceId.
I'm thinking of switching over to Android ID as it doesn't require any permission.
String androidId = Settings.Secure.getString(getContentResolver(), Settings.Secure.ANDROID_ID);

Googling around I see there have been some problems using android ID but it's all old stuff.  Back in Froyo days there was a phone vendor that produced the same ID for all of their phones but that's about all I have seen.
Is anyone aware of any problems using Android ID?
Thanks,
Dean

A: What unique identifier you choose to use depends heavily on what specific use case you need the identifier for. The Best Practices for Unique Identifiers training goes through many common use cases and which identifier to use. They do have a number of tenents of working with Android Identifiers:

1: Avoid using hardware identifiers. Hardware identifiers such as SSAID (Android ID) and IMEI can be avoided in most use-cases without limiting required functionality.
2: Only use Advertising ID for user profiling or ads use-cases. When using an Advertising ID, always respect the Limit Ad Tracking flag, ensure the identifier cannot be connected to personally identifiable information (PII) and avoid bridging Advertising ID resets.
3: Use an Instance ID or a privately stored GUID whenever possible for all other use-cases except payment fraud prevention and telephony. For the vast majority of non-ads use-cases, an instance ID or GUID should be sufficient.
4: Use APIs that are appropriate to your use-case to minimize privacy risk. Use the DRM API API for high value content protection and the SafetyNet API for abuse prevention. The Safetynet API is the easiest way to determine whether a device is genuine without incurring privacy risk.

In the vast majority of cases, Android ID is still not the right thing to use.


text:
Q: Limit set of a non-autonomous system is not invariant I am trying to understand why the (positive or omega) limit set of a non-autonomous dynamical system
\begin{equation}
\dot{x}=f(t,x)
\label{ftx}
\tag{1}
\end{equation} is not necessarily (positively) invariant. Assume that $f$ is piecewise continuous in $t$ for each fixed $x$, and that $f$ is locally Lipschitz in $x$ uniformly over $t$.
I have seen the proof for the autonomous case in this question, and I imagine that, for the non-autonomous case, a set $\bar{\omega}$ may belong to the positive limit set of \ref{ftx} for a given initial time $\bar{t}$, but if the initial time is changed to some $\hat{t}$, then it is possible that the solution will enter $\bar{\omega}$ and leave it.
Am I correct? Or is there something I'm missing that will break in the aforementioned proof?


text:
Q: Filters in Topology (Converge) Let $X$ be an infinite set, $\mathscr{F}$ the filter on $X$ generated by the filter base consisting of all complements of finite sets. To which points does $\mathscr{F}$ converge if $X$ is given the cofinite topology?
I would suspect the answer to be every point in $X$. My reasoning, though may be wrong, is given below.

Let $\mathscr{C}$ denote the filter base, i.e. $\mathscr{C}:=\{A^c: A\subset X\text{ is finite}\}$ and $\mathscr{U}_x$ denote the set of all nhbds of $x$. The filter $\mathscr{F}$ converges to $x\in X$ iff each $U\in \mathscr{U}_x$ contains some $C\in\mathscr{C}$.
Notice,
$$C\subseteq U\iff U^c\subseteq C^c.$$
By definition of the topology, the set $U^c$ is finite, whereas by definition of the filter base, the set $C^c$ is infinite. Therefore, each $U\in \mathscr{U}_x$ contains some $C\in\mathscr{C}$.

A: Note that $\mathscr{C}$ is already a filter, so $\mathscr{F}=\mathscr{C}$. It's true that $\mathscr{C}$ converges to every point of $X$, but there is an error in your argument: for any $C\in\mathscr{C}$ the set $C^c$ is by definition finite, not infinite. But since you haven't actually picked any set $C\in\mathscr{C}$, this doesn't say anything about a particular $U\in\mathscr{U}_x$. What you really should say here is that if $U\in\mathscr{U}_x$, then $X\setminus U$ is finite, so $U\in\mathscr{C}$. In fact, $\mathscr{U}_x=\{C\in\mathscr{C}:x\in C\}$ for each $x\in X$, and therefore $\mathscr{U}_x\subseteq\mathscr{C}$.

A: Yes, if $x \in X$, then any open neighbourhood of $x$ is of the form $F^\complement$, where $F$ is finite. By definition $F^\complement \in \mathcal{F}$ (It has finite complement so is in the filterbase), and so all (open) neighbourhoods of $x$ are in the filter and we have convergence $\mathcal{F}\to x$, for any $x$.


text:
Q: Data is not being read directly from the database instead of buffer on 2nd call I have the following piece of code in my model that ensures that user will be not able to modify a record that was modified by someone else after he has opened it.
 def save(self, *args, **kwargs):
        on_disk = Lease.objects.get(pk=self.id)
        self.full_clean()
        if on_disk.version == self.version:
            error = 0 #do nothing
        else:
            raise ValidationError('Record have been modified by another user, please reopen and edit again')
        # self.version = self.version + 1
        return super(Lease, self).save(*args, **kwargs)

There is mechanism implemented(Django concurrency package) that ensures that after each save version value will be modified.
However, this piece of code doesn't work it appears to me that on_disk value is not being populated with the most recent value from the disc but get it from some buffer and as result this code check is useless.
Any idea how to make it work?


text:
Q: I don't understand the output of the expr command When I run this code
#!/usr/bin/bash
str="I am enjoying this day to the fullest !"
x="this"
y=`expr index "$str" "$x"`
z=${str:`expr $y - 1`:5}
echo $x
echo $y
echo $z

the output is this
this
11
ing t

so I want to know why this is so.
And how can I fix this?

A: index searches for characters.  Perhaps you wanted match?
Try
#!/bin/bash
str="I am enjoying this day to the fullest !"
x="this"
y=$(expr  "$str" : ".*$x" - length "$x")
z=${str:$y:${#x}}
echo $x
echo $y
echo $z

The : operator is the anchored regex match operator.
The pattern to match is "." (any character) "*" zero or more of them, followed by the string in $x (note: this should not contain unescaped regex characters)
This portion will return the length of the matched strong, which will be the number of characters from the beginning of the string ("anchored") to the end of the string in $x.
The next portion subtracts the length of $x to result in the offset in $str to the first character of $x.  This could be replaced with ${#x} as in the following line.


text:
Q: Misplaced alignment tab error Im getting this error, on a simple code, and i dont understand it.
\printbibliography[heading=none]

it shows up on this line.
It says:
You have placed an alignment tab character '&' in the wrong place. If you want to align something, you must write it inside an align environment such as \begin{align} … \end{align}, \begin{tabular} … \end{tabular}, etc. If you want to write an ampersand '&' in text, you must write \& instead."

\namepartgiven ...medelimb Schultz\bibnamedelimb &
                                                  \bibnamedelimb Nikolaj\bib...
l.254 \printbibliography[heading=none]

I can't figure out why you would want to use a tab mark
here. If you just want an ampersand, the remedy is
simple: Just type `I\&' now. But if some right brace
up above has ended a previous alignment prematurely,
you're probably due for more error messages, and you
might try typing `S' now just to see what is salvageable.


text:
Q: Apache Ignite SqlFieldQuery on top of cache storing BinaryObject I cannot seem to get this to work, and have scoured the net for documentation or examples to no avail
Goal
To run a simple aggregation query on an Ignite Cache backed by BinaryObject values with UUID as the key
Put Operation Code
IgniteBinary binary = ignite.binary();
            IgniteCache<UUID, BinaryObject> rowCache = ignite.getOrCreateCache(CACHE_NAME).withKeepBinary();

            // put

            final int NUM_ROW = 100000;
            final int NUM_COL = 100;
            for (int i = 0; i < NUM_ROW; i++) {
                BinaryObjectBuilder builder = binary.builder(ROW);
                for (int j = 0; j < NUM_COL; j++) {
                    builder.setField("col" + j, Math.random(), Double.class);
                }
                BinaryObject obj = builder.build();
                rowCache.put(UUID.randomUUID(), obj);
            }

Read Operation Code
IgniteCache<UUID, BinaryObject> cache = ignite.cache(CACHE_NAME).withKeepBinary();
final SqlFieldsQuery sqlFieldsQuery = new SqlFieldsQuery("SELECT COUNT(col1)" + cache.getName());
FieldsQueryCursor<List<?>> result = cache.query(sqlFieldsQuery);

Error
org.h2.jdbc.JdbcSQLException: Column "COL1" not found; SQL statement

EDIT
I've since added a QueryEntity to the cache configuration to make the problem disappear
 final QueryEntity queryEntity = new QueryEntity();
        queryEntity.setTableName(CACHE_NAME);
        queryEntity.setKeyFieldName("key");
        queryEntity.setKeyType(String.class.getName());
        queryEntity.setValueType(Row.class.getName());
        LinkedHashMap<String, String> fields = new LinkedHashMap<>();
        fields.put("key", String.class.getName());
        for (int i = 0; i < 55; i++) {
            fields.put("col" + i, Double.class.getName());
        }
        queryEntity.setFields(fields);
        return queryEntity;

However, it is unclear to me how QueryEntity's setValueType and setValueFieldName does? My value type is an arbitrary Binary object with arbitrary key, values
I would like to declare these via fields.put(<colName>, <colType>); ...
I am able to get everything to work using POJOs, but not BinaryObject as the value type
Is there anything I am doing wrong?

A: new SqlFieldsQuery("SELECT COUNT(col1)" + cache.getName())

Cache name is a schema name, and class name (Row) is a table name. Looks like you have incorrect table name.
Also make sure that ROW in binary.builder(ROW) equals to QueryEntity.valueType.


text:
Q: Not able to write in /dev/mem The issue that I am experimenting is not related with open() or mmap() function, which are executed properly. I have disabled CONFIG_STRICT_DEVMEM in the kernel so I can read from /dev/mem without problems. Actually, I can do the following:
const char *path = "/dev/mem"
int fd = open(path, O_RDWR); /* read and write flags*/
p  = mmap(0, SIZE, PROT_READ | PROT_WRITE, MAP_SHARED, fd, BASE_ADDR); /* read and write flags*/

And the code does not fail. Nonetheless, I am using this code to write in the PCI address space. So, basically the BASE_ADDR is 0xc000000, and the size is 256 MiB (0x10000000, all the PCI address space).
Said that, when I try to write on these positions (with a specific offset, BDF format), nothing is written; again the code does not fail, it just does not write anything.
In case my code was wrong, I tried BusyBox, with the following parameters:
[horro@ ~]$ sudo busybox devmem 0xc00b0a8c w 0xffffffff
[horro@ ~]$ sudo busybox devmem 0xc00b0a8c
0x00000000

So, basically it is not writing anything.

A: There is a CONFIG_STRICT_DEVMEM kernel config option. My understanding is that it must be set at compile-time as  CONFIG_STRICT_DEVMEM=n. This is a security reasons.


text:
Q: Why multiplying the elements in first column of a matrix by k multiplies the determinant by k My book asks:

Explain in terms of volumes why multiplying all the elements in the
  first column by constant $k$ multiplies the value of the determinant
  by $k$ of $(a\space b\space c)$.

To which the answer is:

Stretching factor by $k$ in one direction only multiplies volume by
  $k$.

So to test it out I carried out:
$\begin{pmatrix}
    ka_1 & b_1 & c_1 \\
    ka_2 & b_2 & c_2 \\
    ka_3 & b_3 & c_3 \\
\end{pmatrix}
\begin{pmatrix}
    y \\
    x \\
    z \\
\end{pmatrix}
= \begin{pmatrix}
    ka_1x+b_1y+c_1z \\
    ka_2x+b_2y+c_2z \\
    ka_3x+b_3y+c_3z \\
\end{pmatrix}$
Which to me (probably interpretation it wrong) seems to be a small increase in all directions relative to $kx$ which i believe would still increase the determinant by $k$ but doesn't really fit into the answer they've given me, i can't see any broken logic in my reasoning so would appreciate any help understanding my error.

A: If you have a parallelepiped $\mathcal{P}$, and double just one side - like taking two copies of $\mathcal{P}$ - what happens to the volume?


text:
Q: $emit generates an error when using testacular (karma) This is most likely me not knowing exactly how to use Karma. Say I have an angularJS boilerplate test like so

'use strict';

describe('Controller: MainCtrl', function () {

  // load the controller's module
  beforeEach(module('testingApp'));

  var MainCtrl,
    scope;

  // Initialize the controller and a mock scope
  beforeEach(inject(function ($controller) {
    scope = {};
    MainCtrl = $controller('MainCtrl', {
      $scope: scope
    });
  }));

  it('should attach a list of awesomeThings to the scope', function () {
    expect(scope.awesomeThings.length).toBe(3);
  });
});

if I insert an $emit in my Controller like so

'use strict';

angular.module('testingApp')
  .controller('MainCtrl', function ($scope) {
    $scope.awesomeThings = [
      'HTML5 Boilerplate',
      'AngularJS',
      'Karma'
    ];

    $scope.$emit('helloWorld');
  });

My test now fails and says
TypeError: Object # has no method '$emit'Any help is much appreciated!

A: Instead of providing empty object as scope, use:
$scope = $rootScope.$new()

So your code would be:
// Initialize the controller and a mock scope
  beforeEach(inject(function ($controller) {
    scope = $rootScope.$new();
    MainCtrl = $controller('MainCtrl', {
      $scope: scope
    });
  }));


text:
Q: Flutter App stuck at "Running Gradle task 'assembleDebug'... " When I run the app it get stuck
Launching lib\main.dart on Lenovo A319 in debug mode...
Running Gradle task 'assembleDebug'...
(This is taking an unexpectedly long time.)

It never initialize Gradle nor the dependencies

A: In my case, Windows Firewall was causing this problem. After I disabled it temporarily the problem was gone. Worth giving it a try. Good luck!

A: For me what worked was clean wipe the emulator data by AVD Manager

A: There were two reasons for me on Archlinux:

*

*I needed to unset TERM which was set to xterm-256color (reference).

*For some reason, flutter stable was not working for me; so I switched to master with: flutter channel master && flutter upgrade. I'll be able to switch back to flutter stable when the fix in master makes its way into stable (reference).

A: This worked for me.I got an issue with license acceptance.
First you need to go through the flutter directory and then run the command
C:\Users\thrishool\flutterProjects\flutter>flutter doctor

Then it will display if everything is fine or not.I got an issue that, I didnot accept all the licenses.So you need to accept them all.Now type this in cmd
C:\Users\thrishool\flutterProjects\flutter>flutter doctor --android-licenses

Accept all the licenses and you are good to go.

A: For me simply the process took too much time. It kept running for about 10 mins and finally the app started running.

A: This problem occurred on my system because of the Zen Kernel.
I installed the Linux-LTS kernel and started system using this.
Then my project backed to compile again.

A: I used the command "flutter clean" in my project and it returned to work perfectly, please try.
Igual a imagem
flutter clean

A: This is likely one of number of issues and some of the recommended troubleshooting can be found here.

*

*Check that you are building against an Android sdk that you have
installed... in your build.gradle file check the compileSdkVersion.

*You can try uninstalling and reinstalling the relevant SDK.

*Some users have reported that they had to resintall Dart.
Without a little more information basic troubleshooting is the best we can offer sorry.
Good luck.

A: For creating an apk for Android in Flutter this issue sometimes happens. I had the luck of facing this issue as well. Here are the few ways it can be solved:
1. Due to androidX

If you followed recommended route from here:
https://flutter.dev/docs/development/packages-and-plugins/androidx-compatibility
Try this:
Check with steps in "not recommended" way in above tutorial if every listed files is same as in your project, especially :
in root/android/gradle/wrapper/gradle-wrapper.properties set distributionUrl=https\://services.gradle.org/distributions/gradle-4.10.2-all.zip

in root/android/build.gradle, set
dependencies { classpath 'com.android.tools.build:gradle:3.3.2' }
check if root/android/app/build.gradle SDK version is set to minimum 28 for:
compileSdkVersion 28 and targetSdkVersion 28
Thank you.

A: In Android Studio:
Tools -> Flutter -> Flutter clean.
After that just run the app

A: I stumbled on this problem when I was running my app without debugging it. Theres two option

*

*Start Debugging

*Run without Debugging

I was doing the second option the whole time which got me stuck in that running graddle loop. I fixed my problem with the first option.

A: Here is solution in my case.

*

*Open your flutter Project directory.

*Change directory to android directory in your flutter project directory cd android

*clean gradle ./gradlew clean

*Build gradle ./gradlew build or you can combine both commands with just ./gradlew clean build

*Now run your flutter project. If you use vscode, press F5. First time gradle running assembleDebug will take time.

PS: Delete gradle in case of all that steps don't work

A: If you are on Windows:
try adding firewall exceptions to your Android Studio.

*

*Go to:

Control Panel\System and Security\Windows Defender Firewall\Allowed apps

*Hit the button:

Allow another app

*Add your new firewall exceptions:

studio.exe and studio64.exe

I hope this can be useful for you too.

A: If Running Gradle task assembledebug is taking unexpectedly long time,
try updating Gradle in your project. (Downloading latest zip file)
You can follow steps in this answer.
Or try by:

*

*Open a project in Android Studio

*Right-click on android in Projects Panel

*Go down to Flutter and click on the 'Open Android module in Android Studio'.

(See screenshot for reference)

This should open the project as an Android Project.

*Now, click on 'gradle' in the right panel.

*Next, click on 'Execute Gradle Task' icon

This should open a 'Run Anything' window.

*Now, Run the command  gradlew clean

*and, then run   gradlew build

*If prompted by Android Studio to 'Update Gradle Plugin', do that.

The update would download the required .zip files.
And, your apps should work fine after that.

A: flutter run -v showed that I was stuck on
Downloading https://services.gradle.org/distributions/gradle-5.6.2-all.zip
This was going to take hours, as for some reason the download speed was ~10kB/s on a decent DSL connection.
Solution:

*

*Interrupt gradle build

*Download the required gradle zip from a fast mirror. e.g.   https://distfiles.macports.org/gradle/gradle-5.6.2-all.zip

*Copy gradle-5.6.2-all.zip to C:\Users\ <MyUsername>\.gradle\wrapper\dists\gradle-5.6.2-all\9st6wgf78h16so49nn74lgtbb (of course the last folder will have a different name on your PC)

*flutter run and voilà.

A: I am using VS Code on Ubuntu 18.04
For me it was a background download of the appropriate android sdk build tools for my connected device. Running flutter run -v showed that it was downloading android SDK build tools which usually take some time. Once it was done, the flutter app compiled and ran successfully.
Solution

*

*Ensure you have installed android sdk tools and added them to the environment path.
I assume you have downloaded android sdk tools.

*Ensure you have installed gradle and added it to the path

*Ensure you have installed latest dart and flutter sdks
For no 1 and 2 please refer to this post:
Setting up flutter without Android studio

A: Had the same issue because of the wrong compileSdkVersion in the build.gradle file.
Working fine now.

A: In my case I forgot to download Google Web Driver.
It's running once I downloaded Google Web Driver.

A: It is taking time on windows 10 as the Android studio needs firewall permission to connect to the device(AVD).
There can be another reason that you don't have downloaded full Android SDK on your machine.
To check the issue simply run the command on your terminal/cmd/PowerShell command tool.
flutter doctorflutter doctor
check if SDK is installed or not.
Try to install and accept license using the following command
flutter doctor --android-licenses
If this doesn't resolve your problem then go to android studio and Open your Android Studio,
File-> settings->System settings(left tab) ->Android SDK
,
go to
SDK Tool section
in that page,
untick hide obsolete packages,
select Android SDL tools(obsolete)
and press apply also install other useful tools according to your convenience.

A: This helped: check if root/android/app/build.gradle SDK version is set to minimum 28 for:
compileSdkVersion 28 and targetSdkVersion 28
Occurs with import of Firestore.

A: In my case the Android Gradle Plugin Version was not updated to any version at all. So i updated it by right clicking on my project folder, clicked "Open Module Settings" and updated gradle plugin version accordingly.

A: In my case, I need to update Android SDK built-tools.
Open in Android studio Tools->SDK Manager-SDK tools.
Mark Android SDK Built-Tools, press Apply, wait for the update.
After updated, press Apply and try to run.

A: I fixed the issue by switching off my antivirus while running my project in the terminal
To run your project in a terminal simply type --> flutter run

A: This worked for me:
C:\Users<user>\AndroidStudioProjects<flutter_app>\android> gradlew clean
C:\Users<user>\AndroidStudioProjects<flutter_app>\android> gradlew build
Now run it, for initial build
"Running Gradle task 'assembleDebug'… "

will take 10-12 mins after that it will be good to go.

A: *

*Download the required gradle zip from a fast mirror: https://distfiles.macports.org/gradle/gradle-5.6.2-all.zip

*Copy gradle-5.6.2-all.zip to C:\Users
.gradle\wrapper\dists\gradle-5.6.2-all\9st6wgf78h16so49nn74lgtbb
If this does not work, go to android studio's terminal then run:- flutter run.
See what SDK platform it's asking you. like SDK API 28, 29, or 30.
Then goto SDK manager and install the required SDK API. Then restart android studio.
It will work perfectly fine!!

A: The same problem occurred on my mac in Android Studio 4.1, unfortunately, I forgot to install Java on my machine, try installing Java.

A: nothing was working for me
I do update the flutter SDK & update all the dependencies to the latest version. after that, I open the android module as a project in android studio. It downloads some files. after completion, I do clean the project using Build->clean Project & update the Gradle version.
After that, I again open the flutter project and run the app. It's working now.... :)

A: This might also be due to developers permission, if you will be using any package which requires devices permission lets say url_launcher and you haven't given permission for that it wont run. Solution for windows is that just run ms-settings:developers this in your command prompt/ powershell and enable for developers option and then it will work fine.
and if that doesnt also works then just run flutter clean and flutter create . it will work.

A: How are you !,
After many attempts, nothing they recommended worked for me.
My problem was that I had * .dart files with many lines of code to perform SQL create and insert operations initially in SQLite, I removed those 4072 lines of operations, the file was reduced in size and I no longer had to compile a very code file long, instead, I preloaded the database into assets, and it worked flawlessly! ..
The message that the operation is taking a long time no longer appears, I hope it serves you.
Before, when long file size
After, without SQL code operations

A: I solved the issue by reinstalling SDK Platform on Android studio for Android API 29
Tools->SDK Manager-SDK Platform

Next go to
Android > app > build.gradle

Make sure you also change
compileSdkVersion 29

targetSdkVersion 29

Be patient, it take longer for the first launch...But, not take forever like before.
good luck

A: With my LG G6 I have the same issue.
It looks like the new versions of adb added some compatibility issues with some LG phones.
Downgrading to platform-tools version 28.0.0 solved the problem.
References:
https://superuser.com/questions/1357708/android-adb-logcat-works-only-on-shell/1357929#1357929
https://github.com/flutter/flutter/issues/18889#issuecomment-421432066

A: Finally i fixed it.
The problem is mostly due to android SDK or  gradle built tool
There are different ways you can try to fix it.
way 1. check whether google drivers are installed . you can find them in sdk manager of the android studio
way 2. flutter doctor -v
flutter doctor --android-licenses  (#this will check whether all the licenses of android are accepted)
way 3.  flutter clean;flutter build apk
flutter run    ( In the start it will take time for assembledeubg so kindly be patient for 7 to 10 mins)
way 4. If this also do not work
flutter clean
flutter run     (be patient and finally after 5 to 10 min your flutter code will run on the emulator)
Hope these solutions work for you, If not reply me back.

A: In my case installing JDK solved the problem.
macOS Catlina v10.15.4

A: Have you tried that from cli ?
flutter devices
flutter run
https://flutter.dev/docs/get-started/test-drive?tab=terminal
In a mac environment, the building process finished in 140s.

A: do flutter clean first
then copy your project folder somewhere else
close your project and open same project which is copied diffrent location.
thats it !!

A: If you already opened a project and create another new project, make sure that you update the Gradle file based on the already runnable project version. In my case, I already installed Gradle 5.6.4 on a previous project and when I create a new project, it was 5.6.2 in the Gradle wrapper file. So I updated it.

A: If Running Gradle task assembledebug is taking unexpectedly long time and if its not working even after checking the solutions mentioned in this article.
Just go and create new virtual device in AVD Manager. I hope this will definitely work for you.

A: In my case, the issue was, project_path contained "space".
Example:
~/New Folder/myProject

Check if you have this issue.

A: the problem is solved using following:

*

*in android studio tools--> sdk Manager --> android sdk--> sdk platforms. dowload android sdk platform 28

now re-run ur project

A: I fixed this with upgrading flutter version from 2.0.5 to 2.2.0.

A: Can run the flutter app in profile / release mode to launch the app quickly. Note: We suppose to relax the hot reload. mode details

A: if u are using windows 10,
open your project in the terminal, and write these commands:

*

*cd android

*gradlew clean

*gradlew build

then run the project.
Note: if u face a problem like no path for JAVA_HOME so set this path
C:\Program Files\Android\Android Studio\jre   in the environment variable.
and open project structure in android studio and set the same path in JDK path.

A: This solution should be working for some cases:
1 - Download Google Web Driver in Android SDK.
2 - Update Dart And Flutter in IntelliJ Idea or Android Studio or VS Code plugin.
3 - Run again.

A: I had the same challenge, meanwhile, doing flutter clean, flutter doctor, download gradle didn't help me and my issue stayed again. Finally the bellow steps rescued me from this trap.
1)Create a new flutter project(File--> new flutter project)
2)Transfer Lib, assets, font, pubspec.yaml, pubspec.lock
3)pub update in pubspec.yaml of new project
4) change the kotlin version to latest version like 1.5.10 in android/build.gradle path in new project.

At the end try to rebuild your project and solve the other tiny problems which maybe occur. For instance, in my project the mentioned steps help me precisely.

A: Had this issue today, every solution I found didn't work. In my case, I had to update Windows, after installing every update they listed and then restarting pc, the problem disappeared.

A: I had the same issue for almost half a day, so what I did :

*

*Go to my Home directory, enabled show hidden folders.

*Delete the .gradle folder.

*Went back to Android studio, opened the terminal, and ran the flutter run  command.

*After it completes, the app will be launched on your connected device.

Note: Make sure you have a strong internet connection because gradle files are going to be re-downloaded.

Thank you, hope this one helps

A: for me, I just changed my proxy, while I have problem on sync gradle files on my country.

A: 1: If it is the first launch, please be patient since it will download all gradle files for the first time.
2: To know if it really stuck, take help from the task manager in windows or the activity monitor on Mac, and check if the process is really using some CPU or network or not. If not, it is stuck. If it is using some resources, please be patient then (it should take ~5-40 minutes normally, even if you have slower internet).
3: If it is really suck, stop the process and run ./gradlew clean before building it next time.

A: In my case I just restart my computer and it's fixed. Probably it's happening because of lack of some files while launching the app.

A: taskkill /F /IM dart.exe then flutter clean

A: Just connect with internet then disable your windows defender/firewall. It works for me.

A: On android studio go to file/invalidate caches/
For me this works


text:
Q: The sum of five positive numbers is $100$. Prove that there are two numbers among them whose difference is at most $10$. The sum of five positive numbers is $100$. Prove that there are two numbers among them whose difference is at most $10$.
attempt: Let $m,n,p,q,r$ be positive real numbers such that $m \leq n \leq p \leq q \leq r$. Then assume $m > 0, n > 10, p> 20, q > 30 , e > 40.$
Can anyone please suggest something ? Thank you

A: Assume all numbers have a difference that is bigger than $10$. Let these $5$ numbers be $a>b>c>d>e>0$. So we have $$a>b+10>c+20>d+30>e+40>40$$So, $$a>e+40, \quad b>e+30, \quad c>e+20, \quad d>e+10$$ So $$100=a+b+c+d+e>5e+100>100$$ Contradiction.

A: Let $x_2,x_2,\dots x_5$ be the numbers and assume by contradiction that $x_{i+1}>10+x_i$ for all $i$.
We have: $x_1>0, x_2> 10,x_3 > 20,x_4> 30,x_5>40\implies x_1+x_2+x_3+x_4+x_5>100$


text:
Q: Cocoon, Bootstrap_Form_For and PostgreSQL updating all fields but boolean check box I am using the Cocoon Gem with Bootstrap_Form_for in my rails 4 application. Everything is working and I have no problem creating and updating all of my fields except when I try to change an already set boolean field.
Below you will find my code, any and all help is much appreciated.
products_controller:
    def update
    respond_to do |format|
      if @product.update(product_params)
        format.html { redirect_to @product, notice: 'Product was successfully updated.' }
        format.json { render :show, status: :ok, location: @product }
      else
        format.html { render :edit }
        format.json { render json: @product.errors, status: :unprocessable_entity }
      end
    end
  end

categories_controller:
  def create
@category = Category.new(category_params)

respond_to do |format|
  if @category.save
    format.html { redirect_to hq_company_settings_path(:anchor => "productsTab"), notice: 'Category was successfully created.' }
    format.js { redirect_to hq_company_settings_path(:anchor => "productsTab") }
  else
    format.html { redirect_to hq_company_settings_path(:anchor => "productsTab") }
    format.json { render json: @category.errors, status: :unprocessable_entity }
  end
end

end
Category model:
belongs_to :company
has_many :products

accepts_nested_attributes_for :products, reject_if: :all_blank, allow_destroy: true

Form:

                        <%= bootstrap_form_for(@category) do |f| %>
                        <% if @category.errors.any? %>

<%= pluralize(@category.errors.count, "error") %> prohibited this category from being saved:

                                <% @category.errors.full_messages.each do |message| %>

<%= message %>

                                <% end %>

                        <% end %>
                        <fieldset>

                              <%= f.text_field :name, hide_label: true %>

                        </fieldset>

                                <fieldset id="products">
                                    <%= f.fields_for :products do |product| %>
                                    <%= render 'product_fields', :f => product %>
                                    <% end %>
                                </fieldset>

                                <%= link_to_add_association ' Add Product', f, :products, class:"btn-u btn-u-blue btn-block" %>

                                    <%= f.submit "Save", class:"btn-u btn-block" %>

                        <% end %>

Nested Cocoon form:

       <%= f.text_field :name, hide_label: true, placeholder: 'Product Name' %>

    <%= f.text_field :price, hide_label: true, placeholder: 'Price' %>

    <%= f.text_field :sku, hide_label: true, placeholder: 'SKU/ID #' %>

   <%= f.hidden_field :company_id, hide_label: true, value: current_user.company_id %>
   <%= f.form_group :tracking do %>
      <%= f.check_box :tracking, label: " Inventory Tracking", class: 'radio1 js-switch', name: 'my-checkbox', inline: true  %>
   <% end %>

      <%= f.text_field :inventory, hide_label: true, class: "txt1", placeholder: 'Quantity' %>

      <%= f.text_field :minimum, hide_label: true, class: "txt2", placeholder: 'Min. Quantity' %>

   <%= link_to_remove_association " Remove Product", f, class:"btn-u btn-u-red btn-block" %>

A: The problem occurred from giving my checkbox the "NAME" attribute for bootstrap switch.
Removing
name: 'my-checkbox'

From
<%= f.form_group :tracking do %>
  <%= f.check_box :tracking, label: " Inventory Tracking", class: 'radio1 js-switch', name: 'my-checkbox', inline: true  %>

ended up fixing my issue.


text:
Q: Параллельные insert/find у Splay дерева Здравствуйте, не могли бы вы мне подсказать как можно реализовать работу с одним и тем же Splay деревом на разных потоках?
Само дерево находится тут (код 200 строк классического дерева, потому я добавил ссылку на pastbin)
Проблема в том, что я не понимаю:
1)что у нас делает flush(в методе synch).
комментарий в коде:

   /*       * This function will be called as a "flush", with an intention
    * to remove inter-thread inconsistencies.       */

2)не могу представить как можно параллельно в разных потоках вставлять и искать в одном и том же Splay дереве элементы, оно же всегда перетягивает узлы в корень. Причем важно, чтобы параллельное Splay  дерево работало быстрее классического...
UPD:
Я уточнил ограничения задания. В проекте имеется main.cpp:
#include "splayset.hpp"
#include "stopwatch.hpp"
#include "rc4prng.hpp"

#include <iostream>
#include <cstdint>
#include <thread>

const size_t concurrency = 4,
             item_count = 200000,
             group_size = 100,
             group_accesses = 2000,
             group_count = 1000;

const char rand_seed[] = "test ukolu";

void test_group (rc4prng<>& rng, splayset<uint64_t>&st)
{
    uint64_t begin = rng.random(), mult = rng.random();
    for (size_t i = 0; i < group_accesses; ++i)
        st.find (begin + mult * rng.random (group_size));
}

int main()
{
    splayset<uint64_t> st;

    rc4prng<> thread_rng[concurrency];
    for (size_t tid = 0; tid < concurrency; ++tid)
        thread_rng[tid].load_key (rand_seed, rand_seed + 10 - tid); // :]

    std::thread thread[concurrency];
    bpp::Stopwatch stopwatch (true);

    for (size_t tid = 0; tid < concurrency; ++tid)
        thread[tid] = std::thread ([tid, &thread_rng, &st]() {
        for (size_t i = 0; i < item_count; ++i)
            st.insert (thread_rng[tid].random());
    });

    for (size_t tid = 0; tid < concurrency; ++tid)
        thread[tid].join();

    stopwatch.stop();
    std::cout << stopwatch.getMiliseconds() << std::endl;
    stopwatch.start();

    for (size_t tid = 0; tid < concurrency; ++tid)
        thread[tid] = std::thread ([tid, &thread_rng, &st]() {
        for (size_t grp = 0; grp < group_count; ++grp)
            test_group (thread_rng[tid], st);
    });

    for (size_t tid = 0; tid < concurrency; ++tid)
        thread[tid].join();

    stopwatch.stop();
    std::cout << stopwatch.getMiliseconds() << std::endl;
    return 0;
}

Менять я могу только код самого дерева(не main.cpp), а следовательно у меня нету возможности сделать worker который будет заниматься диспечированием потоков внешне.
Совет @avp с использованием scheduler мне понравился, но я не знаю как его реализовать, при возможности модификации только имеющегося у меня splayset.hpp.
Если брать во внимание мое дополнение, можно ли как-то решить данное задание хотя бы частично эффективно?
Я очень надеюсь на совет, ибо я в тупике.
Заранее спасибо.

A: Похоже, что конкретно этот код для  параллельной работы не годится.
Я бы подумал над модификацией с отложенным splay(), которая будет проводиться отдельным потоком, запускаемым при создании дерева (или в другой момент? вопрос открытый).
Для find() все довольно очевидно. Мы действительно можем, делая блокировку только на чтение, искать параллельно из нескольких потоков не мешая друг-другу. Данные о найденных каждым потоком несоответствиях в балансировке, для которых сейчас вызывается splay(), могут помещаться в очередь к потоку, который проводил бы балансировку отложено, т.е. когда запросов на поиск нет.
Если в том же духе посмотреть на insert(), то можно увидеть, что если узел не найден, то операция всегда выполняется с текущим листом, после чего вызывается splay() (т.е. ее можно тоже сделать отложенной и выполнять в том же потоке, что делает splay при поиске.)
Выполнение erase() (точнее ее части после find()) можно сделать аналогично.
Таким образом, вырисовывается архитектура с отдельным потоком модификации дерева, который берет запросы из очереди и выполняет их, установив монопольную блокировку всего дерева. Очевидно, что запросы insert и erase, начавшиеся с read-only блокировкой, поместив свои данные в очередь, должны эту блокировку снять и ждать завершения инициированной операции (вероятно, вместе со своим запросом они должны передавать condition variable, сигнала на которой (я говорю в терминах pthreads) они и будут дожидаться).
Возможно понадобится отдельный алгоритм оптимизации очереди запросов к "splay-потоку" (это отдельный вопрос, который придется тщательно продумать).
Еще один открытый вопрос тут, это алгоритм диспетчирования, который должен балансировать нагрузку между read-only потоками и "splay-потоком". Т.е. если в очереди накопилось достаточно данных и достаточно много потоков (insert/erase операции) ждут, то видимо надо приостановить поступление новых read-only операций к дереву.
А вот возможен ли прирост производительности при реализации такого плана?
 Если честно, не уверен. Возможно, для большого дерева с преобладанием запросов на успешный поиск выигрыш и будет.
Update
Утро вечера мудренее...
В самом деле мы можем не заморачиваться с созданием реального "splay-потока". Эту работу может выполнять любой существующий поток перед выходом из функций поиска-обновления.
Т.е. вызвав splay() можно либо добавить свои данные в очередь отложенных действий, либо, обнаружив, что как раз настал момент выполнять все эти действия, выполнить их в рамках этого потока. Естественно, поток должен обеспечить все необходимые блокировки и дождаться завершения работы с деревом другими потоками.
Возможно, для практики более подходит ограниченный подход к параллелизму. Операции модификации всегда выполняем с монопольной блокировкой, а поиск реализует отложенный splay.
Дополнительно, ту же очередь отложенных действий (в реальности это может быть массив  из десятка элементов) можно использовать и как кэш, проводя сначала последовательный поиск в ней.


text:
Q: Why have memory initialization rules changed in .Net 4.5? Updating some of my code samples for a training I've noticed that some local memory that was previously kept uninitialized by the CLR is now being zeroed.
Here is a small CIL sample that shows the "issue":
.assembly Test{}

.assembly extern mscorlib{}

.class S extends [mscorlib]System.ValueType
{
    .field public int32 n;
}

.method static void F()
{
    .locals (int32, valuetype S)

    ldloc 0
    call void [mscorlib]System.Console::WriteLine(int32)

    ldloca 1
    ldfld int32 S::n
    call void [mscorlib]System.Console::WriteLine(int32)

    ret
}

.method static void Main()
{
    .entrypoint

    .locals (int32, valuetype S)

    ldloc 0
    call void [mscorlib]System.Console::WriteLine(int32)

    ldloca 1
    ldfld int32 S::n
    call void [mscorlib]System.Console::WriteLine(int32)

    call void F()

    ret
}

And here are the outputs:

*

*.Net 2.0 (and I'm almost sure it was the same with .Net 4.0):
$ /Windows/Microsoft.NET/Framework/v2.0.50727/ilasm.exe Test.il

Microsoft (R) .NET Framework IL Assembler.  Version 2.0.50727.5420
Copyright (c) Microsoft Corporation.  All rights reserved.
Assembling 'Test.il'  to EXE --> 'Test.exe'
Source file is ANSI

Assembled global method F
Assembled global method Main
Creating PE file

Emitting classes:
Class 1:        S

Emitting fields and methods:
Global  Methods: 2;
Class 1 Fields: 1;
Resolving local member refs: 3 -> 3 defs, 0 refs, 0 unresolved

Emitting events and properties:
Global
Class 1
Resolving local member refs: 0 -> 0 defs, 0 refs, 0 unresolved
Writing PE file
Operation completed successfully
Test.il(6) : warning -- Non-sealed value class, made sealed

$ ./Test.exe
211384
0
2157704
2157328

*.Net 4.5:
$ /Windows/Microsoft.NET/Framework/v4.0.30319/ilasm.exe Test.il

Microsoft (R) .NET Framework IL Assembler.  Version 4.0.30319.17929
Copyright (c) Microsoft Corporation.  All rights reserved.
Assembling 'Test.il'  to EXE --> 'Test.exe'
Source file is ANSI

Assembled global method F
Assembled global method Main
Creating PE file

Emitting classes:
Class 1:        S

Emitting fields and methods:
Global  Methods: 2;
Class 1 Fields: 1;
Resolving local member refs: 3 -> 3 defs, 0 refs, 0 unresolved

Emitting events and properties:
Global
Class 1
Resolving local member refs: 0 -> 0 defs, 0 refs, 0 unresolved
Writing PE file
Operation completed successfully
Test.il(6) : warning : Non-sealed value class, made sealed

$ ./Test.exe
0
0
0
0

I'm curious about the rationales behind this implementation change.
So any feedback, especially from insiders, or reference to any articles or, better, to a specification, is welcome. :)
Thanks in advance.

A: This is just a coincidence, nothing clears your locals intentionally. Jitter tries to keep your locals in registers, it doesn't even allocate stack space if it is not necessary. Your program is tiny, and when you don't compile it with /32bitpreferred flag, the odds are good that it chooses a register for your local, which hasn't been used before on the current thread, and still has zero value. You can get back your garbage when you:

*

*compile the code with /32bitpreferred flag. 32 bit code has less registers, so your locals might be stored on the dirty stack or in a dirty register.

*create more fields for your value type, or use more locals, so they will not fit in the register set, or the jitter doesn't choose to store them there.

*do something more in your methods what involves registers

I am not sure why you need to make more effort to find uninitialized values in version 4.5 compared to previous versions. Maybe this is a side effect of some changes in the jitter, but I am just guessing. The point is that you still need the init flag on your locals to ensure they get zero initial value.


text:
Q: My kernel crashes whenever I attempt to iterate through a dataloader My code below runs until I attempt to view the images. Can anyone see why my kernel is crashing?
transform = transforms.Compose([transforms.Resize(255),
                               transforms.ToTensor()
                               ])

train_dataset = datasets.ImageFolder(train_path, transform= transform)

train_dataloader = torch.utils.data.DataLoader(train_dataset, batch_size= 32, shuffle= True)

for images, labels in train_dataloader:
    plt.imshow(images[0], normalize= False)

error message is
Canceled future for execute_request message before replies were done


text:
Q: Series of Maximal Operator Let $p\in(1,\infty)$. Assume that we have a sequence of functions $\{f_i:i\in\mathbb{N}\}\subset L^p(\mathbb{R}^n)$ such that
$$
\left(\sum\limits_{i=1}^\infty|f_i|^2\right)^{\frac{1}{2}}\in L^p(\mathbb{R}^n)\qquad
\{\mu (f_i):i\in\mathbb{N}\}\subset L^p(\mathbb{R}^n)
$$
I want to prove that
$$
\left\Vert\left(\sum\limits_{i=1}^\infty|\mu(f_i)|^2\right)^{\frac{1}{2}}\right\Vert_p \leq A_p\left\Vert\left(\sum\limits_{i=1}^\infty|f_i|^2\right)^{\frac{1}{2}}\right\Vert_p
$$
Here we can assume that $\mu$ is the Hardy-Littlewood's maximal operator (centered or non-centered).


text:
Q: How To Structure Array Into UITableView? I have an array with the following format:
[NSArray arrayWithObjects:
 [NSArray arrayWithObjects:@"number",@"name",@"date",@"about",nil],
 [NSArray arrayWithObjects:@"number",@"name",@"date",@"about",nil],
 [NSArray arrayWithObjects:@"number",@"name",@"date",@"about",nil],
 [NSArray arrayWithObjects:@"number",@"name",@"date",@"about",nil],
 nil];

I want to structure this data to load into my tableView.
Each row of the tableview should correspond to each row of the array, then the title of each cell should correspond to the subarray objectAtIndex 2 for the name.

A: Suppose your array is named myData:
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
  // Return the number of sections.
  return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
  // Return the number of rows in the section.
  return [myData count];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
  static NSString *CellIdentifier = @"Cell";

  UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
  if (cell == nil) {
      cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
  }

  // Configure the cell...
  NSArray *obj = [myData objectAtIndex:indexPath.row];
  cell.textLabel.text = (NSString*)[obj objectAtIndex:1]; //note: 0=>number; 1=>name,..

  return cell;
}

In favor of reusability, I would suggest to replace the subarrays with NSDictionaries so that you can get e.g. the name by calling [dict objectForKey:@"name"].


text:
Q: Is $\sum_{j=0}^\infty \frac{x}{(1+x^2)^j}$ pointwise convergent or uniform convergent? My initial thoughts for this question was to find the Chebyshev norm of $f_j(x) = \frac{x}{(1+x^2)^j}$. Doing this I get $\vert\vert f_j \vert\vert _\infty = 1$. Does this mean that the series is pointwise convergent to the constant function 1 and how would I go from here to determine whether it is uniformly convergent?

A: Note that $x$ is a constante here, with respect to $j$. Therefore\begin{align}\sum_{j=0}^\infty\frac x{(1+x^2)^j}&=x\sum_{j=0}^\infty\left(\frac1{1+x^2}\right)^j\\&=\frac x{1-\frac1{1+x^2}}\\&=\frac{x+x^3}{x^2}\\&=x+\frac1x,\end{align}unless $x=0$, in which case the sum is $0$, of course. Since the sum is discontinuous but each function is continuous, the convergence cannot be uniform.


text:
Q: Designing a PI controller for my power system I have a power system which is given as:

Using MATLAB, I found the system's response to be:

As you can see, the system is not stable.  So, I need to design a PI controller, so that, the transient performance of the \$\ p(s) \$ can be improved.
Therefore, my new system will be:

Please, know that:

*

*\$\ P(s) = C [sI-A]^{-1} B \$

*\$\ \Delta  x ' = A \Delta x + B u \$

*\$\ Y= C \Delta  x \$

Since we are dealing with a real power plant system, we should consider the input equations to be non-linear. Just for calculation purposes, let us assume that:
\$\ \Delta  x = [\Delta  \delta, \Delta  \omega. \Delta e_q' , \Delta E_d ] ^T \$
Let the angular speed of the rotor ω to be our input. (Just to make everything easier)
Therefor, C= [0 1 0 0]
Where ω can be defined as:
\$ ω' = \frac{1}{M} (P_M - P_E - D(ω-ω_0))\$
Please, know that all of these values are arbitrary, except for ω. (These values will be given to me later by the manufacturer of P(s))
Anyhow, I tried to find \$\ K_I \$ and \$\ K_P \$ using the above equations. So, after using Laplace transforms and many other calculations, I reached to the point where
\$\ H(\lambda)= \frac{\lambda T_W}{1+ \lambda T_W} (K_P + \frac{K_I}{\lambda}) \$
The question is:
What are the best values for \$\ K_I \$ and \$\ K_P\$ so that my power system is stable? And how can I know that?

A: I suppose you don't have the P(s) transfer function. It can be an academic problem or an exercise over a real plant which an unknown model, but at least you should know WHAT INPUT makes P(s) to have that output. Is it an impulse, a step, a sine?
Lacking mathematical knowledge, you can follow some empirical rules, well spread in the industrial field, google for "ziegler nichols tuning method" or begin here.


text:
Q: Demo response different from runtime response I'm trying to use the Google Cloud Vision API to OCR this image:

I'm using the following code the make the request:
const resp = await fetch(
  `https://vision.googleapis.com/v1/images:annotate?key=${KEY}`, {
    method: 'POST',
    body: JSON.stringify({
      requests: [{
        image: {content: encoded},
        features: [{type: "TEXT_DETECTION"}],
      }]
    }),
});

This works but there is some information missing from the result. If we look at the text field:
Dog Search
D G O OD D ODG O O D D O
O D O O G G G D O D G OG G
OGD GOGD GO G GO G D
D D D G D DO DOO G D O O
O DGOGG D O O G G O O D
DOG

Here's that visualized:

There are boxes around the characters which were recognized. But, if we put this image into the gcv demo application, we get this instead:

And this is what text looks like:
Dog Search
D GOOD D 0 D GOOD DO
0 D 0 0 G G G DOD GO GG
o G O G D 0 0 D G 0 0 D D D
D G D o o o G G o o G D Go
0 G D G O G D G O G G O G D
D D D G D DO DO O G D 0 0
O D GO G G D 0 0 G G 0 0 D
DOG

Here's a gist with the requests + responses. I'm authenticating using a API token.
Why are the responses different? The requests are slightly different but not in a way which should affect the output. Right?


text:
Q: Using thmbox's title with lyx Hello
I'm trying to create my own layout
I'm using thmbox package for theorems, and I want to use the title feature.
I'm using LyX  as my editor, and I've created a layout file defining several styles using newboxtheorem-s. is there any way to make lyx understand that the layout takes a parameter and create a wysiwyg environment for it?
Thanks.

A: I've solved the problem long ago,
Just needed to add:
OptionalArgs 1
to the Style Theorem scope.


text:
Q: How to put variable in a href on the vue js 2? When I run this : {{nextPage}}
The result
http://chelseashop.dev/search-result?page=2
But when I put in a href like this :
<template>

            ...

                    »

</template>

There exist error like this :

template syntax error - invalid expression: :href="{{nextPage}}"

How can I solve the error?

A: v-bind expressions are directly executed as JavaScript. As such, they do not require interpolation.
You simply want

See Template Syntax - Attributes

Mustaches cannot be used inside HTML attributes, instead use a v-bind directive


text:
Q: Removing specific files recursively using rm or something simple? I have a root folder with a text file in it called pairs.txt.
Within that root folder are other folders with text files called pairs.txt in them.
Is there a simple way to remove them using rm?
I know that there I could use find . -name 'pairs.txt' -exec rm {} \; but I would like to know of other ways, perhaps using * or some other wildcard?
I tried using rm -rf pairs.txt but it seems to only remove the pairs.txt in the current directory.

A: With bash 4+:
shopt -s globstar dotglob
rm -- **/pairs.txt

The globstar option makes ** match any number of directory levels. The dotglob option makes it include directories whose name begins with . (dot files).
With ksh93, use set -o globstar instead of shopt -s globstar. To get the effect of dotglob, use FIGNORE=.
With zsh, use the second line directly. To include dot files, run setopt glob_dots first or make the second line rm -- **/pairs.txt(D).
Note that bash's ** follows symbolic links to directories. Ksh's and zsh's don't.

A: ls -1R / | grep -e "/pairs.txt$" | xargs rm


text:
Q: How to create multiple new symbolic links using apache ant from a fileset? The symlink task in ant either create a single, record existing, recreate existing, or delete a single symbolic link.  I want to create symbolic links to all the files within a given directory within a different directory.

A: The simplest way to achieve it (in terms of coding) is with the help of antcontrib's For task
<for param="file">
  <path>
    <fileset dir="${src.dir}" includes="*"/>
  </path>
  <sequential>

    <basename property="@{file}.basename" file="@{file}">
    <symlink link="${dest.dir}/${@{file}.basename}" resource="@{file}"/>
  </sequential>
</for>

If you don't want the dependency on ant-contrib, you may try the following (Note: I did not test it at all):

*

*Create a couple of links manually in
${dest.dir}.

*Run
in ${dest.dir}.

Now you have a template properties file that you will recreate with your build instructions:
<pathconvert pathsep="${line.separator}" property="file.list">
  <fileset dir="${src.dir}" includes="*"/>
</pathconvert>
<echo message="${file.list}" file="${file-list.file}" append="false"/>

Now massage the file with regexp filter
<copy file="${file-list.file}" tofile="${dest-dir}/.link.properties">
  <filterchain>
    <tokenfilter>
      <!-- I leave regex as an exercise to the reader -->
      <replaceregex pattern="..." replace="..." flags="..."/>
    </tokenfilter>
  </filterchain>
</copy>

Finally do symlink-recreate.
<symlink action="recreate">
  <fileset dir="${dest.dir}" includes=".link.properties"/>
</symlink>


text:
Q: ReferenceError: Error #1056 - instance name Error I got a Problem with a Movie Clip I add to the Stage in Flash CS4/AS3.
The Flash File consist of two MovieClips, "Inside" and "Outside". The "Inside" Clip is contained by the Outside and has the Instance Name "insideClip". The Clips are attached to Actionscript Class-Files of the same names (Outside and Inside) which are "empty" - they don't do anything, like the ones flash automatically creates.
Adding "Outside" to stage I get the following Error:
ReferenceError: Error #1056: property insideClip in Outside can not be created.
at flash.display::Sprite/constructChildren()
at flash.display::Sprite()
at flash.display::MovieClip()
at gui::Outside()
at MyDocumentClass()

I always have trouble to get to know what Flash and Actionscript actually does behind the scenes - is there any good general ressource which is recommended?
PS.: The code was translated from a version in german -- in case I missed a variable name in the translation.
Code:
DOCUMENT CLASS:
package
{
import flash.display.Sprite;
import flash.display.MovieClip;
import gui.Outside;

public class MyDocumentClass extends MovieClip
{
    public var aussen:MovieClip;
    public function SelfDeclaredClips()
    {   outside = new Outside();
        outside.y = 100;
        outside.x = 100;
        addChild(outside);}}}

OUTSIDE CLASS:
package gui
{

import flash.display.MovieClip;

public class Outside extends MovieClip
{public function Outside(){}}
}

INSIDE CLASS:
package gui
{

import flash.display.MovieClip;

public class Inside extends MovieClip
{public function Inside(){}}
}

A: This error occurs when you uncheck the "Declare Stage Instances Automatically" checkbox in the "ActionScript 3.0 Settings" dialogbox and proceed to declare stage instances as private variables in the class associated with the containing MovieClip.
You cannot choose to simply always declare stage instances automatically without forging the use of inheritance in classes linked to MovieClip Symbols. If you have a class APrime which is derived from class A and APrime is linked to a MovieClip Symbol, all stage instances used in the base class A must be manually declared in class A.
OR
AS3 error 1056 appears when you have improperly referenced a property of an object. This will happen when you misspell something or when you reference variables in the AS2 fashion with a leading underscore ( _ ). AS3 error 1056 is actually pretty nice to work with because it tells you exactly what variable didn't work and it tells you which object it didn't work on.
You can also get this error if you try to dynamically assign a variable to an object that doesn't naturally accept one like a textField.

A: Try to declare a public var corresponding to the name of your inside clip into you outside clip:
package gui
{
 import flash.display.MovieClip;

 public class Outside extends MovieClip
 {
  public var insideClip:MovieClip; // here your declaration so the compiler can find it

  public function Outside(){}
 }
}


text:
Q: How to create an HTML table with JQuery from an array of column values How to create an HTML table using JavaScript and JQuery from an array of column
values in arrays when the dimensions of the table are unknown and the number of cells is not the same in each column. Eg.
[["1","4","7","10"],["2","5","8"],["3","6","9","11","12"]]
Must become:
+----+----+----+
|  1 |  2 |  3 |
+----+----+----+
|  4 |  5 |  6 |
+----+----+----+
|  7 |  8 |  9 |
+----+----+----+
| 10 |    | 12 |
+----+----+----+
|    |    | 11 |
+----+----+----+

A: $(function () {
    var cols = [["1","4","7","10"],["2","5","8"],["3","6","9","11","12"]];
    var rows = [];
    for (var y = 0; y < cols.length; y++) {
        for (var x = 0; x < cols[y].length; x++ ) {
            if (rows.length < x + 1) {
                rows.push([]);
                while (rows[x].length < y + 1) {
                    rows[x].push("");
                }
            }
            rows[x][y] = cols[y][x];
        }
    }
    var table_elem = $("

");
    for (var x = 0; x < rows.length; x++) {
        while (rows[x].length < cols.length) {
            rows[x].push("");
        }
        var row_elem = $("

");
        for (var y = 0; y < rows[x].length; y++) {
            var cell_elem = $("	");
            if (rows[x][y] != "") {
                cell_elem.text(rows[x][y]);
            } else {
                cell_elem.html(" ");
            }
            row_elem.append(cell_elem);
        }
        table_elem.append(row_elem);
    }
    $("body").append(table_elem);
});

A: Maybe you like this one:
        var cols = [["1","4","7","10"],["2","5","8"],["3","6","9","11","12"]];

        function mkTable(cols) {
            var table = $("

");

            for(var y=0;;y++) {
                var row = $("

");
                var cols_left = 0;
                for(i in cols) {
                    var col = cols[i];
                    var date = $('');
                    if(col.length > y) {
                        date.append(col[y]);
                        cols_left++;
                    }
                    row.append(date);
                }
                if(!cols_left)
                    break;
                table.append(row);
            }

            $('body').append(table);
        }


text:
Q: UPDATE statement and WITH clause I want to update my table using WITH clause.
I was trying:
UPDATE mytable
SET myfield = (
   WITH sub AS (SELECT 18)
   SELECT CASE WHEN (sub = 18) THEN 100 ELSE 0 END)

and
WITH sub AS (SELECT 18)
UPDATE mytable
SET myfield = (
   SELECT CASE WHEN (sub = 18) THEN 100 ELSE 0 END)

But it does not work. Please explain to me what I'm doing wrong.

A: your sub is recordset, not column. This one will work:
with sub(col) as (select 18)
update mytable set
   myfield = (select case when col = 18 then 100 else 0 end from sub)

But it'll update all rows in mytable with 100. Don't know what do you want to do with your query, so can't be more precise.

A: UPDATE mytable
SET myfield = (
   WITH sub AS (SELECT 18 AS field)
   SELECT CASE WHEN (field = 18) THEN 100 ELSE 0 END
   FROM sub)

A: The WITH clause defines a "common table expression", and is treated as a table in subsequent queries. So, you still need to reference the common table expression name in the subsequent query just as you would a table, and I find it more clear to prefix the CTE name with cte_ just to make it clear in a complex expression what the source of the data is.
update mytable
set    myfield = (
         with cte_sub as
           (select 18 as field)
         select case field
                  when 18 then 100
                  else 0
                end
         from cte_sub)


text:
Q: Count order lines by condition and calculate the percentage to total lines Experts,
Please let me know how to write the code in ABAP to implement the following logic?
From the below screenshot, for each "S_ORD_ITM", I have to determine if Order_Qty = Dlv_Qty. If yes, determine the total count of S_ORD_ITM for which Order_Qty = Dlv_Qty. In this example, for all 6 rows of S_ORD_ITM, Order_Qty = Dlv_Qty. So, this value would be 6. Lets says this as 'X' Next step is to find the total record count of S_ORD_ITM column. It is also 6 in this case. Lets says this as 'Y'.
My result should be [X/Y]*100.
In some cases, there could be total of 18 S_ORD_ITM, out of which only there exists only 6 records of S_ORD_ITM for which Ord_Qty = Dlv_Qty. So, my result would be [6/18]*100 = 33.33%
This logic has to be implemented for delivery numbers which have a first pass indicator as 'X'. Imagine this sales order has many delivery numbers, and the delivery number in this example is a first pass indicator with 'X'. I already have a loop statement in my end routine, that says
LOOP AT RESULT PACKAGE ASSIGNING RESULT FIELDS WHERE /BIC/FIRSTPASS = 'X'.
Please let me know how I can make use of this already available loop statement and implement the above logic.
Thanks a ton,
G.

A: UPDATE:
Hello Goutham,
You can solve the whole thing a lot easier. You just need to make a data flow from your DSO where the order data is, then you do a lookup. with that you loop through your result data and push just the extracted, aggregated rows in a new DSO. First build the target structure and the DSO and then use an expert routine / end routine with an abap coding like i described.
END UPDATE
so the Structure is like
sales_order, plant, shipping_point, delivery_number, s_ord_itm, ord_qty, dlv_qty
in your result package variable. is that correct? without a screenshot it is very hard to know what you mean, do you mean a SAP BW transformation or just ABAP code?
you could add some helper-variables to your structure or do it in the loop, i prefer doing it in the loop. but first you have to sort your result package!
your coding should be something like this (pseudo code) where your x variable is v_counter_ord_itm and v_counter_ord_dlv is your y:
make some data definitions like
WA_RESULT.../END OF...  (build a workarea for sales_order, result)
T_RESULT (make an itab out of workarea)
WA (workarea with sales_order, counter_ord_itm, counter_ord_dlv)

PSEUDO-CODE!!!

SORT RESULT_PACKAGE BY /BIC/SALES_ORDER
WA-SALES_ORDER = 0.
WA-COUNTER_ORD_ITM = 0
WA-COUNTER_ORD_DLV = 0
LOOP AT RESULT PACKAGE ASSIGNING RESULT FIELDS WHERE /BIC/FIRSTPASS = 'X'.
  IF WA-SALES_ORDER NE /BIC/SALES_ORDER.
    IF WA-SALES_ORDER NE 0.
      WA_RESULT-RESULT = WA-COUNTER_ORD_DLV / WA-COUNTER_ORD_ITM * 100.
      WA_RESULT-SALES_ORDER = WA-SALES_ORDER.
      APPEND WA_RESULT TO T_RESULT.
      CLEAR WA, WA_RESULT.
    ENDIF.
    WA-SALES_ORDER = /BIC/SALES_ORDER.
  ENDIF.
  WA-COUNTER_ORD_ITM = WA-COUNTER_ORD_ITM + 1.
  IF result_fields-ord_qty EQ result_fields-dlv_qty.
    WA-COUNTER_ORD_DLV = WA-COUNTER_ORD_DLV + 1.
  ENDIF.
ENDLOOP.

then you have the variables in your itab. for usage within data processing in sap bw, do another loop with a lookup to push the result data in a new field "result" (you have to add it in the output structure):
LOOP AT RESULT_PACKAGE ...
  LOOP AT IT_RESULT ASSIGNING <z>
   WHERE /BIC/SALES_ORDER = <z>-SALES_ORDER.
  RESULT_PACKAGE-RESULT = <z>-RESULT.
ENDLOOP

A: This is the code that I used:

 SELECT doc_number plant ship_point dsdel_date s_ord_item deliv_numb /bic/zlord_qty /bic/zldlv_qty
   INTO CORRESPONDING FIELDS OF TABLE it_doc_table
   FROM /bic/azord_dso00.

 SELECT doc_number COUNT( DISTINCT s_ord_item ) AS numr
   FROM /bic/azsd_o11000
   INTO CORRESPONDING FIELDS OF TABLE it_count_table
  GROUP BY doc_number.

READ TABLE lt_min_flag WITH KEY doc_number = source_fields-doc_number
                                plant =  source_fields-plant
                                ship_point   = source_fields-ship_point
                                deliv_numb =  source_fields-deliv_numb
                                dsdel_date = source_fields-dsdel_date
                       INTO lt_min_flag_wa
                       BINARY SEARCH.

CHECK sy-subrc = 0. CLEAR result.

IT_DOC_TABLE = VALUE /bic/azord_dso00( FOR ls_doc IN  it_doc_table WHERE ( doc_number = source_fields-doc_number AND plant = source_fields-plant AND ship_point = source_fields-ship_point AND deliv_numb = source_fields-deliv_numb AND dsdel_date = source_fields-dsdel_date AND /bic/zlord_qty = /bic/zldlv_qty ) ( ls_doc ) ).
z_numr = lines( it_doc_table ).
READ TABLE it_count_table INTO wa_count_table WITH KEY doc_number = source_fields-doc_number.

IF sy-subrc = 0 AND wa_count_table-numr <> 0.
 result = ( z_numr / wa_count_table-numr ) * 100 .
ENDIF.


text:
Q: GLEW not initialising; Throws up "Missing OpenGL Version" I am attempting to initialize an OpenGL context on an SDL_Window.
Problem is, when I try to execute glewInit(), it fails to initialize and gives the error message "Missing OpenGL version."
I have poked around on Google, and it seems that this error either comes up when the OpenGL context is not initialized or, more specifically for SDL, when the context is not made current by SDL_GL_MakeCurrent.
It is worth mentioning that the SDL/OpenGL objects in use here(gi_window, gi_glcontext) are public variables in a the GameInstance class.
My OpenGL version is 3.0, my SDL version 2.0.3, and my GLEW version is 1.10-2.
The system in use is 64bit Arch Linux(and as such the 64bit version of the aforementioned libraries are installed).
The initialization code
#include "../headers/init.h"

GameInstance::GameInstance(int p_fps, int p_height, int p_width, const char* p_wtitle)
{
  gi_fps = p_fps;

  if(SDL_Init(SDL_INIT_EVERYTHING) < 0)
  {
    std::cerr << "SDL Error(something about the init):" << SDL_GetError() << std::endl;
  }
  gi_window = SDL_CreateWindow(p_wtitle,
                               SDL_WINDOWPOS_UNDEFINED,
                               SDL_WINDOWPOS_UNDEFINED, p_width, p_height,
                               SDL_WINDOW_OPENGL | SDL_WINDOW_SHOWN);

  if(gi_window == NULL)
  {
    std::cerr << "SDL Error(couldn't create window): " << SDL_GetError() << std::endl;
  }
  SDL_GL_SetAttribute ( SDL_GL_CONTEXT_MAJOR_VERSION , 3 ) ;
  SDL_GL_SetAttribute ( SDL_GL_CONTEXT_MINOR_VERSION , 0 ) ;

  gi_glcontext = SDL_GL_CreateContext(gi_window);

  if(gi_glcontext == NULL)
  {
    std::cerr << "SDL Error(something about glcontext): " << SDL_GetError() << std::endl;
  }

    std::cout << glGetString(GL_VERSION) << std::endl;

  if(SDL_GL_MakeCurrent(gi_window, gi_glcontext) < 0)
  {
    std::cerr << "SDL Error(something about glcontext): " << SDL_GetError() << std::endl;
  }

  glewExperimental = GL_TRUE;
  GLenum glewerror = glewInit();
  if(glewerror =! GLEW_OK)
  {
    std::cerr << "GLEW Error(something about the initilazation): " << glewGetErrorString(glewerror) << std::endl;
  }
  SDL_version compiled;
  SDL_GetVersion(&compiled);
  printf("SDL Version: %d.%d.%d\n",compiled.major, compiled.minor, compiled.patch); //
  SDL_Delay(200000);
}

Edit:
It seems that another reason that Missing OpenGL Version also comes up when glewExperimental is not set, because only the experimental version of glew supports 3.0+
I have properly set glewExperimental(at least from what I gather from online examples), but it still gives me Missing OpenGL Version.
Edit 2:
The code here does not throw up Missing OpenGL version, despite it being very similar to mine.
Edit 3:
As per enhzflep's suggestion I have rewritten the code to try to diagnose what is going on.
The error does not relent.
#include <SDL2/SDL.h>
#include <SDL2/SDL_version.h>
#include <GL/glew.h>
#include <iostream>
int main()
{
  SDL_Init(SDL_INIT_EVERYTHING);

  SDL_Window* gi_window = SDL_CreateWindow("I would love for this to work!",
                               SDL_WINDOWPOS_UNDEFINED,
                               SDL_WINDOWPOS_UNDEFINED, 640, 480,
                               SDL_WINDOW_OPENGL | SDL_WINDOW_SHOWN);
  SDL_GLContext gi_glcontext = SDL_GL_CreateContext(gi_window);
  SDL_GL_MakeCurrent(gi_window, gi_glcontext);

  SDL_GL_SetAttribute ( SDL_GL_CONTEXT_MAJOR_VERSION , 3 );
  SDL_GL_SetAttribute ( SDL_GL_CONTEXT_MAJOR_VERSION , 0 );
  glewExperimental = GL_TRUE;
  GLenum glewerror = glewInit();
  if(glewerror =! GLEW_OK)
  {
    std::cerr << "GLEW Error(something about the initilazation): " << glewGetErrorString(glewerror) << std::endl;
  }

}

A: I am an idiot.
if(glewerror =! GLEW_OK)
{
   std::cerr << "GLEW Error(something about the initilazation): " <<
   glewGetErrorString(glewerror) << std::endl;
}

should be
if(glewerror != GLEW_OK)
 {
   std::cerr << "GLEW Error(something about the initilazation): " <
   glewGetErrorString(glewerror) << std::endl;
 }

Cheers to everyone who tryed to help!


text:
Q: maven-ejb-plugin don't include xml in packages javas I have a EJB project with maven with pom.xml. I have xml in java packages but EJB plugin doesn't include them. Anyone know why?
Specifically, I have bo.package.xml and archivo.xml files, but they don't include in jar EJB final.
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <artifactId>moduloSigep</artifactId>
        <groupId>bo.sigep.modulo</groupId>
        <version>1.0-SNAPSHOT</version>
    </parent>

    <groupId>bo.sigep.modulo</groupId>
    <artifactId>moduloSigep-ejb</artifactId>
    <version>1.0-SNAPSHOT</version>
    <packaging>ejb</packaging>

    <name>moduloSigep-ejb</name>

    <properties>
        <endorsed.dir>${project.build.directory}/endorsed</endorsed.dir>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.eclipse.persistence</groupId>
            <artifactId>eclipselink</artifactId>
            <version>2.5.2</version>
        </dependency>
        <dependency>
            <groupId>org.eclipse.persistence</groupId>
            <artifactId>org.eclipse.persistence.jpa.modelgen.processor</artifactId>
            <version>2.5.2</version>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>javax</groupId>
            <artifactId>javaee-api</artifactId>
            <version>6.0</version>
            <scope>provided</scope>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>2.3.2</version>
                <configuration>
                    <source>1.6</source>
                    <target>1.6</target>
                    <compilerArguments>
                        <endorseddirs>${endorsed.dir}</endorseddirs>
                    </compilerArguments>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-ejb-plugin</artifactId>
                <version>2.3</version>
                <configuration>
                    <ejbVersion>3.1</ejbVersion>
                    <clientIncludes>
                        <clientInclude>**/*</clientInclude>
                    </clientIncludes>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-dependency-plugin</artifactId>
                <version>2.1</version>
                <executions>
                    <execution>
                        <phase>validate</phase>
                        <goals>
                            <goal>copy</goal>
                        </goals>
                        <configuration>
                            <outputDirectory>${endorsed.dir}</outputDirectory>
                            <silent>true</silent>
                            <artifactItems>
                                <artifactItem>
                                    <groupId>javax</groupId>
                                    <artifactId>javaee-endorsed-api</artifactId>
                                    <version>6.0</version>
                                    <type>jar</type>
                                </artifactItem>
                            </artifactItems>
                        </configuration>
                    </execution>
                </executions>
            </plugin>
        </plugins>
    </build>

</project>

A: i agree
   <resources>
        <resource>
            <directory>src/main/java</directory>
            <includes>
                <include>**/*.xml</include>
            </includes>
        </resource>
    </resources>

in pom and works