text:
Q: Android best way to update UI thread from AsyncTask I released an app today and I am getting some crash reports that indicate the following:
java.lang.NullPointerException: Attempt to invoke virtual method 'android.view.View android.app.Activity.findViewById(int)' on a null object reference

I have on Activity and a couple of Fragments. This error happens in one my Fragments where I have an AsyncTask:
private ProgressDialog dialog;

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
    View view = inflater.inflate(R.layout.fragment_dial, container, false);
    dialog = new ProgressDialog(getActivity());
    new CountryCodeTask().execute();
    return view;
}

private class CountryCodeTask extends AsyncTask<Void, Void, ArrayList<String>>
{
    @Override
    protected void onPreExecute()
    {
        if (!dialog.isShowing()) {
            dialog.show();
        }
    }

    @Override
    protected void onPostExecute(ArrayList<String> result)
    {
        if (dialog.isShowing()) {
            dialog.dismiss();
        }

        if (result != null) {
            Spinner countryCodeSpinner = (Spinner) getActivity().findViewById(R.id.country_code_spinner);
            countryCodeSpinner.setAdapter(new CountryCodeAdapter(getActivity(), result));
            countryCodeSpinner.setSelection(countryCodeSpinnerValue);
            countryCodes = result;
        }
    }

    @Override
    protected ArrayList<String> doInBackground(Void... params)
    {
        return MainActivity.apiService.getCountryCodes();
    }
}

I am guessing this is not the best way to update the UI thread from a ASyncTask. This error happens when I use the back/home button and then restart the app (but not all the time). What am I doing wrong here?
The error happens on this line: Spinner countryCodeSpinner = (Spinner) getActivity().findViewById(R.id.country_code_spinner);

A: You're not doing anything wrong really - it's to be expected that when you navigate away from an Activity via back/home, the AsyncTask will no longer have a reference to the Activity. I would modify your code to handle this common scenario:
@Override
protected void onPostExecute(ArrayList<String> result)
{
    if (dialog != null && dialog.isShowing()) {
        dialog.dismiss();
    }
    Activity activity = getActivity();
    if (activity != null) {
        if (result != null) {
            Spinner countryCodeSpinner = (Spinner) activity.findViewById(R.id.country_code_spinner);
            countryCodeSpinner.setAdapter(new CountryCodeAdapter(activity, result));
            countryCodeSpinner.setSelection(countryCodeSpinnerValue);
            countryCodes = result;
        } else {
            cancelTaskAndShowDialog();
        }
   }
}

A: When your AsyncTask finishes, after you pressed back and left the activity, getActivityreturns null.
You need to add a null check in onPostExecute
final Activity activity = getActivity()

if (dialog =! null && dialog.isShowing()) {
    dialog.dismiss();
}

if (activity != null) {
    if (result != null) {
       Spinner countryCodeSpinner = (Spinner) activity.findViewById(R.id.country_code_spinner);
       countryCodeSpinner.setAdapter(new CountryCodeAdapter(activity, result));
       countryCodeSpinner.setSelection(countryCodeSpinnerValue);
       countryCodes = result;
    }
}

A: Try this:
private ProgressDialog dialog;
private Spinner countryCodeSpinner;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
    View view = inflater.inflate(R.layout.fragment_dial, container, false);
    dialog = new ProgressDialog(getActivity());
    new CountryCodeTask().execute();
    countryCodeSpinner = (Spinner) view.findViewById(R.id.country_code_spinner);
    return view;
}

private class CountryCodeTask extends AsyncTask<Void, Void, ArrayList<String>>
{
    @Override
    protected void onPreExecute()
    {
        if (!dialog.isShowing()) {
            dialog.show();
        }
    }

    @Override
    protected void onPostExecute(ArrayList<String> result)
    {
        if (dialog.isShowing()) {
            dialog.dismiss();
        }

        if (result != null) {
            countryCodeSpinner.setAdapter(new CountryCodeAdapter(getActivity(), result));
            countryCodeSpinner.setSelection(countryCodeSpinnerValue);
            countryCodes = result;
        }
    }

    @Override
    protected ArrayList<String> doInBackground(Void... params)
    {
        return MainActivity.apiService.getCountryCodes();
    }
}


text:
Q: Simultaneous triangularizability over a commutative ring Let $R$ be a commutative ring with unity and $A,B\in M_n(R)$ satisfying the property
(*) All elements of the two-side ideal, in $M_n(R)$, generated by $AB-BA$, are nilpotent.
McCoy showed that, if $R$ is an algebraically closed field, then $A,B$ are simultaneously triangularizable (noted ST). Else, McCoy, again, gave a condition that is equivalent to (*) in
A theorem on matrices over a commutative ring, Bulletin of AMS, 45 (1939) 740-744, in free access here:
http://www.ams.org/journals/bull/1939-45-10/S0002-9904-1939-07070-5/S0002-9904-1939-07070-5.pdf
Unfortunately, the previous condition seems (to me) almost useless.
Then my question is: if the matrices, over a ring, $A,B$ satisfy (*) and are separately triangularizable, then are they ST ?
Thanks in advance.

A: When you write that all elements in the two-sided ideal $\langle AB-BA\rangle$ are nilpotent, what precisely do you mean by "nilpotent".  Here is an example that I believe contradicts simultaneous diagonalizability.  Let $R$ be the commutative, unital ring $\mathbb{C}[\epsilon]/\langle \epsilon^2 \rangle$, i.e., the ring of dual numbers.  Let $A$ and $B$ be the following $2\times 2$ matrices with coefficients in $R$, $$A = \left[ \begin{array}{rr} 1 & \epsilon \\ 0 & 1 \end{array} \right],$$ $$B = \left[ \begin{array}{rr} 1 & 0 \\ \epsilon & 1 \end{array} \right].$$  Then the two-sided ideal is simply $\epsilon M_2(R)$, which I consider to consist of "nilpotent" elements.  Yet $A$ and $B$ are not simultaneously triangularizable in the sense that they simultaneously stabilize a complete filtration of the free $R$-module $R^{\oplus 2}$ by direct summand $R$-submodules.
Edit.  My computation was wrong.  The matrices $A$ and $B$ commute as elements in the algebra $M_2(R)$.  So, of course the ideal $\langle AB-BA \rangle$ consists of nilpotent elements; it is just $\{0\}$.
Nonetheless, there is no rank $1$, $R$-submodule of $R^{\oplus 2}$ that is a direct summand and that is stabilized by both $A$ and $B$.  The point is that there is no "rigidity" for such summands as in the semisimple case.  So the standard argument about simultaneous triangularizability does not apply.

redpajama_set_name: RedPajamaStackExchange


text:
Q: TYPO3 : how to get files/images based on sys_category My sys_categories have some files/images like this :

I tried to display them but I only can get the first one, I tried to loop to display all of them like this  :
<f:if condition="{uid.images}">
     <f:for each="{uid.images}" as="files">
           {files.originalResource.name}
     /f:for>
</f:if>

But I get this error message :
(1/1) #1256475113 InvalidArgumentException
The argument "each" was registered with type "array", but is of type "TYPO3\CMS\Extbase\Domain\Model\FileReference" in view helper "TYPO3Fluid\Fluid\ViewHelpers\ForViewHelper".

there is a dump of {uid} variable :

In database I see correctly "2" on "images"
I don't know what mistake I did, there is an issue from my loop ? Or there is another way to display multiples files/images ?
Thanks for help

A: In your Model you have defined "images" of type FileReference. This means "one" reference/file.
You should refactor this to an ObjectStorage of file references.
/**
 * @var \TYPO3\CMS\Extbase\Persistence\ObjectStorage<\TYPO3\CMS\Extbase\Domain\Model\FileReference>
 */
protected $images;

public function initializeObject()
{
    parent::initializeObject();

    $this->images    = new \TYPO3\CMS\Extbase\Persistence\ObjectStorage();
}

/**
 * @return \TYPO3\CMS\Extbase\Persistence\ObjectStorage<\TYPO3\CMS\Extbase\Domain\Model\FileReference>
 */
public function getImages(): \TYPO3\CMS\Extbase\Persistence\ObjectStorage
{
    return $this->images;
}

/**
 * @param \TYPO3\CMS\Extbase\Persistence\ObjectStorage<\TYPO3\CMS\Extbase\Domain\Model\FileReference> $productVideos
 */
public function setImages(\TYPO3\CMS\Extbase\Persistence\ObjectStorage $images): void
{
    $this->images = $images;
}


text:
Q: Removing multiple objects on Fabric.js canvas Struggling to remove multiple objects from the fabric canvas. Everything seems to be in working order but when the code runs it does not remove the multiple selected objects from the canvas.
    service.deleteSelectedObject = function () {
        var selectedObject = service.canvas.getActiveObject();
        var selectedMultipleObjects = service.canvas.getActiveGroup();
        var data = {};

        // get object id
        // get selected objects from canvas

        if (selectedObject) {
            data = {
                type: 'whiteboard::delete',
                id: selectedObject.id
            };

            delete service.objectMap[selectedObject.id];
            service.canvas.remove(selectedObject);
        } else {
            data = {
                type: 'whiteboard::delete',
                object: selectedMultipleObjects
            };
            console.log(selectedMultipleObjects);
            selectedMultipleObjects._objects.forEach(function (object, key) {
                console.log(object);
                service.canvas.remove(object);
            });
        }

        signalService.sendMessage(service.recipient, data);
    };

I should point out that all of these console logs do pass what they should. As well as the problem is occuring in the else statement the first part of this code works how it should
please let me know if you need any further information.

A: Object of active group are indeed on the canvas but removing them from canvas will not remove them from the rendering pipeline if they are in active group.
When fabricjs draws everything, it checks for object on canvas and presence of activeGroup. If activeGroup is present, its objects get rendered later, regardless they are on canvas or not.
So you are effectively removing the objects from the canvas, but untill you clear the selection of the active group, the objects are still there.
Correct procedure is removing the object from the canvas and from the activeGroup.
check the snippet, select all objects with mouse and the press remove all button.

var canvas = new fabric.Canvas('canvas');
var r1 = new fabric.Rect({width:50,height:50});
var r2 = new fabric.Rect({width:50,height:50,top:110, left:110});
var r3 = new fabric.Rect({width:50,height:50,top:60, left:60});
canvas.add(r1,r2,r3);

function removeAll() {
var o = canvas.getActiveGroup();
o._objects.forEach(function (object, key) {
canvas.remove(object);
o.removeWithUpdate(object);
});
canvas.discardActiveGroup();
canvas.renderAll();
}
<script src="//cdnjs.cloudflare.com/ajax/libs/fabric.js/1.7.13/fabric.min.js" ></script>
<input type="button" onClick="removeAll()" value="remove"/>
        <canvas id="canvas" width=400 height=400 style="height:500px;width:500px;"></canvas>

A: After version 2 of fabric.js, there is no getActiveGroup. To delete multiple objects, you need to use forEachObject.  This example builds on the previous one and can delete single objects or grouped objects.

var canvas = new fabric.Canvas('canvas');
var r1 = new fabric.Rect({width:50,height:50});
var r2 = new fabric.Rect({width:50,height:50,top:110, left:110});
var r3 = new fabric.Rect({width:50,height:50,top:60, left:60});
canvas.add(r1,r2,r3);

function deleteObj(){
var doomedObj = canvas.getActiveObject();
  if (doomedObj.type === 'activeSelection') {
   // active selection needs a reference to the canvas.
   doomedObj.canvas = canvas;
   doomedObj.forEachObject(function(obj) {
      canvas.remove(obj);
   });
 }//endif multiple objects
  else{
  //If single object, then delete it
  var activeObject = canvas.getActiveObject();
    //How to delete multiple objects?
  //if(activeObject !== null && activeObject.type === 'rectangle') {
    if(activeObject !== null ) {
   canvas.remove(activeObject);
  }
  }//end else there's a single object
}//end deleteObj
<script src="//cdnjs.cloudflare.com/ajax/libs/fabric.js/2.4.6/fabric.min.js" ></script>
<input type="button" onClick="deleteObj()" value="remove"/>
        <canvas id="canvas" width=400 height=400 style="height:500px;width:500px;"></canvas>


text:
Q: How does ThumDrawable behave in SeekBar? How does ThumbDrawable is worked in SeekBar?
I can't understand why when setting thumbDrawable using the following method seekBar.setThumb(new CustomDrawable),
when i'm overriding draw method, the canvas (0,0) coordinators aren't placed according to the SeekBar progress value (somewhere on the ProgressDrawable) and instead are placed at the top left place (far above the ProgressDrawable).
Why when using seekBar.setThumb(getContext().getResource().getDrawable (R.drawable.someXmlDrawable), the someXmlDrawble (xml file) is being drawing exactly on the ProgressDrawable , considering the progress value , but when i'm adding the drawable progromatically, canvas coordinates aren't placed on the ProgressDrawable at the correct place (considering the progress value).
Code example (adding programatically drawable):
   SeekBar seekBar = findViewById(R.id.seek_bar);
                seekBar.setThumb(new Drawable() {
                    @Override
                    public void draw(@NonNull Canvas canvas) {

                    }

                    @Override
                    public void setAlpha(int alpha) {

                    }

                    @Override
                    public void setColorFilter(@Nullable ColorFilter colorFilter) {

                    }

                    @Override
                    public int getOpacity() {
                        return 0;
                    }
                });

Code example (adding Drawable from XML):
seekBar.setThumb(new Drawable(R.drawable.someXmlDrawable);


text:
Q: how to change child component state in reactjs I came across the following problem: I need to use another component's function inside a component:
header.js
export default function Header() {

  const [showModalLogin ,setShowModalLogin] = useState(false);

  return(
    <>
    Hi,  <Link onClick={() =>{ setShowModalLogin(true)}}>login</Link>
    {showModalLogin ? <LoginModal setShowModalLogin={setShowModalLogin}/> : ''}
    </>
  );
}

home.js
import Header from '../../components/header/header';

export default function Home() {

  return (
    <>

      <Link onClick={() =>{ setShowModalLogin(true)}}>open login</Link>
    </>
}

How do I do in home.js to call the setShowModalLogin function that is in header.js ? I'm trying to use the context api too, but I still can't solve it.

A: You can just place useState in Header component and pass setShowModalLogin as props:
import Header from '../../components/header/header';

export default function Home() {
  const [isShowModalLogin ,setShowModalLogin] = useState(false);

  return (
    <>

      <Link onClick={() => setShowModalLogin(true)}>open login</Link>
    </>
}

export default function Header({ isShowModalLogin, setShowModalLogin }) {
  return(
    <>
    Hi,  <Link onClick={() => setShowModalLogin(true)}>login</Link>
    {isShowModalLogin ? <LoginModal setShowModalLogin={setShowModalLogin}/> : ''}
    </>
  );
}

A: Then you can do it in this way:

*

*Create Context

*Save useState inside

*Use it everywhere you need

export const YourContext = createContext();

export const YourProvider = ({ children }) => {
  const [isShowModalLogin, setShowModalLogin] = useState(false);

  const value = {
    isShowModalLogin,
    setShowModalLogin
  };

  return <YourContext.Provider value={value}>{children}</YourContext.Provider>;
}

// App.js

const App = () => {
  return (
    <YourProvider>
      <AppContent />
    </YourProvider>
  )
}

So now you can use it like here:
import Header from '../../components/header/header';

export default function Home() {
  const { isShowModalLogin, setShowModalLogin } = useContext(YourContext);

  return (
    <>

      <Link onClick={() => setShowModalLogin(true)}>open login</Link>
    </>
}


text:
Q: Unable to run API on non-root pages after Vercel deploy I've been trying to deploy to a Nuxt app to Vercel. The app technically deploys, but only the main page will render. If I attempt to click through to a link that requires an API request, all the API requests on that page return with a 404 error. However, the same app will work perfectly fine on all pages on Localhost.
I'm not sure what's wrong with my deploy that is causing this. Here's what I currently have as my vercel.json
{
    "alias": "corey-lanier-blog",
    "name": "blog",
    "env": {
      "PORT": "4000",
      "SECRET": "@secret",
      "MONGODB_URI": "@mongodb_uri"
    },
    "version": 2,
    "builds": [
      {
        "src": "nuxt.config.js",
        "use": "@nuxtjs/vercel-builder",
        "config": {}
      }
    ],
    "routes": [
      {
        "src": "/api/posts/(.+)",
        "dest": "/api/posts.js"
      },
      {
        "src": "/api/users/(.+)",
        "dest": "/api/users.js"
      },
      {
        "src": "/api/comments/(.+)",
        "dest": "/api/comments.js"
      },
      {
        "src": "/(.*)",
        "dest": "/"
      }
    ]
  }

Unless the issue is that I've deployed my backend and the frontend on the same deploy and Nuxt is not allowing the subsequent API requests to go through. Is that possible? If so then why is it able to render the initial API requests for the front page render and not the subsequent ones on clickthroughs?

A: Nuxt deploys on Vercel overwrite the routes listed in your vercel.json. There is no clear way to prevent that within Nuxt or within the vercel.json. To solve this, you will need to split the codebase from being fullstack in one project/deploy, and redeploy the frontend/backend separate, as well as point your API routes within Nuxt to the URL for the backend. (You will also likely have to ensure CORS has been configured properly on your backend if you haven't already, so that you can accept requests from your frontend)


text:
Q: Can a Swift enum be referenced as a variable? I am centralizing all my application strings in enums, and these strings are all namespaced to the application feature in which they are used (example below).
When I attempt to store the enum in a variable (like var strings = Strings.Feature.SubFeature) and call it like strings.someStringValue, I get a Expected member name or constructor call after name type error.
Declaration:
enum Strings {
     enum Feature {
          enum Subfeature {
               static var someString: String { "some string".localizedLowerCase }
          }
     }
}

Callsite:
someLabel.text = Strings.Feature.Subfeature.string

Hoped-for behavior:
var strings = Strings.Feature.Subfeature
someLabel.text = strings.someString

Is it possible to store a reference to the containing enum, such that I will not have to reference the full path every time I use a given string? I would love to know if there are any alternative ways of going about this as well.

A: Joakim's answer looks like it answers your question, but another option (with potentially lower memory use?) would be using a typealias.
typealias SubFeatureStrings = Strings.Feature.Subfeature

and then
SubFeatureStrings.someString

The typealias could be nested inside the class/struct where you're calling it, to avoid conflicts across your app.

A: enum Strings {
    enum Feature {
        enum Subfeature {
            static var someString: String { "some string".localizedLowerCase }
            static var otherString: String { "some other string".localizedLowerCase }
        }
    }
}

var strings = Strings.Feature.Subfeature.self
someLabel.text = strings.someString
someLabel.text = strings.someOtherString

A: An enum can be enum <#name#> : String
enum Foo : String {
    case bar = "bar"
}

usage: <#something#>.text = Foo.bar.rawValue

For chained purposes
enum SomeEnum {
    enum Foo : String {
        case bar = "bar"
    }
}

usage: <#something#>.text = SomeEnum.Foo.bar.rawValue

Then you can typealias the chain:
typealias foo = SomeEnum.Foo
<#something#>.text = foo.bar.rawValue


text:
Q: MySQL select last record and update it I want to select the last record in the table and update its name.
UPDATE item
SET name = (SELECT name FROM pds
            WHERE id = 9)
WHERE id=(SELECT id ORDER BY id DESC LIMIT 1);

However, when executing name is changed for all the records.
Tried also:
UPDATE item
SET name = (SELECT name FROM pds
            WHERE id = 9)
WHERE id=(SELECT id FROM item ORDER BY id DESC LIMIT 1);

A: In MySQL you can apply order by and limit clauses to an update statement:
UPDATE item
SET name = (SELECT name FROM pds
            WHERE id = 9)
ORDER BY id DESC
LIMIT 1

A: Just use limit and order by:
update item
    set name = (select name from pds where id = 9)
    order by id desc
    limit 1;

Your second version should work . . . except MySQL probably generates a syntax error.  Try:
UPDATE item i CROSS JOIN
       (SELECT MAX(i2.id) as maxid FROM item i2) mi
    SET i.name = (SELECT pds.name FROM pds WHERE pds.id = 9)
    WHERE i.id = mi.maxid;

The first version is syntactically correct, but it has no FROM clause, so it is using the id value from the outer query -- and just checking that the id is equal to itself.  When using subqueries in the select or where clauses, always use qualified column names.  I advise doing this all the time, but this is especially important for subqueries in these clauses.


text:
Q: Auto vectorization on double and ffast-math Why is it mandatory to use -ffast-math with g++ to achieve the vectorization of loops using doubles? I don't like -ffast-math because I don't want to lose precision.

A: You don't necessarily lose precision with -ffast-math. It only affects the handling of NaN, Inf etc. and the order in which operations are performed.
If you have a specific piece of code where you do not want GCC to reorder or simplify computations, you can mark variables as being used using an asm statement.
For instance, the following code performs a rounding operation on f. However, the two f += g and f -= g operations are likely to get optimised away by gcc:
static double moo(double f, double g)
{
    g *= 4503599627370496.0; // 2 ** 52
    f += g;
    f -= g;
    return f;
}

On x86_64, you can use this asm statement to instruct GCC not to perform that optimisation:
static double moo(double f, double g)
{
    g *= 4503599627370496.0; // 2 ** 52
    f += g;
    __asm__("" : "+x" (f));
    f -= g;
    return f;
}

You will need to adapt this for each architecture, unfortunately. On PowerPC, use +f instead of +x.

A: Very likely because vectorization means that you may have different results, or may mean that you miss floating point signals/exceptions.
If you're compiling for 32-bit x86 then gcc and g++ default to using the x87 for floating point math, on 64-bit they default to SSE, however the x87 can and will produce different values for the same computation so it's unlikely g++ will consider vectorizing if it can't guarantee that you will get the same results unless you use -ffast-math or some of the flags it turns on.
Basically it comes down to the floating point environment for vectorized code may not be the same as the one for non vectorized code, sometimes in ways that are important, if the differences don't matter to you, something like
-fno-math-errno -fno-trapping-math -fno-signaling-nans -fno-rounding-math

but first look up those options and make sure that they won't affect your program's correctness. -ffinite-math-only may help also

A: Because -ffast-math enables operands reordering which allows many code to be vectorized.
For example to calculate this
sum = a[0] + a[1] + a[2] + a[3] + a[4] + a[5] + … a[99]

the compiler is required to do the additions sequentially without -ffast-math, because floating-point math is neither commutative nor associative.

*

*Is floating point addition commutative and associative?

*Is floating point addition commutative in C++?

*Are floating point operations in C associative?

*Is Floating point addition and multiplication associative?
That's the same reason why compilers can't optimize a*a*a*a*a*a to (a*a*a)*(a*a*a) without -ffast-math
That means no vectorization available unless you have very efficient horizontal vector adds.
However if -ffast-math is enabled, the expression can be calculated like this (Look at A7. Auto-Vectorization)
sum0 = a[0] + a[4] + a[ 8] + … a[96]
sum1 = a[1] + a[5] + a[ 9] + … a[97]
sum2 = a[2] + a[6] + a[10] + … a[98]
sum3 = a[3] + a[7] + a[11] + … a[99]
sum' = sum0 + sum1 + sum2 + sum3

Now the compiler can vectorize it easily by adding each column in parallel and then do a horizontal add at the end

Does sum' == sum?  Only if (a[0]+a[4]+…) + (a[1]+a[5]+…) + (a[2]+a[6]+…) + ([a[3]+a[7]+…) == a[0] + a[1] + a[2] + … This holds under associativity, which floats don't adhere to, all of the time.  Specifying /fp:fast lets the compiler transform your code to run faster – up to 4 times faster, for this simple calculation.
Do You Prefer Fast or Precise? - A7. Auto-Vectorization

It may be enabled by the -fassociative-math flag in gcc
Further readings

*

*Semantics of Floating Point Math in GCC

*What does gcc's ffast-math actually do?

A: To enable auto-vectorization with gcc, ffast-math is not actually necessary. See https://gcc.gnu.org/projects/tree-ssa/vectorization.html#using

To enable vectorization of floating point reductions use -ffast-math or -fassociative-math.

Using -fassociative-math should be sufficient.
This has been the case since 2007, see https://gcc.gnu.org/projects/tree-ssa/vectorization.html#oldnews

*-fassociative-math can be used instead of -ffast-math to enable vectorization of reductions of floats (2007-09-04).


text:
Q: Assigning a number to a text block I want to set the Text of a TextBlock according to the Value of a Random Number
I thought about using toString for getting the String of the Random number
and then assigning it to the TextBlock
My Code:
 Random Rnd = new Random();
            Number1 = Rnd.Next(1, 12);
            Number2 = Rnd.Next(1, 12);
            num1.Text = Number1.ToString;
        num2.Text = Number2.ToString;

When I run the code
and  it gives me the following error:

Cannot convert method group 'ToString' to non-delegate type 'string'.
  Did you intend to invoke the method?

But both side's types are String , why can't I assign it ?

A: The problem is that you're not calling the ToString method. In this statement:
num1.Text = Number1.ToString;

... ToString is a method group, which can be used for conversions to delegate types. So for example, this is valid:
Func<string> stringProvider = Number1.ToString;

That's why the error message talks about method groups.
For a method invocation, however, you definitely need the brackets. This is a difference between C# and VB. (In VB, you'd need AddressOf to create a delegate for a method group, but don't need to specify the brackets when invoking a parameterless method.)
You need:
num1.Text = Number1.ToString();
num2.Text = Number2.ToString();

(Additionally, I strongly suggest you follow normal C# naming conventions, where non-constant variables are camelCased rather than PascalCased, but that's a slightly different matter.)

A: num1.Text = Number1.ToString;
num2.Text = Number2.ToString;

Isn't valid c# syntax.
You could use:
num1.Text = Number1.ToString();
num2.Text = Number2.ToString();

Or
num1.Text = Convert.ToString(Number1);
num2.Text = Convert.ToString(Number2);

Where Convert.ToString handles null values and value.ToString() doesn't.

A: Try this as .Next() returns an int
num1.Text = Number1.ToString();
num2.Text = Number2.ToString();

A: you need to convert Number1 and Number2 to string like
num1.Text = Number1.ToString();
num2.Text = Number2.ToString();

A: You have to convert Number1 and Number2 to string before assigning it to a text box like
  num1.Text=Number1.ToString();
  num2.Text=Number2.ToString();


text:
Q: clang fails to deduce function template parameter with packed variadic parameters #include <tuple>

template<std::size_t... Is, std::size_t... Js>
auto test(std::tuple<std::index_sequence<Is, Js>...>) {}

int main()
{
    test(std::tuple<std::index_sequence<0, 0>>{});
}

You can see the compile result of each compiler here: https://godbolt.org/z/z6TEWxn49
The latest GCC and MSVC compiles this code but clang doesn't.
I cannot find why clang fails, so I'd like to make an issue report, if it's clang's bug.
Is clang right by standard? Or, is it a bug of clang?


text:
Q: Circular gradient I have searched and searched and I cannot seem to find the code that will give me the effect in the screen shot below:
http://i.stack.imgur.com/MPAiA.png
I have managed to draw the circle and get a simple top to bottom gradient working but I cannot fathom how to get the below, all help is much appreciated.
Here is what got me a simple top to bottom gradient:
CGColorSpaceRef baseSpace = CGColorSpaceCreateDeviceRGB();
CGGradientRef gradient = CGGradientCreateWithColorComponents(baseSpace, colors, NULL, 2);
CGColorSpaceRelease(baseSpace), baseSpace = NULL;

CGContextRef context = UIGraphicsGetCurrentContext();

CGContextSaveGState(context);
CGContextAddEllipseInRect(context, rect);
CGContextClip(context);

CGPoint startPoint = CGPointMake(CGRectGetMidX(rect), CGRectGetMinY(rect));
CGPoint endPoint = CGPointMake(CGRectGetMidX(rect), CGRectGetMaxY(rect));

CGContextDrawLinearGradient(context, gradient, startPoint, endPoint, 0);
CGGradientRelease(gradient), gradient = NULL;

CGContextRestoreGState(context);

CGContextAddEllipseInRect(context, rect);
CGContextDrawPath(context, kCGPathStroke);

A: So you want a radial gradient. But you are drawing a linear gradient. That's pretty silly. Draw a radial gradient if you want a radial gradient!
https://developer.apple.com/library/ios/documentation/graphicsimaging/reference/CGContext/Reference/reference.html#//apple_ref/c/func/CGContextDrawRadialGradient
Another possibility (considerably simpler) is to draw the radial gradient using a CIFilter:
https://developer.apple.com/library/mac/documentation/graphicsimaging/reference/CoreImageFilterReference/Reference/reference.html#//apple_ref/doc/filter/ci/CIRadialGradient


text:
Q: Showing that $\varphi: k[x_1,...,x_n] \rightarrow Map(k^n,k)$ is injective Given a formal expression $f\in k[x_1,...,x_n]$ we can consider it as a map from $k^n$ to $k$ by evaluating the indeterminatns on elements in $k^n$.
I want to show association, which we denote $\varphi$, is injective.
We proceed by induction: Suppose $f\in \ker(\varphi)$. Since $k$ is algebraically closed, $k$ is infinite. Therefore $f$ has an infinite number of zeros. It should follow from this that $f$ must then be zero in $k[x_1,...,x_n]$ but I don't see why this is the case.
Bonus confusion: I am trying to find a counter example in the case the $k$ is not algebraically closed. If we take $k=\mathbb{F}_p$ then it seems $x^p-x$ is a counter example. Whenever we evaluate it on an element in $\mathbb{F}_p$ we get zero, but i am wondering why we don't also count this as being zero as a formal expression in $\mathbb{F}_p[x]$?

A: Preliminary: I'm going to write polynomials with capital letter variables, and their induced maps with lower case variables to make them easier to distinguish.
About your first question: $f$ having an infinite number of zeros does not imply that $f=0$ for $n\geq2$. Take $X_1^2+X_2^2-1\in\mathbb C[X_1,X_2]$ as a counterexample. It is zero on the (real) unit circle, which contains an infinite number of elements, but the polynomial itself doesn't vanish. If you're going to do induction, actually do it:
$n=1$ :
This is where what you tried doing actually works. A single variable polynomial has at most as many zeros as its degree, which is finite. Except if it is the $0$ polynomial. So $f=0$, and thus $\ker\varphi$ is trivial, so $\varphi$ is injective.
$n+1$ :
Now let $f\in k[X_1,\dots,X_{n+1}]=k[X_1,\dots,X_n][X_{n+1}]$ such that $f\in\ker\varphi$. This means $f(x_1,\dots,x_{n+1})=0$ for all $x_1,\dots,x_{n+1}\in k$. consequently, if we consider $f$ as a single variable polynomial in $k[X_1,\dots,X_n][X_{n+1}]$ (the coefficients are polynomials in $k[X_1,\dots,X_n]$), it also has an infinite number of zeros. You can take it from here.
About your second question: The answer to why we don't consider $X^p-X=0$ requires an understanding of what a formal polynomial is supposed to do in the first place. Basically, if $R$ is a commutative ring we want a polynomial $f\in R[X]$ to be something into which we can substitute things. And I'm specifically saying things, not elements of $R$. Because there's more stuff we might want to substitute for $X$. For instance, think back to linear algebra, where the minimal polynomial of a matrix $M$ was defined as the normed polynomial $\mu$ with minimal degree such that $\mu(M)=0$. So we substitute a matrix for $X$, not an element of the underlying field. To be precise, we want there to be evaluation homomorphisms: If $S$ is a ring extension of $R$ and $s\in S$ an element which commutes with every element of $R$, then $\varphi_s:R[X]\to S,~f\mapsto f(s)$ is a ring homomorphism. This is what polynomials must be able to accomplish to be rightfully called polynomials. So back to your example $X^p-X\in\mathbb F_p[X]$, we need to be open to the possibility that we don't substitute an element of $\mathbb F_p$, but an element of any ring extension of $\mathbb F_p$. And while substituting any element of $\mathbb F_p$ would yield $0$, substituting elements of a ring extension might not! For instance, if $x\in\mathbb F_{p^2}\backslash\mathbb F_p$, then $x^p-x\neq0$, since the corresponding polynomial can have at most $p$ zeros due to its degree, which are already contained in $\mathbb F_p$.
Another way to look at it: You're only considering the homomorphism $k[X_1,\dots,X_n]\to\operatorname{Map}(k^n,k)$. But for any commutative ring extension $k\subset S$, there is also a homomorphism $k[X_1,\dots,X_n]\to\operatorname{Map}(S^n,S)$. And while the former might be non-injective for $k$ not algebraically closed, the latter might actually be injective. But only if you consider $X^p-X$ and $x^p-x$ different things, where $x^p-x\equiv 0$ doesn't imply $X^p-X\equiv 0$


text:
Q: Javascript fadeIn div tags fails on click Im kind of new to javascript, and I have tried for several hours now to make this fadeIn function to work.
First of all, look at my code here.
I have also included the following in my header:

This is how I want the page to work,

*

*When a user enters the site, the home selection will fadein

*The menu is based on
 and
 itmes for categories and in each category we have different comapnies. Each category have a  and each company have a  to the div tag made later in the body.

*A user should be able to switch between the menu options, and each time the time should fade in.

So the problem as you see in my code, it works on page load, but I cant choose anything from the menu.
Any suggestions would be helpful

A: If I understood correctly you wanted it to function something like this :
$('#menu a').click(function () {
    $("#content div").hide(); //Hide all content
    var id = $(this).attr('href');
    $(id).fadeIn(); // Show content for current tab
});

You didn't need this line (it is deleting the id) :
$("#menu li").attr("href", ""); //Reset id's

This is line I don't even know what it's for:
$(this).parent().attr("href", "current"); // Activate this google parent!

If you want to add a class to the current active menu item, use something like
$(this).parent().addClass('active');

Also you don't need to add '#' because you already had that in you href atrribute:
$($(this).attr('href')).fadeIn(); // Show content for current tab

You can check what kind of id you're getting by alerting it or logging it :
var id = $(this).attr('href');
alert(id);
$(id).fadeIn();

A: you are resetting the "href" attribute. Thus, when you try to make a fadeIn the "href" attribute value is changed to "current".
Those two lines:
$("#menu li").attr("href", ""); //Reset id's
....
$('#' + $(this).attr('href')).fadeIn();

are wrong because $(this).attr('href') is equal to "" (empty string)
also you made a mistake because you did
$("#content div:last").fadeIn(); // Show first tab content

but the command and what you expect are not coherent. Here you are using fadeIn on the last tab content instead of the first.
You can try something like this: http://jsfiddle.net/546Jn/4/
$(document).ready(function () {
    $("#content div").hide();
    $("#content div:first").fadeIn(); // Show first tab content

    $('#menu a').click(function () {
        $("div#content div").hide(); // Hide all pages
        $('div' + page).fadeIn(); // Show content for current tab
    });
});

A: Are you sure with this line of Code?
$("#menu li").attr("href", "");
You do not override your ID here. You remove your link href.


text:
Q: Attempt to dual boot Windows 10 & Ubuntu Server 14.04 LTS failed. How to fix? I am new, but have read quite a few post on this subject, but I can't find a case similar to mine.
I'm not new to Ubuntu Server 14.04, not an expert either, but I mostly manage the jobs I want done. Not so with dual booting.
I had a brand new Windows 10 installation, I prepared the SSD for dual booting even before installing Windows 10. I now have a 450MB recovery partition, a 100MB EFI system partition & a 100GB partition with Windows 10. Besides that, I have a 12GB EFI system partition where Ubuntu Server is installed & a 7,5 swap partition on that disk.
I installed Windows 10, I researched the dual booting thing & went to install Ubuntu Server, but it didn't work out as planned... Upon boot I got the GRUB menu & could choose both Windows & Ubuntu, but halfway through boot Ubuntu appeared to just sit there (Windows 10 just worked fine)...
So I went and redid the install of Ubuntu & now there's no GRUB menu, but if I set the windows partition as primary boot device (in UEFI bios) it boots in windows and if I set the ubuntu partition as primary boot device it boots Ubuntu.
How can I get the GRUB menu back & get a proper dual booting setup.
If there is any more info needed to answer my question, I'll gladly research

A: Congrats on getting the dual-boot working. Reinstalling GRUB2 is a common practice to return control to the bootloader after installing an OS. Boot into Ubuntu and type the following on a terminal.
 sudo grub-install /dev/sdX  # Example: sudo grub-install /dev/sda

Note that X is the drive letter you wish for GRUB to write the boot information.
For more info, see: https://help.ubuntu.com/community/Grub2/Installing


text:
Q: Is "one too many" too formal or too "proverbial"? Imagine I had 3 cups of coffee. 2 would have been ok, but 3 is too many. I want to be factual that I had too many, by exactly one. I want to say:

I had one too many cup of coffee.

But I feel like this sentence is a little to "proverbial" in the sense that "one too many" is an idiom.
According to this answer, it has a "negative connotation" and it's closely related to alcohol consumption.
I don't want to convey that at all. Is my sentence OK, or is there another way to say it?
Also, is there any difference in connotation or meaning with this sentence?

I had one cup of coffee too many.

A: You are right "one too many" does usually mean there is a bad side effect, feeling sick, needing the toilet urgently, drunk, so full you can't move etc.
This isn't really a formal concept I can not think of a place where I would want to say this formally, as it is a personal internal information.  So every phrase I can think of is casual:

I didn't need that last coffee

is the best alternative I can come up with.


text:
Q: Windows Batch File popd not working as expected I am using the following batch script to run a Java Command Line tool.
@echo off
pushd %~dp0
setLocal EnableDelayedExpansion
set CLASSPATH="
for /R ./libs %%a in (*.jar) do (
    set CLASSPATH=!CLASSPATH!;%%a
)
set CLASSPATH=!CLASSPATH!"
java -cp !CLASSPATH! com.example.CLIApplication %*
popd

I have added the tool's directory to the System Variables PATH so that I can run it from any directory via the command prompt. This is working but the problem I am seeing is:
The tool's dir is C:\tool\
The user is in C:\
After executing the batch file the user is left in C:\tool\ not C:\
popd is getting called but the console navigates back to C:\too\ instead of staying in C:\
How do I ensure they users directory is not changed after the script finishes?

A: The setlocal without endlocal causes this problem here.
You only need to add an endlocal just before calling popd.
In your code the popd returns to your first directory, but as setlocal stores all variables and all open setlocals are closed by implicit endlocals when the batch is exited, it will also restore the cd variable.

A: I may be off track, but why aren't you using:
pushd .


text:
Q: Coffeescript translation If I have this javascript:
function I_did_something(){
  this.test.assertExists('#selector', 'exists');
}

casper.then(I_did_something);

The problem is that casper is using call to call the then method meaning that I cannot do something like this:
@I_did_something = ->
  @assertExists('#selector', 'exists')

casper.then @I_did_something

Because this does not refer to the global object.
Can anyone suggest how I would translate this into coffeescript without using the window object preferably?

A: You can use a fat arrow (=>) to bind the function to the current this:
@I_did_something = =>
  @assertExists('#selector', 'exists')

That has a similar effect to:
that = @
@I_did_something = ->
  that.assertExists('#selector', 'exists')

and I think that's what you're after.


text:
Q: Getting location of a direction of current location in Android I want to implement a function that calculates locations' list (longitudes and latitudes) through a direction of my phone. The result can be a rectengular shape which is pointing the corners as locations.
First how can i find the device current direction which means which direction the back camera points ?
Then how can i obtain a list of location information through this direction ?
Thank you

A: From the documentation of Google Maps Android API, the location data available to an Android device includes the current location of the device pinpointed using a combination of technologies - the direction and method of movement, and whether the device has moved across a predefined geographical boundary, or geofence.

This is the 3 options that you can do with your app.

*

*Using My Location layer that provides a simple way to display the device's location on the map. It does not provide data.

*Using Google Play services Location API is
  recommended for all programmatic requests for location data.

*And using the LocationSource
  interface allows you to provide a custom location provider.
By using this, you can also get the different information about the
  coordinates that you get

For more information, check this tutorial:

*

*Google Map Tutorial in Android Studio: How to get current location in Android Google Map

*Google Map Tutorial in Android Studio


text:
Q: Notification push server vs simple HTTP POST/GET I am currently making API for a product where we read the users calendar and remind them (during chrome - can change this) to frequently take breaks (when there isnt a meeting)
These reminders are like notifications.
In my opinion, we need to push a notification like : http://www.gianlucaguarini.com/blog/nodejs-and-a-simple-push-notification-server/
I am not sure how to trigger it. I know how to write APIs but not sure about the trigger part.
My co-worker says there shouldn't be any web sockets and told me to refer to the following : https://developers.google.com/cloud-messaging/downstream
I am a bit confused and I think we need web sockets. Am I incorrect about this? Also, any recommendations on how I can trigger my API? I don't want to do an ajax call every minute or so (in the front end)

A: You may use socket.io. Websockets are working on both directions. In other words you do not howe to refresh the page or post a ajax request in order to invoke an event in the client side. Examples on the official web site will be sufficient I guess.
http://socket.io/docs/
If the docs are not sufficient let me explain with an example. Whenever you should push notification in backend side you may have something like this
    io.to(socketid).emit('notification', "You have new notifications");

This socket id is unique for every connection. You can keep track of it by using somekind of hashmap. Key may be the user id and the value may be the socket id for that user. Whenever you call this chunk of code on the clientside this pair of code will be invoked:
    socket.on('notification', function(msg){
               /*stuff*/
    }

here msg is just a string with value You have new notifications. You may pass whatever object you want.


text:
Q: Rename a GridFS collection & now cannot see files with the list command in mongofiles utility Would any one know how I can view in the mongofiles utility the files in my renamed GridFS collection in MongoDB?
Frist, I insert a number of text files into the fs collection.
When I run:
~$ mongofiles -db mydb list

I see the names of the files I inserted.
In the mongo shell I successfully ran:
>db.fs.files.renameCollection("mycollect.files")
>db.fs.chunks.renameCollection("mycollect.chunks")

With the find command in the mongo shell, I see the information about the renamed collections (mycollect.chunks & mycollect.files).
When I use the mongofiles utility from the commandline, I can NOT bring a list of files using:
~$ mongofiles -db mydb -c mycollect.files list

Also does not work:
~$ mongofiles -db mydb -c mycollect.chunks list

A: Indeed, that is a documentation bug. The -c parameter has no effect, see MongoDB's Jira issue SERVER-4931 and the mongofiles documentation:

--collection <collection>, -c <collection>
This option has no use in this context and a future release may remove it.

You can, however, access those collections using the drivers' GridFS implementations, most drivers seem to support this.
--- edit ---
You might want to take a look at SERVER-1970 where someone has apparently provided a pull request, but it's no longer in the repository!?


text:
Q: WAN Remote Desktop VPN connection blocking local connection When ever i use my WAN to connect Remote Desktop to work, it blocks my internet access thru the local connection. Not disabling it. The web browser says there is no connection error.
Is there a way to get both to work?
I do have 2 Ethernet ports on my motherboard, and each on uses a different local conn.
Is there a way to allow remote desktop on one and the internet on the other?
So there is now 3 current active connections
Local Conn 2
Local Conn 3
WAN Miniport pptp (when enables, blocks internet access)


text:
Q: Login/Logout with single Stack Exchange account
Possible Duplicate:
Add "network wide logout" functionality

I've tried it on different Stack Exchange sites. There are individual sessions maintained for each site. Logging in/out on one site doesn't reflect on the other. I have to manually log in/out on the other. It would be better to have single login/logout. Because it's hard to remember all the sites that I've logged in especially when at work. Or is it already available in Stack Exchange, and I didn't notice?
I tried logging out from stackoverflow.com but I'm still logged in in meta.stackoverflow.com. Do I have to change any setting to log out all the sessions?


text:
Q: Portable serialisation of IEEE754 floating-point values I've recently been working on a system that needs to store and load large quantities of data, including single-precision floating-point values.  I decided to standardise on network byte order for integers, and also decided to store floating point values in big-endian format, i.e.:
  |-- Byte 0 --| |-- Byte 1 -|  Byte 2   Byte 3
  #      ####### #     ####### ######## ########
Sign     Exponent          Mantissa
 1b    8b, MSB first    23b, MSB first

Ideally, I want to provide functions like htonl() and ntohl(), since I have already been using these for swabbing integers, and I also want to implement this in a way that has as much platform-independence as possible (while assuming that the float type corresponds to IEEE754 32-bit floating point values).  Is there some way, possibly using ieee754.h, to do this?
I have one answer that seems to work, and I will post it below, but it seems pretty slow and inefficient and I would appreciate any suggestions about how to make it faster and/or more reliable.

A: Much simpler, and depending on the same assumption as yours (which is that float and integer types have the same byte order, and is almost universally valid -- realistically you'll never encounter a system where it isn't true):
#include <string.h>

float htonf(float val) {
    uint32_t rep;
    memcpy(&rep, &val, sizeof rep);
    rep = htonl(rep);
    memcpy(&val, &rep, sizeof rep);
    return val;
}

Any reasonably good compiler will optimize away the two memcpy calls; they are present to defeat over-eager strict aliasing optimizations, so this ends up being as efficient as htonl plus the overhead of a single function call.

A: As mentioned in the question above, I have a solution to my problem, but I'm not particularly attached to it, and I welcome other answers, so I'm posting it here rather than in the question.  In particular, it seems likely to be slow, and I'm not sure whether it breaks strict aliasing, among other potential problems.
#include <ieee754.h>

float
htonf (float val)
{
  union ieee754_float u;
  float v;
  uint8_t *un = (uint8_t *) &v;

  u.f = val;
  un[0] = (u.ieee.negative << 7) + ((u.ieee.exponent & 0xfe) >> 1);
  un[1] = ((u.ieee.exponent & 0x01) << 7) + ((u.ieee.mantissa & 0x7f0000) >> 16);
  un[2] = (u.ieee.mantissa & 0xff00) >> 8;
  un[3] = (u.ieee.mantissa & 0xff);
  return v;
}

float
ntohf (float val)
{
  union ieee754_float u;
  uint8_t *un = (uint8_t *) &val;

  u.ieee.negative = (un[0] & 0x80) >> 7;
  u.ieee.exponent = (un[0] & 0x7f) << 1;
  u.ieee.exponent += (un[1] & 0x80) >> 7;
  u.ieee.mantissa = (un[1] & 0x7f) << 16;
  u.ieee.mantissa += un[2] << 8;
  u.ieee.mantissa += un[3];

  return u.f;
}

A: Here's a portable IEEE 754 write routine.
It will write a double in IEEE 754 format, regardless of the floating point representation on the host machine.
/*
* write a double to a stream in ieee754 format regardless of host
*  encoding.
*  x - number to write
*  fp - the stream
*  bigendian - set to write big bytes first, elee write litle bytes
*              first
*  Returns: 0 or EOF on error
*  Notes: different NaN types and negative zero not preserved.
*         if the number is too big to represent it will become infinity
*         if it is too small to represent it will become zero.
*/
static int fwriteieee754(double x, FILE *fp, int bigendian)
{
    int shift;
    unsigned long sign, exp, hibits, hilong, lowlong;
    double fnorm, significand;
    int expbits = 11;
    int significandbits = 52;

    /* zero (can't handle signed zero) */
    if (x == 0)
    {
        hilong = 0;
        lowlong = 0;
        goto writedata;
    }
    /* infinity */
    if (x > DBL_MAX)
    {
        hilong = 1024 + ((1 << (expbits - 1)) - 1);
        hilong <<= (31 - expbits);
        lowlong = 0;
        goto writedata;
    }
    /* -infinity */
    if (x < -DBL_MAX)
    {
        hilong = 1024 + ((1 << (expbits - 1)) - 1);
        hilong <<= (31 - expbits);
        hilong |= (1 << 31);
        lowlong = 0;
        goto writedata;
    }
    /* NaN - dodgy because many compilers optimise out this test, but
    *there is no portable isnan() */
    if (x != x)
    {
        hilong = 1024 + ((1 << (expbits - 1)) - 1);
        hilong <<= (31 - expbits);
        lowlong = 1234;
        goto writedata;
    }

    /* get the sign */
    if (x < 0) { sign = 1; fnorm = -x; }
    else { sign = 0; fnorm = x; }

    /* get the normalized form of f and track the exponent */
    shift = 0;
    while (fnorm >= 2.0) { fnorm /= 2.0; shift++; }
    while (fnorm < 1.0) { fnorm *= 2.0; shift--; }

    /* check for denormalized numbers */
    if (shift < -1022)
    {
        while (shift < -1022) { fnorm /= 2.0; shift++; }
        shift = -1023;
    }
    /* out of range. Set to infinity */
    else if (shift > 1023)
    {
        hilong = 1024 + ((1 << (expbits - 1)) - 1);
        hilong <<= (31 - expbits);
        hilong |= (sign << 31);
        lowlong = 0;
        goto writedata;
    }
    else
        fnorm = fnorm - 1.0; /* take the significant bit off mantissa */

    /* calculate the integer form of the significand */
    /* hold it in a  double for now */

    significand = fnorm * ((1LL << significandbits) + 0.5f);

    /* get the biased exponent */
    exp = shift + ((1 << (expbits - 1)) - 1); /* shift + bias */

    /* put the data into two longs (for convenience) */
    hibits = (long)(significand / 4294967296);
    hilong = (sign << 31) | (exp << (31 - expbits)) | hibits;
    x = significand - hibits * 4294967296;
    lowlong = (unsigned long)(significand - hibits * 4294967296);

writedata:
    /* write the bytes out to the stream */
    if (bigendian)
    {
        fputc((hilong >> 24) & 0xFF, fp);
        fputc((hilong >> 16) & 0xFF, fp);
        fputc((hilong >> 8) & 0xFF, fp);
        fputc(hilong & 0xFF, fp);

        fputc((lowlong >> 24) & 0xFF, fp);
        fputc((lowlong >> 16) & 0xFF, fp);
        fputc((lowlong >> 8) & 0xFF, fp);
        fputc(lowlong & 0xFF, fp);
    }
    else
    {
        fputc(lowlong & 0xFF, fp);
        fputc((lowlong >> 8) & 0xFF, fp);
        fputc((lowlong >> 16) & 0xFF, fp);
        fputc((lowlong >> 24) & 0xFF, fp);

        fputc(hilong & 0xFF, fp);
        fputc((hilong >> 8) & 0xFF, fp);
        fputc((hilong >> 16) & 0xFF, fp);
        fputc((hilong >> 24) & 0xFF, fp);
    }
    return ferror(fp);
}


text:
Q: Array Filter and Array Values taking a long time on large PHP array of objects I have a piece of code running a simulation.
public function cleanUpHouses(\DeadStreet\ValueObject\House\Collection $collection)
{
    $houses = $collection->getHouses();

    $housesLength = count($houses);
    $filterValues = false;

    for($i = 0; $i < $housesLength; $i++) {
        if(!$this->houseModel->hasBeenAttacked($houses[$i])) {
            break;
        }

        $houses[$i]->setCurrentAttackers(0);

        if($this->houseModel->requiresDestroying($houses[$i])) {
            $houses[$i] = null;
            $filterValues = true;
        }
    }
    if($filterValues) {
        $houses = array_values(array_filter($houses));
    }

    $collection->setHouses($houses);

    return $collection;
}

However, $collection contains an array ($getHouses) of up to and over 1 million results, although it will never need to iterate over all of these results, the line $houses = array_values(array_filter($houses)) is taking ages due to the sheer size of the array, (up to 3 seconds each time this line is ran).
I have to keep the array index numeric, and there can be no null values in this array.
I was hoping unset($array[$i]) would shift the array elements after the element being unset 'down' in key, so if I was to unset($array[5]), then $array[6] would become $array[5], however it doesn't seem to work like this.
The break conditional is there because, on an iteration if the house under iteration hasn't been attacked, then it's safe to assume any other house after that in the array has also not been attacked.
Is there an optimal, less resource heavy way to achieve this?
I can't really restructure this at the moment as it's in unit tests and I need it finishing ASAP, the approach isn't great, but eh.

A: I think the most painless way to achieve this is something like this:
While you are looping through the array of houses, and you need to unset something in the array, you can cheat the loop itself.
if($this->houseModel->requiresDestroying($houses[$i])) {
    // $houses[$i] = null;
    // when you unset the $i house in the array,
    // you can simply switch it with the last one in the array, keeping in mind,
    // that this may break your logic with the break condition, so will want to change that as well.
    $lastHouse = $houses[$housesLength - 1];
    $houses[$i] = $lastHouse;
    unset($houses[$housesLength - 1]);
    $i--;
    $housesLength--; // by doing the top two lines we would make the loop check the last house again.
    $shouldBreak = false; // this will keep your logic with the break if later.
    // $filterValues = true; // you can remove this line here.
}

You would want to set up a variable for the break condition before the for loop starts.
$shouldBreak = true;
for($i = 0; $i < $housesLength; $i++) {
    ...

And now for the condition itself
if(!$this->houseModel->hasBeenAttacked($houses[$i]) && true === $shouldBreak) {
    break;
} else {
    $shouldBreak = true; // we set $shouldBreak = false when we unset the last house,
    // so we would want to keep checking the houses not to break the logic.
}

We only will remove the last element in the array, so it will be kept numeric.


text:
Q: Is it possible to declare a shader variable as both input and output? I'm using both a vertex shader and a geometry shader. My vertex shader does nothing more than forward its input to the geometry shader.
#version 330 core
layout (location = 0) in uint xy;
layout (location = 1) in uint znt;

out uint out_xy;
out uint out_znt;

void main()
{
    out_xy = xy;
    out_znt = znt;
}

Is it possible to declare xy and znt as both an input and an output, so that I don't need to rename them?

A:
Is it possible to declare a shader variable as both input and output?

No. Names of variables are identifiers and 2 different variables have to have different identifiers.

See GLSL - The OpenGL Shading Language 4.6; 3.7 Identifiers; page 18

Identifiers are used for variable names, function names, structure names, and field selectors ...
... More generally, it is a compile-time error to
  redeclare a variable, ...

But of course it is possible to declare an interface block with an instance name. As described in the answer of Nicol Bolas. In this case the variable can be accessed by the instance name of the interface block and the name of the variable.
But it is still not possible to use an interface block without an instance name and to reuse a variable name inside the instance block.
See GLSL - The OpenGL Shading Language 4.6; 4.3.9 Interface Blocks; page 54

If an instance name (instance-name) is not used, the names declared inside the block are scoped at the global level and accessed as if they were declared outside the block. If an instance name (instance-name) is used, then it puts all the members inside a scope within its own name space, accessed with the field
  selector ( . ) operator (analogously to structures).

A: You cannot "declare" them that way, but you can use interface blocks, which can give you essentially the same thing:
//Vertex shader:

layout (location = 0) in uint xy;
layout (location = 1) in uint znt;

out VS
{
   uint xy;
   uint znt;
} to_gs;

void main()
{
    to_gs.xy = xy;
    to_gs.znt = znt;
}

//Geometry shader:

in VS
{
   uint xy;
   uint znt;
} from_vs[];

void main()
{
}

You have to use instance names on these blocks so that GLSL knows what variables you're talking about. But otherwise, they have the same name. This also allows you to use from_vs[X] to select the Xth vertex from the primitive in the geometry shader, rather than having to declare each individual input variable as an array.


text:
Q: cakephp - order by timestamp DESC not working I have a table called posts that stores all the posts . It has two columns "Created" and "Modified" .
Below is my query in the model :
$options = [
            'conditions' => [
                'circle_id'                => $my_circle_list,
                'team_id'                  => $this->current_team_id,
                'modified BETWEEN ? AND ?' => [$start, $end],
            ],
            'order'      => ['modified'=> 'desc'],
            'limit'      => $limit,
            'fields'     => ['post_id'],
        ];
        $res = $this->find('list', $options);

Now i want the latest edited posts on top and below is what my mysql dump reads like :
SELECT `Post`.`id` FROM `db`.`posts` AS `Post`   WHERE `Post`.`id` IN (125, 124) AND `Post`.`del_flg` = '0'   ORDER BY `Post`.`modified` desc  LIMIT 20

If i run this query in my database editor ,it gives my the correct output , but in my controller the ordering changes again , this is something i figured after i debugged the array values.
Would be helpful if anyone could tell me if there's any specific reason behind this . The call to this model method from the controller is done in a conventional manner  .

A: When using $this->find() after Cake has queried the database with the generated SQL it calls the afterFind() method on the model where it can manipulate the data. This is the mostly likely place for the ordering to have been modified.


text:
Q: Azure Virtual Machine Inbound rule for only specified IP adress service is running on port x in Azure VM.
In order to access service from outside VM inbound rule is requred. However, it opens access to all ip addresses which means that anyone can access the service.
Is it possible to set an allowed IP on port level?

A: Go to your Azure virtual machine / Networking / Inbound port rules / Add inbound security rule -> Source: IP Addresses
You can add Source IP addresses/CIDR ranges


text:
Q: Python line plotting 2 columns in same DataFrame using Index and count Newbie to Python so am unsure whether this can be done in one graph or not. I have one DataFrame containing Year, Number of Accidents and Number of Fatalities:

I am trying to generate a line plot that shows x axis = Year, y axis = number of instances per year, and 2 lines showing number of each individual column. Using Seaborn, I can only see a way to map 2 columns and hue. Can anyone please provide any advice on whether this is achievable in either Matplotlib or Seaborn.
Tried using Seaborn but cannot work out how to set up x and y axis as required and show 2 individual columns within that:
sns.lineplot(x=f1_safety['NumberOfFatalities'],y=f1_safety['NumberOfAccidents'].count(), hue = f1_safety['year'].count())
plt.show()

A: There are at least two ways to accomplish what you want to do here.

*

*The simpler one uses pandas built-in plotting API. You can plot dataframes directly when they are already in the correct form. In your case, you need to set the year as the index, and then can plot right away:f1_safety.set_index("year").plot()

*If you want to use seaborn, you first need to transform the data into the correct format. seaborn takes x and y, and you can not specify different y columns directly (like y1, y2 and so on). Instead, you need to transform the data into "long format". In such a table, you get one index or id column, one value column and a "description" kind of columns. This works like this:

f1_safety = pd.melt(df, id_vars="year", value_vars=["NumberOfAccidents", "NumberOfFatalities"])
sns.lineplot(data=f1_safety, x="year", y="value", hue="variable")

The plot in both cases looks quite the same:

There are other ways. In particular, in Jupyter you can execute two plot statements in the same cell, and matplotlib will put the plots into the same figure, even cycling through the colors as necessary.


text:
Q: PHPDoc for a parameter that must be a specific class implementing an interface How do I write PHPDoc for a parameter that must be a certain class (or subclass) and also must implement an interface?
class Animal{
    public function name();
}

interface IsCute{
    public function cuddles();
}

/**
 * @param Animal<IsCute> $animal must be a subclass of Animal and also implements IsCute
 */
function cuddlyAnimal(Animal $animal){
    $animal->cuddles();
}

In the above example, I have an AnimalClass with many potential subclasses, Dog, Cat, Salmon, Bluejay.
My class structure looks like:

*

*Animal

*

*Mammal

*

*Dog implements IsCute

*Cat implements IsCute

*Fish

*

*Salmon

*Bird

*

*Bluejay implements IsCute
Dog, Cat, and Bluejay implement IsCute, Salmon does not. I'd like to have a PHPDoc for cuddlyAnimal that requires Animal class and IsCute interface.

A: Try this:
/**
 * @param IsCute|Animal $animal must be a subclass of Animal and also implements IsCute
 */
function cuddlyAnimal(IsCute $animal){
    $animal->cuddles();
}


text:
Q: UWP text wrapping with TextBlock Run My goal is to display a large number and highlight variably the first few numbers in a different color. Since RichTextBox would be overkill I found out about 'TextBlock' with 'Run' inside of them.
<TextBlock Style="{StaticResource SubText}" Margin="20" TextWrapping="Wrap" >
                     <Run x:Name="txtBlckNumberFirst" Foreground="#1ba1e2" Text="123456789123456789123456789" />
                     <Run x:Name="txtBlckNumberSecond" Text="123456789123456789123456789"  />

Inside the XAML preview this wraps just fine. At runtime though, it will always line break after the first 'Run'. I tried binding as well with the same result. Is this normal behaviour and is there an easy way to fix this?

A: If you put your Runs on separate lines a single space will be added after the first run. This single space does not show in the designer but applies at runtime (stupid, I know). So just put both Runs on the same line in your XAML.


text:
Q: Update DynamoDB row from Lambda using JSON request I have a frontend that queries then updates data in a DynamoDB table via a Lambda Function (NodeJS runtime) and API Gateway (HTTP: POST). The issue I have is the request body that goes into the Lambda to make the DynamoDB change is too verbose and I would like to simplify it into a simple JSON file.
DynamoDB current row:
{
    "primary_key": "99999999",
    "key_to_change": "old_value"
}

Lambda:
body = await dynamo.update({
                    TableName: "database-name",
                    Key: { primary_key : event.primary_key },
                    AttributeUpdates: event.body
                    }).promise();

Current Request:
    "primary_key": "99999999",
    "body": {
        "key_to_change": {
            "Action": "PUT",
            "Value": "new_value"
        },

Effect: The row with the partition key 99999999 had its key_to_change column value changed to "new_value" but the request body will eventually attempt to change 50+ values so I feel it'll be very verbose
Is there a way to modify the DynamoDB table using a JSON file like below? All actions will be PUT
Desired request body:
    "primary_key": "99999999",
    "body": {
        "key_to_change": "new_value",
        "next_key_to_change": "new_value",
        ...
    }


text:
Q: Why is the Quasitriangular Hopf algebra called "Quasitriangular"? The precise definition of a Quasitriangular Hopf algebra can be found on wikipedia.
What is the reason behind the word "Quasitriangular"?
Is it because the R-matrix  is a triangular matrix, or is it related to some properties of triangles?
Thanks for the enlightenment.


text:
Q: PowerBI Athena Beta Connector Details: "We cannot convert the value null to type Record." I am trying to connect to AWS Athena from Power BI using the new Athena connector. The first page prompts for a DSN which I supply (and which works when connecting through the old ODBC method) but when the new connector attempts to connect with this DSN the following error is thrown:

Unable to connect
We encountered an error while trying to connect.  Details: "We cannot
convert the value null to type Record."

A: I had the same issue and I figured out the reason it was happening. When you mention your DSN in the Amazon Athena (Beta), the next thing it will ask is your login (which has two options).Do not take the 2nd option. Pick the first option where the all setting are pulled from your DSN settings, which you did to setup your datasource.
Now if you once did it wrong, It won't ask you again the same things to fix it. Create a new powerbi file and do the steps.

A: As Janzaib mentioned above, you picked the wrong option when you set up your datasource. But you don't need to create a new file. You can click Data source settings and then find the name of the DSN and edit the permissions. Then the setting is pulled from your DSN and you are good to go.

A: I had to do a strange workaround to get this to work for me. When I selected the Amazon Athena connection type in PowerBI, typed in the DSN name, and hit OK, I got the error above with no way to correct it. To get it to work, I typed a dummy name in the Role entry ("xyz") before hitting OK. Then I was presented with an authentication dialog - where I could select "Use Data Source Configuration," which would work.


text:
Q: Padding for Mobile Web in Appcelerator? I'm working on an Appcelerator app. We're all new to the platform. For some reason, padding (left or right) - plus some other attributes - doesn't work for mobile web. In fact, I think it's only supported for iOS. What are we supposed to do instead? I've tried just using the CSS equivalent (e.g. padding-left: '10px') in the TSS file to no avail.
There's a bug report for it - https://jira.appcelerator.org/browse/TIMOB-7304 - but it's almost two years old and still no traction on the matter.

A: You could use a View as a container, then use top/bottom/left/right in the inner element to achieve a padding-like effect. You can see an example of that here: https://gist.github.com/asiviero/7323029, it works on Android but I haven't tested on Mobile Web

A: Instead of padding-left you should define paddingLeft: '10px'.


text:
Q: Unable to view Maps with Debug/Release APK release I am able to view google maps on Emulators and on my device when USB debugging is enabled. But when I try to generate a debug / release apk and install the apk on my device, I am unable to view the maps.
I have done the following:
a) Generated API Key in https://console.developers.google.com/ and have copied it into google_maps_api.xml of my project.
b) I have generated the necessary SHA key using the following command.
keytool.exe -list -v -alias <myalias> -keystore <my path> -storepass <passwd> -keypass <passwd>

What I am not able to understand is, how do I use the generated SHA?
As per Release APK file not showing google maps I am supposed to add the SHA key into my API key on https://console.developers.google.com/.  But, I see no such option to add it.
By installing the apk and then debugging the installed code on an emulator, I see the following exception:
API Key must not be empty.

My google_maps_api.xml is as follows:
<resources>
<string name="google_maps_key" templateMergeStrategy="preserve" translatable="false">Have added my api key here</string>

Have added my api key here --> This is where I have added the API ket that I have generated.
Have added this into my manifest file:
<meta-data
        android:name="com.google.android.geo.API_KEY"
        android:value="@string/google_maps_key" />

Can someone help me out in understanding what is it that I am supposed to do?

A: I was finally able to fix this issue and these were the steps I followed [on a windows machine, should be much more easier on a mac]:
a) cd into C:\Program Files\Java<jdk version>\bin [or wherever your jdk is installed].
b) Run: keytool -list -v -alias  -keystore "{keystore ie., .jks file loc}" -storepass {your store password} -keypass {your keypass}
c) By running the keytool cmd, your SHA1 file would then be generated.
d) Login to https://console.developers.google.com/
e) In your project there will be a google_maps_api.xml file. In this file there is a commented url, something like this: https://console.developers.google.com/flows/enableapi?apiid=maps_android_backend&keyType=CLIENT_SIDE_ANDROID&r={your SHA1 key}%3B{your project package}.
f) In the link above, replace the default SHA1 key with the newely generated key and open the link on a browser from where you already have logged into google develover console.
h) Follow the steps as prompted on the browser and with this you should be able to generate an API key.
i) Paste the generated API key here:
<string name="google_maps_key" templateMergeStrategy="preserve" translatable="false">API key</string>

This is available on your google_maps_api.xml file.
j) Now go to {your project location}\app\src\release\res\values and open the google_maps_api file. Here again, replace your API key in the location mentioned in point (i) ie., the code snippet.
k) Finally go to Android Studio > Your Project > Build > Generate Signed Bundle / APK > {input keystore path and passwords as per point (b)} > select debug/release version > Finish
The debug or release apk generated will now allow you to access google maps.


text:
Q: Pip vs Package Manager for handling Python Packages Python packages are frequently hosted in many distribution's repositories. After reading this tutorial, specifically the section titled "Do you really want to do this" I have avoided using pip and preferred to use the system repository, only resorting to pip when I need to install a package not in the repository.
However, because this is an inconsistent installation method, would it be better to only use pip? What are the benefits/detractors to using pip over the system's own repository for packages that are available in both places?
The link I included states

The advantage of always using standard Debian / NeuroDebian packages, is that the packages are carefully tested to be compatible with each other. The Debian packages record dependencies with other libraries so you will always get the libraries you need as part of the install.

I use arch. Is this the case with other package-management systems besides apt?

A: If we're talking about installing python packages to use in code you're writing, use pip.
For each project you're working on, create a virtual environment, and then only use pip to install the things that that project needs. That way, you install all the libraries you use in a consistent way, and they're contained and don't interfere with anything you install via your package manager.
If you're planning to release any python code, typically, you'll add a setup.py or requirements.txt to your project, which will allow pip to automatically get all it's dependencies. Allowing you to easily create or recreate a virtual environment for that project.

A: The biggest disadvantage I see with using pip to install Python modules on your system, either as system modules or as user modules, is that your distribution's package management system won't know about them. This means that they won't be used for any other package which needs them, and which you may want to install in the future (or which might start using one of those modules following an upgrade); you'll then end up with both pip- and distribution-managed versions of the modules, which can cause issues (I ran into yet another instance of this recently). So your question ends up being an all-or-nothing proposition: if you only use pip for Python modules, you can no longer use your distribution's package manager for anything which wants to use a Python module...
The general advice given in the page you linked to is very good: try to use your distribution's packages as far as possible, only use pip for modules which aren't packaged, and when you do, do so in your user setup and not system-wide. Use virtual environments as far as possible, in particular for module development. Especially on Arch, you shouldn't run into issues caused by older modules; even on distributions where that can be a problem, virtual environments deal with it quite readily.
It's always worth considering that a distribution's library and module packages are packaged primarily for the use of other packages in the distribution; having them around is a nice side-effect for development using those libraries and modules, but that's not the primary use-case.

A: Summary
There are three general categories of modules you're dealing with:

*

*Those supporting programs installed for all users with the OS package system. (This may even include tools and libraries used by people programming in Python; see below.) For these you use the OS packages where you can, and pip installs to the system directories where necessary.

*Those supporting programs installed by a particular user only for her own use, and also for certain aspects of her "day-to-day" use of Python as a scripting language. For these she uses pip --user, perhaps pyenv or pythonz, and similar tools and tactics.

*Those supporting development and use of a specific application. For these you use virtualenv (or a similar tool).

Each level here may also be getting support from a previous level. For example, our user in (2) may be relying on a Python interpreter installed via OS packages.
Going into this in a bit more detail:
System Programs and Packages
Programs written in Python that you want to "just run" are easy: just use the OS install tools and let them bring in whatever they need; this is no different from a non-Python program. This is likely to bring in Python tools/libraries (such as the Python interpreter itself!) that users on your machine may start to rely on; this isn't a problem so long as they understand the dependency and, ideally, know alternative means to handle it on hosts that don't provide those dependencies.
A common and simple example of such a dependency is some of my personal scripts in ~/.local/bin/ that start with #!/usr/bin/env python. These will work fine (so long as they run under Python 2) on RH/CentOS 7 and most (but not all) Ubuntu installs; they will not under a basic Debian install or on Windows. Much as I dislike my personal environment having much in the way of dependencies on OS packages (I work on a number of different OSes), something like this I find fairly acceptable; my backup plan on the rare hosts that don't have a system Python and can't get one is to go with a User system as described below.
People using a system python interpreter are also usually dependent on the system pip3. That's about where I usually draw the line on my system dependencies; everything from virtualenv forward I deal with myself. (For example, my standard activate script relies on whatever pip3 or pip is in the path, but downloads its own copy of virtualenv to bootstrap the virtual environment it's creating.
That said, there are probably circumstances where it's perfectly reasonable to make more of a development environment available. You might have Python interfaces into complex packages (such as a DBMS) where you want to use the system version of that and you feel it's best you also let the system choose the particular Python library code you'll use to talk to it. Or you may be deploying a lot of hosts with a basic development environment for a Python class, and find it easiest to automate with standard system packages.
User "Day-to-day" Programs and Packages
Users may have Python libraries or programs that don't fit well into a virtual environment because they're wanted to help create virtual environments in the first place (e.g., virtualenvwrapper) or they're things you commonly use from the command line even while doing non-Python work. Even if they do have the capability to install system versions of these, they may feel more comfortable installing their own (e.g., because they want to be using the latest version of the tool and its dependencies).
Generally pip --user is what people will be using for this, though certain dependencies, such as the Python interpreter itself, require a bit more than that. pyenv and pythonz are useful for building personal interpreters (whether installed in ~/.local/bin to be the default interpreter or otherwise), and of course one can always just build "by hand" from source if the dev libraries are available.
I try to keep the bare minimum set of things installed here: virtualenvwrapper (because I use it constantly) and perhaps the latest version of pip. I try to avoid dependencies outside the standard library or on Python 3 for personal scripts I write to be used across many hosts. (Though we'll see how long I can hold out with that as I move more and more of these personal scripts to Python.)
Separate Application Development and Runtime Environments
This is the usual virtualenv thing. For development you should almost always be using a virtualenv to ensure that you're not using system dependencies, or often more than one to test against different Python versions.
These virtual environments are also good for applications with a lot of dependencies where you want to avoid polluting your user environment. For example I usually set up a virtualenv for running Jupyter notebooks and the like.

A: TL;DR

*

*use pip (+ virtualenv) for stuff (libs, frameworks, maybe dev tools) your projects (that you develop) use

*use the package manager for applications you use (as an end-user)

Development dependencies
If you're developing software in Python, you'll want to use pip for all of the project's dependencies, be they runtime dependencies, build-time dependencies or stuff needed for automated testing and automated compliance checks (linter, style checker, static type checker ...)
There are several reasons for this:

*

*This allows you to use virtualenv (either directly or through virtualenvwrapper or pipenv or other means) to separate dependencies of different projects from each other and to isolate the python applications you use "in production" (as a user) from any exotic shenanigans (or even just incompatibilities) that may go on in development.

*This allows you to track all of a project's dependencies in a requirements.txt (if your project is an application) or setup.py (if your project is a library or framework) file. This can be checked into revision control (e.g. Git) together with the source code, so that you always know which version of your code relied on what versions of your dependencies.

*The above enables other developers to collaborate on your project even if they don't use the same Linux distribution or not even the same operating system (if the used dependencies are also available on Mac and Windows or whatever they happen to use, that is)

*You don't want automatic updates of your operating system's package manager to break your code. You should update your dependencies, but you should do so consciously and at times you choose, so that you can be ready to fix your code or roll back the update. (Which is easy if you track the complete dependency declaration in your revision control system, together with your code.)

If you feel you need to separate direct and indirect dependencies (or distinguish between acceptable version range for a dependency and actual version used, cf. "version pinning") look into pip-tools and/or pipenv. This will also allow you to distinguish between build and test dependencies. (The distinction between build and runtime dependencies can probably be encoded in setup.py)
Applications you use
For stuff that you use as normal application and that just happens to be written in Python, prefer your operating system's package manager. It'll make sure it stays reasonably up-to-date and compatible to other stuff installed by the package manager. Most Linux distributions will also assert that they don't distribute any malware.
If something you need isn't available in your distribution's default package repo, you can check out additional package repos (e.g. launchpad of deb-based distros) or use pip anyway. If the latter, use --user to install into your user's home instead of system-wide, so that you're less likely to break your Python installation. (For stuff you only need temporarily or seldom, you may even use a virtualenv.)

A: Another reason to go with the package manager is that updates will be automatically applied which is critical for security. Think if the beans package Equifax used had been automatically updated via yum-cron-security, the hack may not have happened.
On my personal dev box I use Pip, in prod I use packages.


text:
Q: How to add an mutable array of objects to another object in swift (array of classes) If I have to swift classes.
class Route : NSObject {
    var routeNo: String!
    var routeName: String!
}

and
class Stop : NSObject {
    var stopName: String!
    var routes: [Route]!
}

In my ViewController, I want to be able to add any number of routes for a stop.
var route1 = Route()
route1.routeNo = "1"
route1.routeName = "Direction for route 1"

var route2 = Route()
route2.routeNo = "2"
route2.routeName = "Direction for route 2"

// now, create a Stop object and add the two routes
var stop = Stop()
stop.stopName = "5th Avenue/3rd Street"
stop.routes.append(route1)
stop.routes.append(route2)

This unfortunately does not work. It compiles fine but get this error at run time:
fatal error: unexpectedly found nil while unwrapping an Optional value at the line stop.routes.append(route1).
I have absolutely no clue what this means. I tried all sort of condition checks but no luck.
What is the solution to be able to add any number of instances of Route the the Stop object?
Thanks

A: Your app crashes because you didn't initialise your routes array.
This should fix the problem:
class Stop : NSObject {
    var stopName: String!
    var routes: [Route] = []
}


text:
Q: Switch case statement in PHP I am learning PHP. I have downloaded an open source project from a website and looking the workflow of each modules in that project. I noticed a switch case which is unfamiliar to me.
switch ($value) {
        case 'student':
        case StudentClass::getInstance()->getId();
            return new StudentClass();
            break;
        case 'teacher':
        case TeacherClass::getInstance()->getId();
            return new TeacherClass();
            break;
        default:
            break;
    }

The above patch is what I looked.
When I give input:
$value = 'student';

It returns StudentClass instance.
If I give
$value = 'teacher';

then it returns TeacherClass instance.
If anyone explain the flow, it will be helpful to me to understanding PHP much better

A: Your string cases don't have break or return statements, so they "fall through" to the next case. Also, your breaks don't serve any purpose here.
I've added comments to your code to explain what's happening.
switch ($value) {
        case 'student': // keeps going with next line
        case StudentClass::getInstance()->getId();
            return new StudentClass(); // handles both cases above
            break; // unnecessary because of the return above
        case 'teacher': // keeps going with next line
        case TeacherClass::getInstance()->getId();
            return new TeacherClass(); // handles both cases above
            break; // unnecessary because of the return above
        default:
            break; // pointless, but handles anything not already handled
}

Also, PHP explicitly allows use of a semicolon (;) after a case, but it is not generally considered good style. From the docs:

It's possible to use a semicolon instead of a colon after a case...

A: Switch statement is used to perform different actions based on different conditions.
First we have a single expression n (most often a variable), that is evaluated once. The value of the expression is then compared with the values for each case in the structure. If there is a match, the block of code associated with that case is executed. Use break to prevent the code from running into the next case automatically. The default statement is used if no match is found.

switch (n) {
    case label1:
        code to be executed if n=label1;
        break;  // if n=label1,break ends execution and exit from switch
    case label2:
        code to be executed if n=label2;
        break;  // if n=label2,break ends execution and exit from switch
    case label3:
        code to be executed if n=label3;
        break;  // if n=label3,break ends execution and exit from switch
    ...
    default:
        code to be executed if n is different from all labels;
}


text:
Q: Viewport on Opera Mini & WM6.1 does not match 100% of the `device-width`
*

*sample page: 256.cz/test/
with code: meta name="viewport" content="width=device-width, initial-scale=1.0, minimum-scale=1.0, maximum-scale=1.0, user-scalable=no, target-densitydpi=device-dpi"

*same CSS style for mobile view and normal view

*latest Opera Mini from Android Market (Android version 2.1) - scale is not 100% :-(

*latest Opera Mini from site Opera (Windows Mobile 6.1, Native Opera Mini, Not Java) - scale is not 100% :-(

*latest Opera Mini from site Opera (Sony Ericsson W995) - scale 100% :-)

*latest Opera Mini from site Opera (BlackBerry) - scale 100% :-)

How to achieve proper display (scale 100%) on all mobile devices?

A: Opera Mini will set the device-width to something that makes sense, considering font size and so on. E.g. on the HTC Desire, the default zoom level is 170%, resulting in a device-width of 282px (480px/1.7). target-densitydpi=device-dpi however is only supported by Opera Mobile, not by Opera Mini.
In other words, at present, there is no way to force that 1 CSS pixel equals 1 device pixel on Opera Mini.


text:
Q: Get formatting information in Excel I'm working on an excel template with formatting, and I'm using python to insert data into the template.
The formatting is turning out REALLY weird. Some of the columns are becoming unformatted, but others later are still formatted, and if I change the textcolor of some columns, then those columns have the rows background color correct, but others don't.
Anyway, it's weird.
What I'd like is a way to see (in a NON WISIWYG way) what Excel thinks it's doing. Maybe something that was vaguely HTML-ish? Decades ago, you used to be able to do this in word processors (I mean like Word Perfect 4.2 era).

A: As @Blackwood already mentioned in the comment, a .xlsx file is just a zip file with a defined folder and file structure. If you want to dig into how Excel stores formatting, rename an Excel file to .zip und unpack it. You will see a structure like this:
_rels
docProps
xl
 +-- _rels
 +-- worksheets
 |    +-- sheet1.xml
 +-- sharedStrings.xml
 +-- styles.xml   <-- this is what you are after :-)
 +-- workbook.xml
[Content_Types].xml

If your want to learn about formattinng and styles, examine this file. The general structure like this:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<styleSheet
xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main">
    <numFmts />
    <fonts />
    <fills />
    <borders />
    <cellStyleXfs />
    <cellXfs />
    <cellStyles />
</styleSheet>

I left out the content of each element, but the numFmts element stores Number (and Date etc.) formats. Here you also find the internal ID of a format. Let's have a look at the most simple content:
    <numFmts count="1">
        <numFmt formatCode="GENERAL" numFmtId="164"/>
    </numFmts>

Just the defaults: we have one format, the "GENERAL" format. Fill format and background color are stores in the fills element. I made a simple example:
    <fills count="1">
        <fill>
            <patternFill patternType="solid">
                <fgColor rgb="FF00FF00"/>
                <bgColor rgb="FF33CCCC"/>
            </patternFill>
        </fill>
    </fills>

Here you see the patternType you may specify and color values. Maybe you want to post the Python package you are using, because most packages are able to write such formatting information as well as setting column width. I gave up on templates for my project and write everything directly from Python using a very simple DSL that describes a cell entry in a text line that my script parses. Looks like so:
<addr>|<content>|<format>|<alignment>|<color>
example:
  C2|=A2*B2|#0.00|right|#0000FF@#CCCCCC
  A1|"Text"||center|#000000

Makes it easy to just have a list of strings in my script and use this as template. I do not need a template anymore and as we have a struct spec for the layout and formatting, no one can accidentally "improve" it. :-)


text:
Q: Why is this Basic XPath Selector Not Working Here's my basic structure:

    <form>
         ......

I'm trying to select elements from within the form, but XPath isn't finding anything past the primarycontentblock div.
The first query finds the parent node, but the second query finds nothing.
$dom->query('//*[@id="PrimaryContentBlock"]');
$dom->query('//*[@id="PrimaryContentBlock"]/form');

Any idea why XPath would be acting so strange? I've been seeing a lot of inconsistent behavior when working with DOMXPath queries.

A: One way this could happen is if you have an XHTML document (with an xmlns decalaration on the root html element) and you are parsing it as XML. In such a document all the elements are part of the http://www.w3.org/1999/xhtml namespace, and you need to specify this when querying.
Your first query, //*[@id="PrimaryContentBlock"], will find any element with a matching id attribute, including those in the XHTML namespace (that's what the * means). The second query, //*[@id="PrimaryContentBlock"]/form is looking for form elements that are not in any namespace. This fails to match the document since all form elements are in the default XHTML namespace.
The simplest way to fix this, if this is an XHTML document, is to parse it as HTML. If you currently are doing something like:
$domdocument->loadXML(...);

change it to use loadHTML:
$domdocument->loadHTML(...);

If you want to parse the document as XML, then you need to specify the namespace in your query. First you need to register the namespace uri and prefix you are going to use with the DOMXPath instance, then change your query to include the new prefix:
$xpath = new DOMXPath($doc);
$xpath->registerNamespace('xhtml', "http://www.w3.org/1999/xhtml");

$result = $xpath->query('//*[@id="PrimaryContentBlock"]/xhtml:form')

A: Given you have the above structure, and you are sure that the document is well-formed both of your queries WILL work:
$xml = <<<EOF

    <form></form>

EOF;

$doc = new DOMDocument();
$doc->loadHTML($xml);
$selector = new DOMXPath($doc);

foreach($selector->query('//*[@id="PrimaryContentBlock"]/form') as $element) {
    echo $element->nodeName;
}

Output:
form

If the following sentence is true for you:

I've been seeing a lot of inconsistent behavior when working with DOMXPath queries.

... then you have either not enough expertise with XPath, or your input data isn't well formed. At least one those both reasons apply to me when I have problems with a certain query.


text:
Q: how to use user_data in ansible playbook while I am creating the instance using ansible playbook instance is createing but the user_data is not applied to that instance
- name: create an EC2 instance with SSD volume type
  ec2:
    key_name: apex-1
    group: dmz
    instance_type: m3.xlarge
    region: "{{ aws_region }}"
    aws_access_key: "{{ aws_access_key }}"
    aws_secret_key: "{{ aws_secret_key }}"
    image: ami-d1315fb1
    assign_public_ip: yes
    vpc_subnet_id: "{{ my_public_subnet.subnet.id }}"
    volumes:
      - device_name: /dev/xvda
        volume_type: gp2  #insert the volume code here
        volume_size: 40  #size is in GB
    wait : true
    wait_timeout: 500
    group_id: security_group.group_id
    user_data: |
               #!/bin/sh
                sudo wget =http://download.memsql.com/memsql-ops-5.8.4/memsql-ops-5.8.4.tar.gz
                sudo tar -xvzf memsql-ops-5.8.4.tar.gz
                sudo sh memsql-ops-5.8.4/install.sh
                sudo yum install mysql -y
    count_tag:
      Name: apacheserver
    exact_count: 1
  register: ec2


text:
Q: Axios GET request working in plain js but not working in react - CORS error When I make a GET request inside in react, I get blocked by CORS policy error. However if I make the same request inside vanilla js (a simple .js file) I get the appropriate response.
Here is my code in the react:
const axios = require('axios');

function getLatestPrice() {
  const config = {
    url: 'https://api.kraken.com/0/public/Trades?pair=ETHUSDT&since=1656322000',
    method: 'GET'
  };

  return axios(config);
}

exports.getLatestPrice = getLatestPrice;

I get the following error:
Access to XMLHttpRequest at 'https://api.kraken.com/0/public/Trades?pair=ETHUSDT&since=1656322000' from origin 'http://localhost:3000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

My code in vanilla js file
const axios = require('axios');

const url = "https://api.kraken.com/0/public/Trades?pair=ETHUSDT&since=1656322000";

const config = {
  url: url,
  method: "GET"
};

axios(config).then(res => {
  console.log(res.data);
}).catch(err => {
  console.log(err);
});

Here I am getting the correct response. The postman request to the same is also working.
(I am not controlling the API backend)


text:
Q: gui shutdown on acer aspire v5-573G not working When I press the gui shutdown button, the system is not powering off, but rather just remains at splash screen. Hence, I always have to power off the machine manually holding the power button. Issuing shutdown -h or shutdown -P from command line works fine while shutdown -H causes the same problem as the gui shutdown.
I use ubuntu 13.10 (uefi version) on an Acer Aspire V5-573G.
Adding the line "INIT_HALT = POWEROFF" to /etc/default/halt as suggested here does not help.
Any suggestions are very welcome!

A: FIx with Ubuntu 13.10 is installed in Acer aspire v5-573 laptop, uefi boot.
 wget http://kernel.ubuntu.com/~kernel-ppa/mainline/daily/current/linux-headers-3.13.0-999-generic_3.13.0-999.201312270405_amd64.deb

 wget http://kernel.ubuntu.com/~kernel-ppa/mainline/daily/current/linux-headers-3.13.0-999_3.13.0-999.201312270405_all.deb

 wget http://kernel.ubuntu.com/~kernel-ppa/mainline/daily/current/linux-image-3.13.0-999-generic_3.13.0-999.201312270405_amd64.deb

 sudo dpkg -i linux-headers-3.13.0-*.deb linux-image-3.13.0-*.deb

then reboot

A: It is a bug. Fixed in latest kernel 3.13-rc5.


text:
Q: Passing a Param to System.EventHandler in c# Since google has failed me for the past 5-10 minutes I have a quick question. I wish to pass a param value into a function that I call from a button.click Event Handler. The event is currently added using
MyButton.Click = new System.EventHandler(MyButton_click);

But I want the function to recieve:
private void MyButton_click(int ID)
{
...
}

How can I change my EventHandler declaration so that this can be accomplished?

A: Button.Click is defined as it is, and there is no way to change it. However,
myButton.Click += delegate { MyButton_click(1); }

will do the job.

A: you can use CommandArgument property and then cast a sender in your event handler to a Button type to get the CommandArgument value