text:
Q: Getting crash on android All of my code was working properly until I attempted to add in the date. When i did that, the applications crashes on Launch. Here is what I have so far:
activity_main.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >

<!-- Header -->

<TextView
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:background="#000000"
    android:textColor="#FFFFFF"
    android:gravity="center"
    android:layout_marginTop="20dp"
    android:id="@+id/Header"
    android:text=""
/>

<!-- Name -->

<TextView
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:layout_marginLeft="50dp"
    android:id="@+id/Name"
    android:text=""
/>

<!-- Project Name -->

<TextView
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:layout_marginLeft="50dp"
    android:id="@+id/ProjectName"
    android:text=""
/>

<!-- Digital Clock -->

<DigitalClock
    android:id="@+id/DigitalClock"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginLeft="50dp"
    android:text=""
/>

<!-- Calendar -->

<TextView
    android:id="@+id/stringCalendar"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginLeft="50dp"
    android:text=""
/>

<!-- End of Program -->

<TextView
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:textColor="#FFFFFF"
    android:background="#000000"
    android:gravity="center"
    android:id="@+id/EndOfProgram"
    android:text=""
/>

</LinearLayout>

MainActivity.java:
package com.example.d1project1;

import java.util.Calendar;

import android.os.Bundle;
import android.app.Activity;
import android.widget.DigitalClock;

import android.widget.TextView;

@SuppressWarnings({ "deprecation", "unused" })
public class MainActivity extends Activity {
    //Declare GUI objects

    TextView stringHeader;
    TextView stringName;
    TextView stringProject;
    TextView digitalClock1;
    TextView stringEnd;

    TextView stringCalendar;
    TextView stringDisplay;
    DigitalClock DigitalClock;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        Init_GUI();
        DigitalClock();
        Nonevent_Event();
    }

    private void DigitalClock() {
        //DigitalClock
        DigitalClock = (DigitalClock)findViewById(R.id.DigitalClock);
    }
    private void Nonevent_Event() {
        String stringDate = "";

        Date_Class.date_time(stringCalendar);

        stringCalendar.setText(stringDate);
    }

    //method to link GUI items to code
    private void Init_GUI() {
        stringHeader = (TextView)findViewById(R.id.Header);
        stringName = (TextView)findViewById(R.id.Name);
        stringProject = (TextView)findViewById(R.id.ProjectName);
        stringEnd = (TextView)findViewById(R.id.EndOfProgram);

        stringHeader.setText("Day 1 Project 1 - Travis Finlan");
        stringName.setText("Travis Finlan");
        stringProject.setText("Day 1 Project 1");
        stringEnd.setText("End of Program");
    }
}

Date_Class.java:
package com.example.d1project1;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Calendar;

import android.widget.DigitalClock;
import android.widget.TextClock;
import android.widget.TextView;

public class Date_Class {
    public static String date_time(TextView stringCalendar) {
        //Calendar
        Calendar c = Calendar.getInstance();
        System.out.println("Current time => " + c.getTime());

        SimpleDateFormat df = new SimpleDateFormat("dd-MMM-yyyy");
        String formattedDate = df.format(c.getTime());

        return formattedDate;
    }
}

Also, if you see any errors, please let me know. I can't seem to figure out why it keeps crashing on me. I just want it to show the current date along with the current time. I have to have all the methods in the non-instantiated class, so they have to be pulled over.
LogCat Information
02-19 17:02:17.785: DEBUG/AndroidRuntime(2095): >>>>>>>>>>>>>> AndroidRuntime START <<<<<<<<<<<<<<
02-19 17:02:17.785: DEBUG/AndroidRuntime(2095): CheckJNI is ON
02-19 17:02:17.885: DEBUG/AndroidRuntime(2095): --- registering native functions ---
02-19 17:02:17.915: INFO/jdwp(2095): Ignoring second debugger -- accepting and dropping
02-19 17:02:18.305: DEBUG/AndroidRuntime(2095): Shutting down VM
02-19 17:02:18.305: DEBUG/dalvikvm(2095): Debugger has detached; object registry had 1 entries
02-19 17:02:18.327: INFO/AndroidRuntime(2095): NOTE: attach of thread 'Binder Thread #3' failed
02-19 17:02:18.635: DEBUG/AndroidRuntime(2103): >>>>>>>>>>>>>> AndroidRuntime START <<<<<<<<<<<<<<
02-19 17:02:18.635: DEBUG/AndroidRuntime(2103): CheckJNI is ON
02-19 17:02:18.736: DEBUG/AndroidRuntime(2103): --- registering native functions ---
02-19 17:02:18.755: INFO/jdwp(2103): Ignoring second debugger -- accepting and dropping
02-19 17:02:19.175: INFO/ActivityManager(59): Starting activity: Intent { act=android.intent.action.MAIN cat=[android.intent.category.LAUNCHER] flg=0x10000000 cmp=com.example.d1project1/.MainActivity }
02-19 17:02:19.195: INFO/ActivityManager(59): Start proc com.example.d1project1 for activity com.example.d1project1/.MainActivity: pid=2109 uid=10036 gids={}
02-19 17:02:19.225: DEBUG/AndroidRuntime(2103): Shutting down VM
02-19 17:02:19.225: DEBUG/dalvikvm(2103): Debugger has detached; object registry had 1 entries
02-19 17:02:19.275: INFO/dalvikvm(2103): JNI: AttachCurrentThread (from ???.???)
02-19 17:02:19.275: INFO/AndroidRuntime(2103): NOTE: attach of thread 'Binder Thread #3' failed
02-19 17:02:19.365: INFO/jdwp(2109): Ignoring second debugger -- accepting and dropping
02-19 17:02:19.679: INFO/System.out(2109): Current time => Wed Feb 19 17:02:19 CST 2014
02-19 17:02:19.686: DEBUG/AndroidRuntime(2109): Shutting down VM
02-19 17:02:19.686: WARN/dalvikvm(2109): threadid=1: thread exiting with uncaught exception (group=0x4001d800)
02-19 17:02:19.696: ERROR/AndroidRuntime(2109): FATAL EXCEPTION: main
02-19 17:02:19.696: ERROR/AndroidRuntime(2109): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.d1project1/com.example.d1project1.MainActivity}: java.lang.NullPointerException
02-19 17:02:19.696: ERROR/AndroidRuntime(2109):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2663)
02-19 17:02:19.696: ERROR/AndroidRuntime(2109):     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2679)
02-19 17:02:19.696: ERROR/AndroidRuntime(2109):     at android.app.ActivityThread.access$2300(ActivityThread.java:125)
02-19 17:02:19.696: ERROR/AndroidRuntime(2109):     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2033)
02-19 17:02:19.696: ERROR/AndroidRuntime(2109):     at android.os.Handler.dispatchMessage(Handler.java:99)
02-19 17:02:19.696: ERROR/AndroidRuntime(2109):     at android.os.Looper.loop(Looper.java:123)
02-19 17:02:19.696: ERROR/AndroidRuntime(2109):     at android.app.ActivityThread.main(ActivityThread.java:4627)
02-19 17:02:19.696: ERROR/AndroidRuntime(2109):     at java.lang.reflect.Method.invokeNative(Native Method)
02-19 17:02:19.696: ERROR/AndroidRuntime(2109):     at java.lang.reflect.Method.invoke(Method.java:521)
02-19 17:02:19.696: ERROR/AndroidRuntime(2109):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:868)
02-19 17:02:19.696: ERROR/AndroidRuntime(2109):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:626)
02-19 17:02:19.696: ERROR/AndroidRuntime(2109):     at dalvik.system.NativeStart.main(Native Method)
02-19 17:02:19.696: ERROR/AndroidRuntime(2109): Caused by: java.lang.NullPointerException
02-19 17:02:19.696: ERROR/AndroidRuntime(2109):     at com.example.d1project1.MainActivity.Nonevent_Event(MainActivity.java:44)
02-19 17:02:19.696: ERROR/AndroidRuntime(2109):     at com.example.d1project1.MainActivity.onCreate(MainActivity.java:32)
02-19 17:02:19.696: ERROR/AndroidRuntime(2109):     at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)
02-19 17:02:19.696: ERROR/AndroidRuntime(2109):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2627)
02-19 17:02:19.696: ERROR/AndroidRuntime(2109):     ... 11 more
02-19 17:02:19.706: WARN/ActivityManager(59):   Force finishing activity com.example.d1project1/.MainActivity
02-19 17:02:19.706: WARN/ActivityManager(59):   Force finishing activity com.android.mms/.ui.ConversationList
02-19 17:02:20.206: WARN/ActivityManager(59): Activity pause timeout for HistoryRecord{4a4c5dd0 com.example.d1project1/.MainActivity}
02-19 17:02:24.827: INFO/Process(2109): Sending signal. PID: 2109 SIG: 9
02-19 17:02:24.846: INFO/ActivityManager(59): Process com.example.d1project1 (pid 2109) has died.
02-19 17:02:26.416: DEBUG/dalvikvm(233): GC_EXPLICIT freed 4119 objects / 277728 bytes in 123ms
02-19 17:02:31.137: WARN/ActivityManager(59): Activity destroy timeout for HistoryRecord{4a4c5dd0 com.example.d1project1/.MainActivity}
02-19 17:02:39.466: DEBUG/SntpClient(59): request time failed: java.net.SocketException: Address family not supported by protocol

A: You never set the field stringCalendar in class MainActivity. Therefore you get a NullPointerException from this line:
stringCalendar.setText(stringDate);


text:
Q: session management in standalone applications I have a standalone application which can be installed on multiple machines.
Need to do session management for each user.
Currently we are maintaining a database table to save userid,login and logout time and login status.(which is"Y" when user is logged in and "N: when user has logged out.) This allows a user to login to only one instance of the application.
Now the issue is: If system crashes on one Machine, the status remains "Y" for that user in the DB,
and doesnt allow the user to login again.How to Identify a system crash?
Alternatively, how to store login information wrt Mac Id's?
Thanks!

A: Always override the last login.
For example there is terminal A and terminal B
When user logs in on terminal A he has an instance there.
When he switches to terminal B login goes as normal, but anyone else working on terminal A will be forcibly logged out.
Thats the way the remote desktop of windows works, and it prevents a lot of the issues you encounter with other mechanics.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Invertible matrix is product of diagonalizable and matrix with eigenvalues 1 I'm studying for an algebra exam, and this question was on a previous test:

Let $A$ be an invertible $n \times n$ complex matrix. Show that $A$ can be written as $$A = MN = NM$$ where $M$ is diagonalizable and all eigenvalues of $N$ are equal to 1.

I'm not really sure how to approach this sort of question; I know about Jordan normal form and rational canonical form and conceptually what eigenvalues are, but I don't have a sense of how to put all the information together to solve something like this. Any help would be appreciated!

A: You know the Jordan normal form. Show that each Jordan block can be written in the required form, with $M=\lambda I$.
Finally conjugate the $M$ and $N$ block matrices back to the original coordinate system.

A: You know that $A$ is similar to an upper triangular matrix $T$. And an upper triangular matrix can be written as the product of a diagonal matrix $D$ (whose main diagonal consists of the elements of the main diagonal of $T$) and an upper triangular matrix $T^\star$ whose entries of the main diagonal are all equal to $1$.


text:
Q: Why is extended slice assignment less flexible than regular slice assignment? According to the Python documentation on extended slices:

If you have a mutable sequence such as a list or an array you can
  assign to or delete an extended slice, but there are some differences
  between assignment to extended and regular slices. Assignment to a
  regular slice can be used to change the length of the sequence:
>>> a = range(3)
>>> a
[0, 1, 2]
>>> a[1:3] = [4, 5, 6]
>>> a
[0, 4, 5, 6]

Extended slices aren't this flexible. When assigning to an extended
  slice, the list on the right hand side of the statement must contain
  the same number of items as the slice it is replacing:
>>> a = range(4)
>>> a
[0, 1, 2, 3]
>>> a[::2]
[0, 2]
>>> a[::2] = [0, -1]
>>> a
[0, 1, -1, 3]
>>> a[::2] = [0,1,2]
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
ValueError: attempt to assign sequence of size 3 to extended slice of size 2

I do not understand why the "ordinary" slice method works but the "extended" slice method doesn't work. What differentiates an "ordinary" slice from an "extended" slice, and why does the "extended" slice method fail?

A: It's a little easier to see the problem if you try to imagine how
a[::3] = [0, 1, 2]

would work with a 4-item list:
+---+---+---+---+   +   +---+
| a | b | c | d |       | ? |
+---+---+---+---+   +   +---+
  ^           ^           ^
+---+       +---+       +---+
| 0 |       | 1 |       | 2 |
+---+       +---+       +---+

We're trying to replace every third value, but our list isn't long enough, so if we went ahead anyway we'd end up with some kind of weird frankenstein list where some of the items don't actually exist. If someone then tried to access a[5] and got an IndexError (even though a[6] works normally), they'd get really confused.
Although you could technically get away with the a[::2] case by extending a by one, for the sake of consistency, Python bans all extended slicing assignments unless there's already a place for the value to go.
A regular slice always has a stride of one, so there's no chance of any gaps occurring, and so the assignment can safely be allowed.


text:
Q: iOS firebase login my firebase login screen crashes when trying to login
Here is the error:
2018-05-02 09:39:25.937258-0400 noteCollab[2418:625945] * Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'The link provided is not valid for email/link sign-in. Please check the link by calling isSignInWithEmailLink:link: on Auth before attempting to use it for email/link sign-in.'
* First throw call stack:
(0x1837d6d8c 0x1829905ec 0x1837d6c6c 0x1008aa3e0 0x10089c0b8 0x10089cd08 0x10089b808 0x101a29260 0x101a29220 0x101a37e80 0x101a2c730 0x101a38dd8 0x101a3febc 0x1833fbe70 0x1833fbb08)
libc++abi.dylib: terminating with uncaught exception of type NSException
(lldb)
Here is my code:
    //
//  signinViewController.swift
//  noteCollab
//
//  Created by James Hall on 5/2/18.
//  Copyright © 2018 James Hall. All rights reserved.
//

import UIKit
import Firebase
import FirebaseAuth

class signinViewController: UIViewController {

    @IBOutlet weak var signInSelector: UISegmentedControl!
    @IBOutlet weak var signInLabel: UILabel!
    @IBOutlet weak var emailTextField: UITextField!
    @IBOutlet weak var passwordTextField: UITextField!
    @IBOutlet weak var signInButton: UIButton!

    var isSignIn:Bool = true

    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

    @IBAction func signInSelectorChanged(_ sender: UISegmentedControl) {

        isSignIn = !isSignIn
        if isSignIn {
            signInLabel.text = "Sign In"
            signInButton.setTitle("Sign In", for: .normal)
        }else{
            signInLabel.text = "Register"
            signInButton.setTitle("Register", for: .normal)
        }

    }

    @IBAction func signInButtonTapped(_ sender: UIButton) {

        if let email = emailTextField.text, let pass = passwordTextField.text{
            //check if its sign in or register
            if isSignIn{
                //sign in the user with Firebase
                Auth.auth().signIn(withEmail: email, link: pass) { (user, error) in
                    // check that user isnt nil
                    if error != nil{
                        print("cant sign in user")
                    }else{

                        self.performSegue(withIdentifier: "goToHome", sender: self)

                    }
                }
            }else{
                //register the user with Firebase

                Auth.auth().createUser(withEmail: email, password: pass) { (user, error) in
                    // check that user isnt nil
                    if let u = user {

                        //user is found, go to home
                        self.performSegue(withIdentifier: "goToHome", sender: self)

                    }else{
                        //error: check error and show message
                    }
                }

            }
        }

    }

}

A: Your sign in code is looking for an email link instead of a password. Simply change the word "link:" to "password:" and you should be all set.
Auth.auth().signIn(withEmail: email, password: password)


text:
Q: Download image not being displayed iOS Swift I'm trying to download images and display them based on different conditions. The code worked if I was to simply download the images in the main thread, but I am trying to download them through the back end now.
My console is clean, so I'm not getting any errors - yet my images are not being displayed? This is my first attempt at doing back end image downloading and also doing swift as I come from objective-c.
Could someone please look at the code below and let me know what the problem is?
//FizzBuzz Image Download
weak var fizzBuzzImage: UIImage!
let fizzBuzzString = "https://emkaydeum.files.wordpress.com/2015/08/fizzbuzz.png"
var fizzBuzzURL:NSURL!

//Fizz Image Download
weak var fizzImage: UIImage!
let fizzString = "https://vignette2.wikia.nocookie.net/leagueoflegends/images/b/b0/Fizz_Render.png/revision/latest?cb=20151205185848"
var fizzURL:NSURL!

//Buzz Image Download
weak var buzzImage: UIImage!
let buzzString = "https://vignette2.wikia.nocookie.net/disney/images/b/bc/Buzz_Disney_INFINITY_Render.png/revision/latest?cb=20140605182818"
var buzzURL:NSURL!

override func viewDidLoad() {
    super.viewDidLoad()

    fizzBuzzURL = NSURL(string: fizzBuzzString)
    fizzURL = NSURL(string: fizzString)
    buzzURL = NSURL(string: buzzString)
}

@IBAction func checkTextField(_ sender: UITextView){

    enteredValue = userInput.text

    let checkIfEmpty = userInput.text?.isEmpty

    if (checkIfEmpty == false) {
    let multipleOf3:Int = Int(enteredValue)!%3
    let multipleOf5:Int = Int(enteredValue)!%5

        if (multipleOf3 == 0 && multipleOf5 == 0) {
            fizzBuzz.text = "FizzBuzz"
            URLSession.shared.dataTask(with: (fizzBuzzURL as URL), completionHandler: {(fizzBuzzData, resp, error) -> Void in
                if (error != nil && fizzBuzzData != nil){
                    OperationQueue.main.addOperation ({
                        self.displayImage.image = UIImage(data: fizzBuzzData!)
                    })
                }
                }).resume()}
        else if (multipleOf5 == 0){
            fizzBuzz.text = "Buzz"
            URLSession.shared.dataTask(with: (buzzURL as URL), completionHandler: {(buzzData, resp, error) -> Void in
                if (error != nil && buzzData != nil){
                    OperationQueue.main.addOperation ({
                        self.displayImage.image = UIImage(data: buzzData!)
                })
                }
                }).resume()}
        else if (multipleOf3 == 0){
            fizzBuzz.text = "Fizz"
            URLSession.shared.dataTask(with: (fizzURL as URL), completionHandler: {(fizzData, resp, error) -> Void in
                if (error != nil && fizzData != nil){
                    OperationQueue.main.addOperation ({
                        self.displayImage.image = UIImage(data: fizzData!)
                })
                }
                }).resume()}
        else {
            fizzBuzz.text = "Incorrect Value"
            displayImage.image = nil
        }
    }
}

A: Please check for your IF conditions. You have written
if (error != nil && fizzBuzzData != nil){
                    OperationQueue.main.addOperation ({
                        self.displayImage.image = UIImage(data: fizzBuzzData!)
                    })
                }

which never executed. Please make it as below
 if (error == nil && fizzBuzzData != nil){
                    OperationQueue.main.addOperation ({
                        self.displayImage.image = UIImage(data: fizzBuzzData!)
                    })
                }

A: set
uiimageview contentMode is scaleAspectFill
and clipsToBounds true


text:
Q: How to troubleshoot ASK ChangeReport failing with INVALID_REQUEST_EXCEPTION Summary: I am getting an INVALID_REQUEST_EXCEPTION response when attempting to submit a ChangeReport event.
I'm troubleshooting with postman.
POSTing to: https://api.amazonalexa.com/v3/events
One header: Authorization with my token (if this is wrong, I get the correct error)
My body:
{
    "event":{
        "header":{
            "messageId":"06a6278a-0c38-47e5-90e9-12eef0205487",
            "namespace":"Alexa",
            "name":"ChangeReport",
            "payloadVersion":"3"
        },
        "endpoint":{
            "scope":{
                "type":"BearerToken",
                "token":"XXX My Token XXX"
            },
            "endpointId":"BedroomLight"
        },
        "payload":{
            "change": {
                "cause" : {
                    "type" : "PHYSICAL_INTERACTION"
                },
                "properties":[
                {
                    "namespace": "Alexa.PowerController",
                    "name": "powerState",
                    "value": "ON",
                    "timeOfSample": "2019-03-09T15:22:48Z",
                    "uncertaintyInMilliseconds": 500
                }]
            }
        }
    }
}

The response:
{
    "header": {
        "namespace": "System",
        "name": "Exception",
        "messageId": "bb7a3bb7-5c2c-4568-8a31-ae24a075f15e"
    },
    "payload": {
        "code": "INVALID_REQUEST_EXCEPTION",
        "description": "The request was malformed."
    }
}

My input passes the schema validation.
I've tried substituting known invalid values to see if I could shift the error message and narrow down the root cause.
I compared to other code examples in Github and I'm not seeing an obvious error.
I'm not sure how to narrow the problem scope.

A: Contrary to my understanding above, I was not using the correct BearerToken. I was using the original OAuth code provided in the grant response (I didn't understand the LoginWithAmazon/LWA portion of the security exchange).
The further mistake that made this difficult was the lack of a security error.  When I created the Authorization header, I left out the type (Bearer) and just had my value in the value area of the header, which might have been the base reason for the format error.


text:
Q: Remove first part of a string based on unique tag I am looking for a way to remove everything between
SOME TEXT
. The good news is that the string always uses
SOME TEXT
 - the bad news is that the text within that p tag always changes.
What I am looking for is to not only remove the text between

 but also the complete

 section.
Example String:

New York, NY  August 19, 2013

Kaminski Auctions is pleased to announce the addition of Sheri Mason to our team of expert appraisers.

What I am looking for is to get this result:

Kaminski Auctions is pleased to announce the addition of Sheri Mason to our team of expert appraisers.

That said, if my string contains the

 then I would like to have it removed, no matter what text is within the tags, but keep everything else in tact.
I am still pretty new to PHP as I just do some small jobs for friends now and then, so I tried some stuff with str_replace but since the content within the element is never the same, I am having issues understanding how I would go from there.
Your help is greatly appreciated.

A: You can use this (where $str holds your content):
preg_replace('/
(.*)
/g', '', $str);

Have a look here:  http://regexr.com?360sd

A: <?php
$myString = '
New York, NY  August 19, 2013

Kaminski Auctions is pleased to announce the addition of Sheri Mason to our team of expert appraisers.
';
$tab1 = explode('
', $myString);
if(isset($tab1[1])){
  $tab2 = explode('
', $tab1[1]);
  $myString = $tab2[1];
}
echo $myString;
?>


text:
Q: Dynamically Select SQL Server Column Names When Value is Not Null I have a summary fact table in my SQL Server data warehouse that has Order QTY by Order Number and Product Type. I would like to use this to generate a table that shows order composition (qty of each type) as a text field for reporting.
The original data looks like this:
ORDER_NBR   PRODUCT_TYPE    ORDER_QTY
-----------------------------------------
ABC123      PANTS       1
ABC123      SHIRTS      1
DEF456      SHIRTS      2
HIJ789      JACKETS     1
HIJ789      SHIRTS      2
KLM012      PANTS       2

I was able to get as far as here by using dynamic pivot.
ORDER_NBR   JACKETS     PANTS       SHIRTS
-------------------------------------------------------
ABC123      (NULL)      1           1
DEF456      (NULL)      (NULL)      2
HIJ789      1           (NULL)      2
KLM012      (NULL)      2           (NULL)

I would now like to turn this data into the following:
ORDER_NBR   ORDER_COMPOSITION
----------------------------------
ABC123      1 PANTS, 1 SHIRTS
DEF456      2 SHIRTS
HIJ789      1 JACKETS, 2 SHIRTS
KLM012      2 PANTS

Is there a way to dynamically select the column name and value only when the value is not null, then concatenate them together into a sigle field?

A: You don't need to PIVOT the data to get this result. You can simply concatenate the result using STUFF and FOR XML PATH:
select
  t1.order_nbr,
  STUFF(
         (SELECT ', ' + cast(order_qty as varchar(10)) + ' ' + product_type
          FROM yourtable t2
          where t1.order_nbr = t2.order_nbr
          FOR XML PATH (''))
          , 1, 1, '')  AS order_composition
from yourtable t1
group by t1.order_nbr;

See SQL Fiddle with Demo. The PIVOT is totally unnecessary to get the result.  This query will get you the result without any need to use dynamic sql:
| order_nbr |    order_composition |
|-----------|----------------------|
|    ABC123 |    1 PANTS, 1 SHIRTS |
|    DEF456 |             2 SHIRTS |
|    HIJ789 |  1 JACKETS, 2 SHIRTS |
|    KLM012 |              2 PANTS |


text:
Q: where to map my all dimensions and facts in jasper ireport My databse is oracle 11.1 and Jasper iReport server 5.6
My requirement is to generate level wise reports from all dimensions and facts
then where do i map these dimensions and facts in jasper ireport designer
I have 52 dimensions and 13 facts
Thanks
 Ragav

A: When we Right click on the Report name in the Outline Tab you can see the "Database Query" their you can define the Relationship between fact and dimensions using SQL query.
If any issues let me know.


text:
Q: What's the best way to gear up for heroics in Mists of Pandaria? I have just reached 90 and my gearscore is way short of the one required for heroics. I am just wondering whether there is another way to improve my gearscore without having to grind reputation points with the various MoP factions?
Even if I eventually manage to get the reputation required to buy JP gear, then how do I go about earning JP? I can no longer randomly queue normal dungeons at 90 (I can manually select them, but that doesn't give me the seven times per week JP bonus). Essentially I am in a bit of limbo.
According to this unhelpful comment by Manbullpig, apparently it only takes 15 minutes to gear up for heroics at 90. I am not quite sure whether he was exaggerating or if it's true.

A: Players are expected to gather gear pre-heroics from:

*

*Questing, especially completing long questing chains around level 89 and 90 that reward a blue

*Doing normal dungeons at level 88 through 90. There is enough blue gear here to do heroics in.

*Cashing in any Justice points from level 85 at the justice point vendor (no reputation required*)

*Grinding out reputation with factions that award blue gear at honored (not that much of a grind).

*Doing Scenarios at level 90, there is a ring of valor style scenario that rewards a blue weapon (Arena of Annihilation)

If your falling short, you might have abandoned long quest chains too early, or didn't do any dungeons (or just got unlucky). Dungeon quests themselves reward a guaranteed couple of blues as a reward for their first playthrough.
**source: Patch 5.0.5 October 1st Hotfixes: Players no longer require Honored reputation with Mists of Pandaria factions to purchase gear with Justice Points.*

A: You need ilevel 435 for Heroic Dungeons.
Based on this article, the easiest options are:
ilevel 435 Gate of Setting Sun / Shado-Pan Monastary (normal)
ilevel 437 Dread Wastes quest rewards (green)
ilevel 442 Townlong Steppes quests rewards (blue)
ilevel 450 Dread Wastes quests rewards (blue)  <--- start here if you are 90
ilevel 458 Justice Points / Honor Points
ilevel 463 Scenarios  (requires ilevel 425 for entry)

Check the auction house for BoE world drops and level 90 crafted gear.
There's also BoA archaeology gear.
Also the Sha of Anger drops a one time quest item you can turn in for a set of epic boots. And killing Galleon has a chance for you to get raid gear from Galleon and Sha of Anger each week


text:
Q: 'Counter' object has no attribute 'count' There are two lists and I want to check how many of elements are duplicate. Assuming list one is l1 = ['a', 'b', 'c', 'd', 'e'] and list two is l2 = ['a', 'f', 'c', 'g']. Since a and c are in both lists, therefore, the output should be 2 which means there are two elements that repeated in both lists.  Below is my code and I want to count how many 2 are in counter. I am not sure how to count that.
l1 = ['a', 'b', 'c', 'd', 'e']
l2 = ['a', 'f', 'c', 'g']
from collections import Counter
    c1 = Counter(l1)
    c2 = Counter(l2)
    sum = c1+c2
    z=sum.count(2)

A: What you want is set.intersection (if there are no duplicates in each list):
l1 = ['a', 'b', 'c', 'd', 'e']
l2 = ['a', 'f', 'c', 'g']

print(len(set(l1).intersection(l2)))

Output:
2

A: Every time we use a counter it converts the lists into dict. So it is throwing the error. You can simply change the number of lists and run the following code to get the exact number of duplicate values.
# Duplicate elements in 2 lists
l1 = ['a', 'b', 'c', 'd', 'e']
l2 = ['a', 'f', 'c', 'g']# a,c are duplicate
from collections import Counter

c1 = Counter(l1)
c2 = Counter(l2)
sum = c1+c2
j = sum.values()
print(sum)
print(j)

v = 0
for i in j:
    if i>1:
        v = v+1

print("Duplicate in lists:", v)

Output:
Counter({'a': 2, 'c': 2, 'b': 1, 'd': 1, 'e': 1, 'f': 1, 'g': 1})
dict_values([2, 1, 2, 1, 1, 1, 1])
Duplicate in lists: 2


text:
Q: Three fair dice are rolled thrice: Probability of getting a "double 5" at least once?
Three fair dice are rolled thrice. What is the probability of getting a "double 5" at least once?

I was thinking that it is $$\frac 16 \cdot \frac 16 \cdot \frac 56 \cdot 3$$

A: 1/6 * 1/6 * 5/6 * 3 is the probability that you get double 5's on a given throw.
If you wanted to get doubled 5's EACH of the three times, then you would cube the result.
However, if you want the probability of getting a "double 5" AT LEAST once, you should calculate the probability that it does not happen, and then subtract that number from 1, as Gilles Bonnet said.
Probability of not getting double 5 on a throw = 1- (1/6 * 1/6 * 5/6 * 3)
probability of not getting double 5 on any of the throws p = (1- (1/6 * 1/6 * 5/6 * 3)) ^3
probability of getting a "double 5" at least once= 1-p = 1- (1- (1/6 * 1/6 * 5/6 * 3)) ^3

A: *

*$\frac 16 \cdot \frac 16 \cdot \frac 56 \cdot 3$ is the probability of a "double five" but not a "triple five" on a single roll of three dice.

*Add $\frac 16 \cdot \frac 16 \cdot \frac 16$ if you want to include a "triple five" in the calculation.

*Subtract from $1$ to get the probability not to get a "double five" on a single roll of three dice.

*Put to the power of $3$ to get the probability not to get a "double five" on any of three rolls of three dice.

*Subtract from $1$ to get the probability of getting a "double five"  at least once on three rolls of three dice.


text:
Q: Grails fails to start up, "downloading tomcat-embed..." Symptoms:
Grails was stuck on
| Loading Grails 2.2.4
| Configuring classpath
| Downloading: tomcat-embed-core-7.0.42.jar

... and would not advance.
Environment:
Laptop with Intellij 12.0.1, Windows 7 Home Premium, Grails 2.2.4.

A: I tried:

*

*I turned off windows firewall through control panel - no help I added
'log "verbose"' to BuildConfig.groovy - It didn't help.  It just
added more information before | Downloading:
tomcat-embed-core-7.0.42.jar

*I deleted the IVY cache file under
c:\Users\Me.grails - Getting close.  Delete failed. I found "Java"
tasks in task manager and killed them.  Now I can copy the relevant
jar into place after downloading from the URL in verbose output!
Still no dice on grails startup, though (because of the next
dependency).

*I stopped AVG temporarily - no help.

*I went back to Windows Firewall and found a "... with Advanced Security" link.

*I disabled the "domain profile" security (my earlier actions had disabled "public profile" and "private profile")...  Now grails starts up appropriately.  But firewall is disabled, not the best solution.

From here, the correct solution became obvious.  I had accidentally mis-categorized my home network as "Public" and even after I plugged in an ethernet cable Windows used the wireless security settings.  Simply disabling the wireless network or reclassifying it allowed me to reset windows security settings without disabling grails.


text:
Q: How to apply default policies to cloudformation or terraform in aws? With terraform or cloudformation, we can apply individual permissions while creating a policy.
But how to select default predefined policies like AWSRDSReadyOnlyAccess, like these to the terraform template

A: Using the ManagedPolicyArns property. Here's how you do it using CloudFormation
DmsCloudwatchServiceRole:
    Type: AWS::IAM::Role
    Properties:
        RoleName: dms-cloudwatch-logs-role
        Description: "Role to allow DMS to write to Cloudwatch Logs. Role name must not be changed as DMS requires this exact role name."
        AssumeRolePolicyDocument:
            Version: 2012-10-17
            Statement:
                -
                    Effect: Allow
                    Principal:
                        Service:
                            - dms.amazonaws.com
                    Action:
                        - sts:AssumeRole
        Path: /
        ManagedPolicyArns:
         - arn:aws:iam::aws:policy/service-role/AmazonDMSCloudWatchLogsRole

I'm not 100% sure this is the question you're asking, the question is a little imprecise.


text:
Q: Is a mysql-query logical or not? I'm sorry if the question is already asked somewhere, I can't find it.
I was asking myself a question : is a mysql-query logical or not ?
Let's imagine : if I want to get all the posts of a topic of a forum, with the users'informations, I do :
SELECT p.p_id, p.p_text, p.p_uid, p.p_date,
   u.u_nickname, u.u_email
FROM posts as p
  JOIN users as u ON p.p_uid = u.u_id
WHERE p.p_id = :pid

We can imagine some users posted different times. Does the query try to get the users' informations each time it encounters a u_id or just when it encounters a different u_id it didn't see before ?
In a different way, if the user with u_id = 1 posts ten posts, will the query get his informations ten times or just once ?
I believe this question is already solved somewhere, or even in the doc. But as you can see, english is not my first language, so there are many things I have trouble to understand.
Thank you for your help !


text:
Q: Forms for file upload in nested model in rails I'm aiming to implement a one-to-many -> one-to-many structure like the one described in the rails api here:
class Document < ActiveRecord::Base
  has_many :sections
  has_many :paragraphs, :through => :sections
end

class Section < ActiveRecord::Base
  belongs_to :document
  has_many :paragraphs
end

class Paragraph < ActiveRecord::Base
  belongs_to :section
end

I'm trying to let the paragraphs class have a file upload through carrierwave, as described in the railscast on the topic, within a nested AJAX form that lets me add and remove sections and paragraphs.
Since I will be viewing the pictures only within the full document, I'm trying to keep the code within my Document controller.  So, right now, the controller there is:
  def show
    @document = Document.find_by_username(params[:documentname])
    @section = @document.sections
#   @paragraph = @section.paragraphs #DONT UNDERSTAND WHY UNCOMMENTING THIS DOESNT WORK.
  end

Both my document and section models have the accepts_nested_attributes_for set up.  However, when I load a document view, if I uncomment the @paragraph above, I get an error that suggests section assignment was successful, but paragraph assignment was unsuccessful for lack of a method:
NoMethodError in DocumentController#show
undefined method `paragraph' for #<ActiveRecord::Relation:0x007f9b6409c340>

If I comment it out, it appears to load the section assignment fine.  Currently, my sections and paragraph tables are completely blank because I can't set up the forms, so maybe that is part of the problem.  But I think nil would give me a different error than no method, right?  So, I suspect something is wrong under the hood already.
So, my main bits of confusion here:  How and where do I construct a form controlled by my document controller to accept any data, and then especially to work with the carrierwave file upload?
If you have any other suggestions on how to structure this better, I'd appreciate it.
Also, what would be a good way to go about debugging this?  I seem to be missing a method, which one, where?
I've referenced these, but wasn't able to find a solution:

*

*http://railscasts.com/episodes/196-nested-model-form-revised

*http://railscasts.com/episodes/253-carrierwave-file-uploads

*Carrierwave upload with nested forms?

*Rails 3 + JQuery-File-Upload + Nested Model

*Rails 3 and a Nested jQuery File Upload Model
Update 1
I suspect the problem is coming from my bad show commands?  It can't multi-index the right sections to the right paragraphs?  So,
  def show
    @document = Document.find_by_username(params[:documentname])
    @section = @document.sections
#   @paragraph = @section.paragraphs #DONT UNDERSTAND WHY UNCOMMENTING THIS DOESNT WORK.
  end

should be more like:
  def show
    @document = Document.find_by_username(params[:documentname])
    @section = @document.sections
    @paragraph = @section.find(params[:section_id]).paragraphs
  end

This doesn't work, but something like that?  There's a way it doesn't seem to be linking the sections to the individual paragraphs.  The error I get with the above is:
ActiveRecord::RecordNotFound in DocumentController#show

Couldn't find Section without an ID

Update 2
Maybe that means I should telescope all of the show commands? ie, that getting the right paragraphs for the right section would be covered more like so:
in the document controller:
def show
    @document = Document.find_by_username(params[:documentname])
    @section = @document.sections
end

in the section controller:
def show
    @section = Section.find(params[:id])
    @paragraph = @section.pictures
end

So, if that is the case, how do I set up my nested form?  To jointly create (1) sections, (2) paragraphs, and (3) images in the railcasts-style ajax interface from within document#show page?

A: Have you tried ?
  @section = @document.sections.build
  @paragraph = @sections.paragraphs.build

A: None of the SO answers I searched for worked for me, because the initial key did not exist at the time of upload, so it was impossible to link to it.
So, my solution was just not to try this design.  Make a different form with less nesting.

A: I wrote a huge answer in another post that outlined how I got multiple-file uploading working in Rails with Carrierwave, jQuery File Uploader, and a nested model. Perhaps it'll help?
Rails 3 + JQuery-File-Upload + Nested Model


text:
Q: How to get bitbucket OAUTH token via bash script? I am attempting to get an OAUTH token for bitbucket via a bash script.
At the moment, I'm able to use the following URL:
https://bitbucket.org/site/oauth2/authorize?client_id={key}&response_type=token
I simply visit this via a web browser and hit authenticate, I am then redirected to the callback website, And I can see the token in the URL. For example, if my callback url was stackoverflow.com, My url bar would now contain stackoverflow.com/#access_token=XYZ
What I need to do, is figure out how to hit this url but get this access token in a bash script rather than from a URL.
Relevant doc: https://bitbucket.org/site/oauth2/authorize?client_id=kdBELaEX6HkUexPMRS&response_type=token

A: Using curl (can be used inside your bash script)
curl -X POST https://bitbucket.org/site/oauth2/access_token \
  -d grant_type=client_credentials \
  -u  key:secret


text:
Q: How to run Facebook Infer on Windows I know the official docs mentioned only Mac and Linux options, but I tried on Cygwin with the Android example.
Always get the following error:
C:\Python27\python.exe: can't open file '/cygdrive/c/Users/Tung/infer-linux64-v0.1.0/infer/infer/bin/infer':
Am I missing anything? Has anyone been successful on this? Thanks

A: Unfortunately, Infer currently doesn't support Windows. We recommend trying Infer on Windows using a Linux virtual machine, if your project also compiles on Linux.


text:
Q: .htaccess redirect to another domain except admin page I am asking because I can not for the live of me figure out what is wrong and so far none of the StackOverflow answers worked.
I have to redirect a domain to another subdomain, except the admin. For example:
sub1.domain.com/testsite/ shoud redirect to "sub2.domain.com/testsite/",
but sub1.domain.com/admin/ or "sub1.domain.com/de/admin/" should stay right where it is.
As a first step I tried to only check for the "admin", so everything would be redirected except "sub1.domain.com/admin/":
RewriteCond %{HTTP_HOST} ^sub1\.domain\.com
RewriteCond %{REQUEST_URI} !^\/admin
RewriteRule ^/?(.*)$ http\:\/\/sub2\.domain\.com%{REQUEST_URI} [R=301,L]

This one looked most promising, but it is not working. The second condition is not working and the admin page still gets redirected.
If anyone can help I would appreciate it.

EDIT:
I should have said that its a multi-domain site, which means we have a .htaccess file for all sites and that is the reason I specifically check for the domain.

A: I'm just posting this, but I can't test it!
But I guess this redirects EVERYTHING except that one domain.
RewriteCond %{HTTP_HOST} !^sub1.domain.com/admin/ [NC]
RewriteRule ^/(.*)$http\:\/\/sub2\.domain\.com%{REQUEST_URI} [R=301,L,NC]

I hope it works!

A: So,
I just found the reason (besides my stupidity). The site I should redirect was a Drupal Site. Thats why all links end up at the same location:
sub1.domain.com/index.php
The reason why my above Rewrite Condition was not working is, that sub1.domain.com/admin is being redirected to sub1.domain.com/index.php, which consequently ends up at: "sub2.domain.com/index.php". The correct rewrite rule looks like that:
 RewriteCond %{HTTP_HOST} ^sub1\.domain\.com
 RewriteCond %{REQUEST_URI} !^/(admin|index\.php|de\/admin|it\/admin|user|de\/user|it\/user)
 RewriteRule (.*) http://sub2.domain.com%{REQUEST_URI} [R=301,L]

This redirects everything except:
sub1.domain.com/admin
sub1.domain.com/de/admin
sub1.domain.com/it/admin
sub1.domain.com/user
sub1.domain.com/de/user
sub1.domain.com/it/user

and of course
sub1.domain.com/index.php

Since the last one also should not be redirected if the user types it in directly, it is not a perfect solution, but I can live with it.

A: RewriteCond is use to check condition weather to execute .htacess or not
For your case the solution may be as below:-

Options +FollowSymLinks
RewriteEngine On
RewriteCond %{HTTP_HOST} ^domain\.com [NC]
RewriteRule ^(admin)$ http://sub1.domain.com/$1 [R=301,L]
RewriteRule ^(.*)$ http://sub2.domain.com/$1 [R=301,L]


text: Q: Eclipse Plugin controls display I'm working with plugin creation for eclipse, and its running fine. It looks good in desktop screens but when its viewed in Laptop screens, half of the screen controls are hidden. Pls help me on this, guide me on how to use a particular layout that will adjust controls appearance on different screens.


text:
Q: python / php - cross-language string compression (uses gzcompress/urlencode/json) I have a routine in Python 2.6 that stores large amounts of html text in an AWS DynamoDB database, the problem is that these 'blobs' are sucking up a lot of space and compute unites when doing simple retrievals so I'm looking at ways to compress the strings into something much more lightweight.
I've done some simple tests on the following and it works (greatly reduces DynamoDB compute units) but I'm looking for input on whether or not this is the best way to go about it.
The following is the Python 2.6 code I use to generate a plain text gzip compressed version of the json array. The json array contains a few keys each with a big blob of html.
import urllib, json
str = urllib.quote(json.dumps({'foo1': 'bar'}).encode('zlib').encode('base64'))

Then with php I can run the following to return the string to its natural array:
json_decode(gzuncompress(base64_decode(urldecode($str))),1);

Does anyone have any tips or is this the best way to achieve my goal?

A: Do you really need to have data as plain string in database? You could omit base64 encoding and save data to database as binary to slightly improve speed of your code. Anyway the data is gzipped so you are not able to visualize it directly. http://aws.amazon.com/about-aws/whats-new/2012/08/21/dynamodb-announces-binary-data-types/

A: You could use base64 encoding
Python Code:
import base64
print(base64.b64encode(b"Hello World").decode())

PHP Code:
base64_decode("your base64 encoded text from the python script")


text:
Q: Jquery Delay when value is removed from dropdown Dropdown look when the value is Removed

I have been trying to remove a value from the dropdown when a user clicks on the drop.But there is some delay in that and also when removed it shows a blank area below the last dropdown value.
Here is the code i have used.
jq(document).ready(function()
{
   jq('#gbMainTable').on('click', 'tr.dr td[name="v4"] select', function()
   {
     jq('#gbMainTable tr.dr td[name="v4"] select').find('option[value=Other]').remove();
    });
});

A: Sometimes (often ?), native JS si more simple & efficient :
HTML :
<select id="test">
    <option value="foo">foo</option>
    <option value="bar">bar</option>
    <option value="other">other</option>
    <option value="hey">hey</option>
</select>

JS :
function removeOption(value) {

    document.getElementById('test').addEventListener('click', function() {
        var optionToRemove = document.querySelector('#test option[value="' + value + '"]');
        if (optionToRemove) {
            this.removeChild(optionToRemove);
        }
    });
}

removeOption('other');

https://jsfiddle.net/nejktxso/

A: You can use either of these to remove accordingly
$("#selectBox option[value='other']").remove();

$('#some_select_box').click(function() {
  $('option:selected', this).remove();
});


text:
Q: Проверка пароля при вводе в TextField Подскажите пожалуйста, у меня есть TextField в который я ввожу пароль. После добавления нового символа мне необходимо проверять соответствие пароля некоторым требованиям (например 8 символов). Как можно этого добиться?
Заранее спасибо)

A: Самый простой вариант:
1

2 Задаете тип Connection - Action, Type - UITextField, Event - Editing Changed.

3 Проверяете что необходимо.
К примеру, длина введенного текста 8 и больше символов:
@IBAction func myTfToCheck(_ sender: UITextField) {
    if let text = sender.text {
        let textLength = text.characters.count
        if  textLength > 7 {
            //Do something
            print("\(text), length: \(textLength)")
        }
    }
}

A: Можно использовать готовый валидатор, этот
TextFieldValidator для obj-c, но и под свифт аналогов тьма.
Множество настроек, подсказки юзеру, проверка на совпадение паролей и тд.

A: Вот ссылка, тут есть все что вам надо )
https://stackoverflow.com/questions/25223407/max-length-uitextfield
Чуть не забыл, не забудьте прописать делегат в расширении класса - UITextFieldDelegate
и указать этот делегат своему TextField
yourTextField.delegate = self

Пользуйся.


text:
Q: Signal handling with glade and GTK+ Trying to learn Linux development out of curiosity with little knowledge of C.
I am using glade 3.18.3.
I want to create an application in which the text on label1 will be changed with the input text in entry1 (input box) when button1 will be pressed.
I do not know how to pass the needed arguments to the callback.
This is sample.glade:
<?xml version="1.0" encoding="UTF-8"?>
<!-- Generated with glade 3.18.3 -->
<interface>
  <requires lib="gtk+" version="3.12"/>
  <object class="GtkWindow" id="window_main">
    <property name="can_focus">False</property>
    <property name="title" translatable="yes">Nishant</property>
    <property name="default_width">440</property>
    <property name="default_height">250</property>
    <signal name="destroy" handler="on_window_main_destroy" swapped="no"/>
    <child>
      <object class="GtkBox" id="box1">
        <property name="visible">True</property>
        <property name="can_focus">False</property>
        <property name="orientation">vertical</property>
        <child>
          <object class="GtkMenuBar" id="menubar1">
            <property name="visible">True</property>
            <property name="can_focus">False</property>
            <child>
              <object class="GtkMenuItem" id="menuitem1">
                <property name="visible">True</property>
                <property name="can_focus">False</property>
                <property name="label" translatable="yes">_File</property>
                <property name="use_underline">True</property>
                <child type="submenu">
                  <object class="GtkMenu" id="menu1">
                    <property name="visible">True</property>
                    <property name="can_focus">False</property>
                    <child>
                      <object class="GtkImageMenuItem" id="imagemenuitem1">
                        <property name="label">gtk-new</property>
                        <property name="visible">True</property>
                        <property name="can_focus">False</property>
                        <property name="use_underline">True</property>
                        <property name="use_stock">True</property>
                      </object>
                    </child>
                    <child>
                      <object class="GtkImageMenuItem" id="imagemenuitem2">
                        <property name="label">gtk-open</property>
                        <property name="visible">True</property>
                        <property name="can_focus">False</property>
                        <property name="use_underline">True</property>
                        <property name="use_stock">True</property>
                      </object>
                    </child>
                    <child>
                      <object class="GtkImageMenuItem" id="imagemenuitem3">
                        <property name="label">gtk-save</property>
                        <property name="visible">True</property>
                        <property name="can_focus">False</property>
                        <property name="use_underline">True</property>
                        <property name="use_stock">True</property>
                      </object>
                    </child>
                    <child>
                      <object class="GtkImageMenuItem" id="imagemenuitem4">
                        <property name="label">gtk-save-as</property>
                        <property name="visible">True</property>
                        <property name="can_focus">False</property>
                        <property name="use_underline">True</property>
                        <property name="use_stock">True</property>
                      </object>
                    </child>
                    <child>
                      <object class="GtkSeparatorMenuItem" id="separatormenuitem1">
                        <property name="visible">True</property>
                        <property name="can_focus">False</property>
                      </object>
                    </child>
                    <child>
                      <object class="GtkImageMenuItem" id="imagemenuitem5">
                        <property name="label">gtk-quit</property>
                        <property name="visible">True</property>
                        <property name="can_focus">False</property>
                        <property name="use_underline">True</property>
                        <property name="use_stock">True</property>
                      </object>
                    </child>
                  </object>
                </child>
              </object>
            </child>
            <child>
              <object class="GtkMenuItem" id="menuitem2">
                <property name="visible">True</property>
                <property name="can_focus">False</property>
                <property name="label" translatable="yes">_Edit</property>
                <property name="use_underline">True</property>
                <child type="submenu">
                  <object class="GtkMenu" id="menu2">
                    <property name="visible">True</property>
                    <property name="can_focus">False</property>
                    <child>
                      <object class="GtkImageMenuItem" id="imagemenuitem6">
                        <property name="label">gtk-cut</property>
                        <property name="visible">True</property>
                        <property name="can_focus">False</property>
                        <property name="use_underline">True</property>
                        <property name="use_stock">True</property>
                      </object>
                    </child>
                    <child>
                      <object class="GtkImageMenuItem" id="imagemenuitem7">
                        <property name="label">gtk-copy</property>
                        <property name="visible">True</property>
                        <property name="can_focus">False</property>
                        <property name="use_underline">True</property>
                        <property name="use_stock">True</property>
                      </object>
                    </child>
                    <child>
                      <object class="GtkImageMenuItem" id="imagemenuitem8">
                        <property name="label">gtk-paste</property>
                        <property name="visible">True</property>
                        <property name="can_focus">False</property>
                        <property name="use_underline">True</property>
                        <property name="use_stock">True</property>
                      </object>
                    </child>
                    <child>
                      <object class="GtkImageMenuItem" id="imagemenuitem9">
                        <property name="label">gtk-delete</property>
                        <property name="visible">True</property>
                        <property name="can_focus">False</property>
                        <property name="use_underline">True</property>
                        <property name="use_stock">True</property>
                      </object>
                    </child>
                  </object>
                </child>
              </object>
            </child>
            <child>
              <object class="GtkMenuItem" id="menuitem3">
                <property name="visible">True</property>
                <property name="can_focus">False</property>
                <property name="label" translatable="yes">_View</property>
                <property name="use_underline">True</property>
              </object>
            </child>
            <child>
              <object class="GtkMenuItem" id="menuitem4">
                <property name="visible">True</property>
                <property name="can_focus">False</property>
                <property name="label" translatable="yes">_Help</property>
                <property name="use_underline">True</property>
                <child type="submenu">
                  <object class="GtkMenu" id="menu3">
                    <property name="visible">True</property>
                    <property name="can_focus">False</property>
                    <child>
                      <object class="GtkImageMenuItem" id="imagemenuitem10">
                        <property name="label">gtk-about</property>
                        <property name="visible">True</property>
                        <property name="can_focus">False</property>
                        <property name="use_underline">True</property>
                        <property name="use_stock">True</property>
                      </object>
                    </child>
                  </object>
                </child>
              </object>
            </child>
          </object>
          <packing>
            <property name="expand">False</property>
            <property name="fill">True</property>
            <property name="position">0</property>
          </packing>
        </child>
        <child>
          <object class="GtkLabel" id="label1">
            <property name="visible">True</property>
            <property name="can_focus">False</property>
            <property name="label" translatable="yes">label1</property>
          </object>
          <packing>
            <property name="expand">False</property>
            <property name="fill">True</property>
            <property name="position">1</property>
          </packing>
        </child>
        <child>
          <object class="GtkEntry" id="entry1">
            <property name="name">entry1</property>
            <property name="visible">True</property>
            <property name="can_focus">True</property>
          </object>
          <packing>
            <property name="expand">False</property>
            <property name="fill">True</property>
            <property name="position">2</property>
          </packing>
        </child>
        <child>
          <object class="GtkButton" id="button1">
            <property name="label" translatable="yes">button1</property>
            <property name="name">button1</property>
            <property name="visible">True</property>
            <property name="can_focus">True</property>
            <property name="receives_default">True</property>
            <property name="halign">center</property>
            <signal name="activate" handler="on_button1_activate" swapped="no"/>
            <signal name="clicked" handler="on_button1_clicked" swapped="no"/>
          </object>
          <packing>
            <property name="expand">False</property>
            <property name="fill">True</property>
            <property name="position">3</property>
          </packing>
        </child>
        <child>
          <object class="GtkStatusbar" id="statusbar1">
            <property name="visible">True</property>
            <property name="can_focus">False</property>
            <property name="margin_left">10</property>
            <property name="margin_right">10</property>
            <property name="margin_start">10</property>
            <property name="margin_end">10</property>
            <property name="margin_top">6</property>
            <property name="margin_bottom">6</property>
            <property name="orientation">vertical</property>
            <property name="spacing">2</property>
          </object>
          <packing>
            <property name="expand">False</property>
            <property name="fill">True</property>
            <property name="position">4</property>
          </packing>
        </child>
      </object>
    </child>
  </object>
</interface>

...and this is main.c:
//##gcc -o gladewin main.c -Wall pkg-config --cflags --libs gtk+-3.0 -export-dynamic
#include <gtk/gtk.h>
#include <stdio.h>
//gchar *buffer1;   //added
int main(int argc, char *argv[])
{
    GtkBuilder      *builder;
    GtkWidget       *window;
  // ## gchar BUFF[100];

    gtk_init(&argc, &argv);

    builder = gtk_builder_new();
    gtk_builder_add_from_file (builder, "sample.glade", NULL);

    window = GTK_WIDGET(gtk_builder_get_object(builder, "window_main"));
    gtk_builder_connect_signals(builder, NULL);

    g_object_unref(builder);

    gtk_widget_show(window);
    gtk_main();

    return 0;
}

// called when window is closed
void on_window_main_destroy()
{
    gtk_main_quit();
}

//called when button1 is clicked
void on_button1_clicked()
{
//buffer1 = gtk_entry_get_buffer (entry);
//gtk_entry_buffer_get_text (buffer1);

g_print("Button1 pressed");

//gtk_button_set_label (button1 ,"Hi");
//gtk_label_set_text(GTK_LABEL(entry1),"hi");   // i think this is correct just need tofigure out what to replace insted of entry1
}

A: The signal callbacks receive specific arguments depending on the type of signal caught. The signature of every callback is documented by the official documentation.
In glade, when defining a signal, you can pass an additional widget to the signal callback. The real challenge is that you can pass only one widget, while you need to have access to both of them (the label and the entry).
In plain C you will stuff the two pointers into one struct and use that instead but if you still want to use glade you must find another solution. A way could be to use two callbacks, e.g.:
Glade screenshot
Then your callbacks could be:
void read_from_entry(GtkButton *button, gpointer user_data)
{
    GtkEntry *entry = GTK_ENTRY(user_data);

    g_print("read_from_entry\n");

    g_object_set_data(G_OBJECT(button), "text", (gpointer) gtk_entry_get_text(entry));
}

void write_to_label(GtkButton *button, gpointer user_data)
{
    GtkLabel *label = GTK_LABEL(user_data);

    g_print("write_to_label\n");

    gtk_label_set_text(label, g_object_get_data(G_OBJECT(button), "text"));
}

The g_object_{set,get}_data pair is used just to avoid using a global. The above will work reliably provided that:

*

*the callback order is retained;

*do not write to the entry in or between the two callbacks.

A: Your method for acquiring the GtkEntry's text is weird. You don't need to play with buffers at all; just do
const char *text = gtk_entry_get_text(myEntry);

The buffer returned by text gives you the complete text, but as a read-only string that is freed when the GtkEntry wants it.
For your needs, you can pass it directly to gtk_button_set_label() and gtk_label_set_text():
gtk_button_set_label(button, text);
gtk_label_set_text(label, text);

And in general, the value stays valid throughout the entire signal handler.
If you want to keep the text around for later, you need to copy it with g_strdup() (free with g_free()).
Also gtk_label_set_text() does not work with GtkEntry; you need to use a GtkLabel with it.


text:
Q: Embed Word, PPT, and Excel in a Website I'm trying to embed Word, PPT, and Excel files on a website.
I've tried Google docs and Microsoft Office 365 but I had the following issues with them:

*

*If I'm not signed in using my Gmail account for many days, the embedded document won't show up. Also, sometimes it says that I've reached the maximum number of views for the current document.

*Microsoft office 365's problem is that it adds big top and bottom bars to the documents and they come with colors (red, green, and blue)..which makes the website look very ugly

A: Did you try this? It adds a bar at the bottom but that's required to navigate the slideshow
http://www.microsoft.com/web/solutions/powerpoint-embed.aspx

A: You can install LibreOffice on your server and do the conversions from any doc files to PDF automatically.
An alternative is using VeryPDF.


text:
Q: Material slider wrong drag label show If I use material slider example from here range slider when drag looks like this:

But when I use it i my application, when I drag slider I see only one slider label:

How can I fix it? My code:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:clickable="true"

    android:focusable="true"

    android:focusableInTouchMode="true"
    android:orientation="vertical"
    android:paddingStart="15dp"
    android:paddingEnd="15dp"
    tools:context=".presentation.sub_search.view.SubSearchFragment">

    <com.google.android.material.slider.Slider
        android:id="@+id/prices_slider"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_gravity="center"

        android:layout_marginTop="40dp"
        android:stepSize=".1"
        android:valueFrom="0"

        android:valueTo="100" />
</LinearLayout>

Slider pricesSlider = view.findViewById(R.id.prices_slider);
pricesSlider.setValues(10f, 70f);

UPD:
I have this problem only inside fragments. If I use the same code in activity, I have no problems

A: The problem was in fragment container. After I change container to CoordinatorLayout problem fixed. In other place problem fixed after I replace ViewPager with ViewPager2

A: @cren90 for example in this code
main_activity.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <FrameLayout
        android:id="@+id/fragment_container"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />
</RelativeLayout>

MainActivity.java
public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        getSupportFragmentManager().beginTransaction().add(R.id.fragment_container, new SliderFragment()).commit();
    }
}

slider_fragment.xml
<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="wrap_content">

    <com.google.android.material.slider.Slider
            android:id="@+id/prices_slider"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:stepSize="1"
            android:valueFrom="0"
            android:valueTo="100"
            />
</RelativeLayout>

You need replace FrameLayout with androidx.coordinatorlayout.widget.CoordinatorLayout in main_activity.xml


text:
Q: AB load testing on local ip or domain name? I am using digitalocean as a vps for my webserver.
I added a second droplet with ubuntu 18 that is part of the private network (digitalocean function) with the web server.
I am using cloudflare as my dns provider and also using their ssl certificates.
What is the most accurate load test with ab (**please note the http/https in the example below):
    ab -n 100 -c 1 -k -H "Accept-Encoding: gzip, deflate" https://www.example.com/
    Request per second : 12.66

    ab -n 100 -c 1 -k -H "Accept-Encoding: gzip, deflate" http://www.example.com/
    Request per second : 60.90

    ab -n 100 -c 1 -k -H "Accept-Encoding: gzip, deflate" https://private.network.local.ip/
    Request per second : 36.70

    ab -n 100 -c 1 -k -H "Accept-Encoding: gzip, deflate" http://private.network.local.ip/
    Request per second : 1849

How should I use ab with http or https and with domain or local ip?

A: *

*Well-behaved load test should represent real-life application usage as close as possible, otherwise it doesn't make sense. So you should use the same settings as real users of your application will use, my expectations are:

*

*domain name instead of IP address

*https protocol

*Any reason for comparing response time of your application with the http://example.com which is a live website? You should be comparing DNS hostname of your application with the IP address of your application, in this case the results should be the same

*ab is not the best tool for simulating real users activity, it basically "hammers" a single URL which doesn't represent real user behaviour, real users:

*

*establish SSL session once, further communication is being made over this channel

*send HTTP Headers which may trigger response compression reducing response size

*have HTTP Cache implemented in their browsers so embedded resources like images, scripts, styles, fonts, etc. are being requested only once

*have Cookies which represent user session

assuming all above I would recommend switching to a more advanced load testing tool which is capable of acting like a real browser


text:
Q: Check attribute value by schema XSD I need to check the attribute value "id" of "book" (root) element.
If "id" value ends with three zeros(id="******-000") then the another attribute "book-type" should be "book" otherwise it should be "chapter".
Here is my xml looks like:
<book id="201019894-000" book-type="book" xsi:noNamespaceSchemaLocation="schema.xsd" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<book-meta>
<title-group>...

Is there any possibilities to check the above conditions in Schema(xsd).
Please guide me..
Thanks

A: Can't be done in XSD 1.0.
In XSD 1.1 you can do this with an assertion such as
<xs:assert test="if (ends-with(@id, '-000') then @book-type='book' else @book-type='chapter'"/>


text:
Q: Cannot customize different Y axis in Google bar chart My google chart is made of a bar chart and a scatter chart, and so I use two different Y axis.
I cannot specify different options for each Y axis.
{
    vAxis: {
      /* not taken into account... */
      0: {
        title: 'Y Left Axis',
        format: '#'
      },
      1: {
        title: 'Y Right Axis',
        format: '#'
      }
    },
    seriesType: 'bars',
    series: {
      4: {
        type: 'scatter',
        targetAxisIndex: 1
      },
      5: {
        type: 'scatter',
        targetAxisIndex: 1
      }
    },
    isStacked: true,
    legend: {
      position: 'none'
    }
}

If I set the vAxis like below, it will use the same format and same title for the two axis...
vAxis: {
  format: '#',
  title: 'Same title will be used for the two axis...'
}

A: It is not well documented but from this page, I had to use vAxes and not vAxis.


text:
Q: What is a package stanza? Briefly speaking, how to define a package stanza?
It arrives by running dpkg-gencontrol in a package directory:
# dpkg-gencontrol
dpkg-gencontrol: error: no package stanza found in control info

A: It is a "state" where a package offers rules about how it should behave (install, upgrade, remove) and how it relates (eg: other packages or running services). This rules can be how to install it, how it depends on other packages, general information regarding the actual package and more.
When dpkg-gencontrol issues that type of error, it usually means that the package did not offer, or have any information to control what to do with said package. This information is typically found in what is called a "Control File" inside the package.
For the cases of Debian packages, you can find more information here
and from where the actual error description came from, I believe you can go here.
Note that stanzas (In computer terms I mean) can also mean states in which a service is at a specific moment. An example is found in How to enable or disable services? when a service is stopped or started.


text:
Q: Conservative functor in a category of co-limit preserving functors between $R$ modules and vector spaces Let $R$ be a commutative algebra over some field $k$, and let $RM$ denote the category of $R$ modules.
Let $C =$ Fun$_{co}(RM,$ Vect$)$ be the category of colimit preserving functors, where Vect is the category of $k$ vector spaces.
Define a functor $F: C \to$ Vect by $F(G) = G(R)$, and so if $\eta: G_1 \ \implies G_2$ in $C$, $F(\eta) = \eta_R$.

Show that $F$ is conservative; that is, $F$ reflects isomorphisms.

My attempt:
First we try to write every $R$ module, $M$, as a cofiltered limit of $R$.
Let $I = \{\oplus_jR \cong N \subset M:$ $N$ is a submodule$\}$, that is, free submodules of $M$. We equip maps only if they are inclusion maps.
Since $R$ has a copy in $M$, $I$ isn't empty, and given two free submodules we can find another free submodule contained in both. So $I$ is a cofiltered category.
Thus it seems that $M \cong$ colim$_IId$.
Next, let $\eta: G_1 \implies G_2$ be a map in $C$ s.t $\eta_R$ is an isomorhism. By definition $G_1, G_2$ preserve colimits and so $G_1(M), G_2(M)$ are cofiltered limits in Vect.
Now I feel pretty close to showing that $\eta_M$ is an isomorphism as well, but am not sure how to formally. In a way $G_i(M)$ are made up of $G_i(R)$ in some sense..
Questions:

*

*are my constructions correct?

*how can I use $\eta_R$ being an isomorphism to show $\eta_M$ is as well?

A: Let me start with your second question.  There is a very general fact here which is handy.

Theorem: Let $I,C,$ and $D$ be categories.  Let $X:I\to C$ be a functor and $c_i:X(i)\to A$ be a cocone under $X$.  Suppose $G_1,G_2:C\to D$ are functors which both send this cocone to a colimiting cocone, and suppose $\eta:G_1\to G_2$ is a natural transformation such that $\eta_{X(i)}$ is an isomorphism for each $i\in I$.  Then $\eta_A$ is an isomorphism.

Proof:  Note that the maps $\eta_{X(i)}$ form a natural isomorphism between the functors $G_1\circ X$ and $G_2\circ X$.  They thus induce an isomorphism between the colimits of these functors.  But $\eta_A$ is exactly the induced morphism between the colimits $G_1(A)$ and $G_2(A)$ (since it commutes with the cocone morphisms by naturality of $\eta_A$), so $\eta_A$ is an isomorphism.  (Explicitly, its inverse can be constructed using the maps $\eta_{X(i)}^{-1}$ and the universal property of $G_2(A)$.) $\ \blacksquare$
So, in your situation where $G_1$ and $G_2$ preserve all colimits, this means that if $\eta$ is an isomorphism on every object in some diagram, then $\eta$ is also an isomorphism on the colimit of the diagram.  In particular, if $\eta_R$ is an isomorphism, then $\eta_F$ is an isomorphism on any free module $F$, and so $\eta$ is an isomorphism on any object which is a colimit of some diagram of free modules.
Now let me turn to your first question.  Unfortunately, your work is wrong: most of your assertions are totally unjustified and false in general.  Indeed, most modules are not the filtered colimits of their free submodules.  For instance, if $I\subset R$ is any nonzero proper ideal then the quotient $M=R/I$ will contain no nonzero free submodules at all.
But, there is no reason to restrict yourself to filtered colimits, or to submodules.  Every module is the cokernel of some map between free modules (just consider any presentation of the module).  Explicitly, that means any module $M$ can be written as a pushout of a diagram where two objects are free modules and the third object is $0$ (and thus also free).  So, as discussed above, this implies $\eta_M$ is an isomorphism.
As a final note, I very strongly suspect you have written the definition of the category $C$ incorrectly and you want to consider only the category of $k$-linear colimit preserving functors.  It doesn't make a difference for the proof of this particular statement, though.


text:
Q: Find three power series with the following properties Find three power series:
$\sum _{n=0}^\infty a_nz^n,\sum _{n=0}^\infty b_nz^n,\sum _{n=0}^\infty c_nz^n$ such that the radius of convergence of the sum of the any two of the series is $0$ but the radius of convergence of the sum of all three series is $\infty$

A: Based on a suggestion by suresh, take $a_n = n!$, $b_n = 2n!$, $c_n = -3n!$.


text:
Q: Error running Rmpi when doing parallel computing I'm trying to running parallel computing in R with below lines
library(parallel)
library(snow)
library(snowFT)
library(VGAM)
library(dplyr)
library(Rmpi)

nCores <- detectCores() - 1
cl <- makeCluster(nCores)

Then R returns an error
Error in Rmpi::mpi.comm.spawn(slave = mpitask, slavearg = args, nslaves = count, : Internal MPI error!, error stack: MPI_Comm_spawn(cmd="C:/R/R-40~1.2/bin/x64/Rscript.exe", argv=0x00000223DB137530, maxprocs=11, MPI_INFO_NULL, root=0, MPI_COMM_SELF, intercomm=0x00000223DCFCD998, errors=0x00000223DA9FC9E8) failed Internal MPI error! FAILspawn not supported without process manager
 3. Rmpi::mpi.comm.spawn(slave = mpitask, slavearg = args, nslaves = count, intercomm = intercomm)
 2. makeMPIcluster(spec, ...)
 1. makeCluster(nCores)

I've tried to install MPICH2 on Windows from here, but the final cmd command mpiexec -validate always returns FAIL.
Could you please elaborate on how to solve this issue?

A: The problem is that makeCluster(nCores) is used by more than one package. As such, I use parallel::makeCluster(nCores) to solve the issue.


text:
Q: what does it mean by 'passed by assignment'? As follow is my understanding of types & parameters passing in java and python:
In java, there are primitive types and non-primitive types. Former are not object, latter are objects.
In python, they are all objects.
In java, arguments are passed by value because:
primitive types are copied and then passed, so they are passed by value for sure. non-primitive types are passed by reference but reference(pointer) is also value, so they are also passed by value.
In python, the only difference is that 'primitive types'(for example, numbers) are not copied, but simply taken as objects.
Based on official doc, arguments are passed by assignment. What does it mean by 'passed by assignment'? Is objects in java work the same way as python? What result in the difference (passed by value in java and passed by argument in python)?
And is there any wrong understanding above?

A: tl;dr: You're right that Python's semantics are essentially Java's semantics, without any primitive types.

"Passed by assignment" is actually making a different distinction than the one you're asking about.1 The idea is that argument passing to functions (and other callables) works exactly the same way assignment works.
Consider:
def f(x):
    pass
a = 3
b = a
f(a)

b = a means that the target b, in this case a name in the global namespace, becomes a reference to whatever value a references.
f(a) means that the target x, in this case a name in the local namespace of the frame built to execute f, becomes a reference to whatever value a references.
The semantics are identical. Whenever a value gets assigned to a target (which isn't always a simple name—e.g., think lst[0] = a or spam.eggs = a), it follows the same set of assignment rules—whether it's an assignment statement, a function call, an as clause, or a loop iteration variable, there's just one set of rules.

But overall, your intuitive idea that Python is like Java but with only reference types is accurate: You always "pass a reference by value".
Arguing over whether that counts as "pass by reference" or "pass by value" is pointless. Trying to come up with a new unambiguous name for it that nobody will argue about is even more pointless. Liskov invented the term "call by object" three decades ago, and if that never caught on, anything someone comes up with today isn't likely to do any better.
You understand the actual semantics, and that's what matters.

And yes, this means there is no copying. In Java, only primitive values are copied, and Python doesn't have primitive values, so nothing is copied.

the only difference is that 'primitive types'(for example, numbers) are not copied, but simply taken as objects

It's much better to see this as "the only difference is that there are no 'primitive types' (not even simple numbers)", just as you said at the start.

It's also worth asking why Python has no primitive types—or why Java does.2
Making everything "boxed" can be very slow. Adding 2 + 3 in Python means dereferencing the 2 and 3 objects, getting the native values out of them, adding them together, and wrapping the result up in a new 5 object (or looking it up in a table because you already have an existing 5 object). That's a lot more work than just adding two ints.3
While a good JIT like Hotspot—or like PyPy for Python—can often automatically do those optimizations, sometimes "often" isn't good enough. That's why Java has native types: to let you manually optimize things in those cases.
Python, instead, relies on third-party libraries like Numpy, which let you pay the boxing costs just once for a whole array, instead of once per element. Which keeps the language simpler, but at the cost of needing Numpy.4

1. As far as I know, "passed by assignment" appears a couple times in the FAQs, but is not actually used in the reference docs or glossary. The reference docs already lean toward intuitive over rigorous, but the FAQ, like the tutorial, goes much further in that direction. So, asking what a term in the FAQ means, beyond the intuitive idea it's trying to get across, may not be a meaningful question in the first place.
2. I'm going to ignore the issue of Java's lack of operator overloading here. There's no reason they couldn't include special language rules for a handful of core classes, even if they didn't let you do the same thing with your own classes—e.g., Go does exactly that for things like range, and people rarely complain.
3. … or even than looping over two arrays of 30-bit digits, which is what Python actually does. The cost of working on unlimited-size "bigints" is tiny compared to the cost of boxing, so Python just always pays that extra, barely-noticeable cost. Python 2 did, like Java, have separate fixed and bigint types, but a couple decades of experience showed that it wasn't getting any performance benefits out of the extra complexity.
4. The implementation of Numpy is of course far from simple. But using it is pretty simple, and a lot more people need to use Numpy than need to write Numpy, so that turns out to be a pretty decent tradeoff.

A: Similar to passing reference types by value in C#.
Docs: https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/passing-reference-type-parameters#passing-reference-types-by-value
Code demo:
# mutable object
l = [9, 8, 7]

def createNewList(l1: list):
    # l1+[0] will create a new list object, the reference address of the local variable l1 is changed without affecting the variable l
    l1 = l1+[0]

def changeList(l1: list):
    # Add an element to the end of the list, because l1 and l refer to the same object, so l will also change
    l1.append(0)

print(l)
createNewList(l)
print(l)
changeList(l)
print(l)

# immutable object
num = 9

def changeValue(val: int):
    # int is an immutable type, and changing the val makes the val point to the new object 8,
    # it's not change the num value
    value = 8

print(num)
changeValue(num)
print(num)


text:
Q: Kendo dropdownlist set selected item with angularjs in angularjs with kendo ui dropdownlist, how can i set the selected item?
If i have this control:
<select name="product" kendo-drop-down-list style="width: 200px" k-options="customOptions" ng-model="newProduct.name"></select>

in the angularjs controller:
$scope.newProduct.icon

has the index of the item selected (and it's ok). But how can i set the item?

A: Try setting the property you want in a k-data-text-field and the ng-model to hold the entire object, this way just changing that object should work.
<select name="product" kendo-drop-down-list style="width: 200px" k-options="customOptions" ng-model="newProduct" k-data-text-field="'name'"></select>


text:
Q: Resize elements within a flex container when using Svelte #if blocks I am using Svelte and flexbox to to add and remove elements from a container, while dynamically resizing permanent elements inside the container to always take up the remaining space.
I'd like to have added and removed elements transition in and out with svelte "fly."
Here is the problem: the permanent elements jump to their new sizes right away awkwardly rather than animating smoothly along with the entering/exiting elements.  How do I make the permanent elements animate as they are resizing?
I know this can be done with animate "flip" but that is only allowed within an #each block.  I am hoping to use #if bocks to control elements entering and exiting.
I have a repl with a sample, but I'll also show the code below.
JS
import { fly } from 'svelte/transition'
let add = false;

HTML
<main>
{#if add}
    <div transition:fly="{{ y: -200, duration: 2000 }}" class='box' id='add'>
        Added element
</div>
{/if}

<div class='box' id='permanent'>
    I would like this element resize smoothly when a new elements is added to the parent container.  Can I do this without an each block, though?
</div>

<button on:click={() => add = !add}>
    {add ? 'Remove ' : 'Add '} element
</button>

CSS
main {
    height: 100%;
    display: flex;
    flex-direction: column;
    gap: 10px;
}

.box {
    border: 1px solid black;
    min-height: 50px;
}

#permanent {
    flex: 1;
    display: flex;
    text-align: center;
    flex-direction: column;
    justify-content: center;
}


text:
Q: PHP - max scripts/tasks at same time I wrote a big product importer script that must be started multiple times so it takes advantage of multiple cores.
If I start the script in plesk via scheduled tasks 8 times it is only running five scripts at the same time:
PID USER      PR  NI    VIRT    RES    SHR S  %CPU %MEM     TIME+ COMMAND
    4994 root      20   0 2956004 1.573g  16212 R  74.5  6.6  45:52.21 php
     1636 root      20   0 2976000 1.592g  16224 R  72.8  6.6  77:04.52 php
     4338 root      20   0 2971744 1.588g  16468 R  72.2  6.6  49:11.41 php
     4919 root      20   0 2985488 1.597g  16216 R  69.8  6.7  45:31.94 php
     5907 root      20   0 2958256 1.576g  16484 R  69.8  6.6  45:04.00 php

Where and how is it possible to define the max number of scripts running by a user?
Currently running PHP 7.2.9 on a 12 core machine.
Just saw that the tasks weren't started:
| 2018-08-22 09:26:43 | 181 | scheduler-run-task                       | started     |               0 | ea66c06c1e1c05fa9f1aa39d98dc5bc1 | queue          | NULL           |         100 |             0 | 0000-00-00 00:00:00 |  4330 | NULL       |
| 2018-08-22 09:29:25 | 182 | scheduler-run-task                       | started     |               0 | ea66c06c1e1c05fa9f1aa39d98dc5bc1 | queue          | NULL           |         100 |             0 | 0000-00-00 00:00:00 |  4911 | NULL       |
| 2018-08-22 09:29:46 | 183 | scheduler-run-task                       | started     |               0 | ea66c06c1e1c05fa9f1aa39d98dc5bc1 | queue          | NULL           |         100 |             0 | 0000-00-00 00:00:00 |  4986 | NULL       |
| 2018-08-22 09:32:59 | 185 | scheduler-run-task                       | started     |               0 | ea66c06c1e1c05fa9f1aa39d98dc5bc1 | queue          | NULL           |         100 |             0 | 0000-00-00 00:00:00 | 26735 | NULL       |
| 2018-08-22 09:34:30 | 186 | scheduler-run-task                       | started     |               0 | ea66c06c1e1c05fa9f1aa39d98dc5bc1 | queue          | NULL           |         100 |             0 | 0000-00-00 00:00:00 | 31270 | NULL       |
| 2018-08-22 09:34:43 | 187 | scheduler-run-task                       | not_started |               0 | ea66c06c1e1c05fa9f1aa39d98dc5bc1 | queue          | NULL           |         100 |             0 | 0000-00-00 00:00:00 |     0 | NULL       |
| 2018-08-22 10:21:06 | 188 | scheduler-run-task                       | not_started |               0 | ea66c06c1e1c05fa9f1aa39d98dc5bc1 | queue          | NULL           |         100 |             0 | 0000-00-00 00:00:00 |     0 | NUL

So only the 5 tasks I can see with "top" are running - can I force the start of these other tasks?
Thanks a lot for your suggestions.

A: Try to pass different parameters at the end of file like ./schedule.php 10013
Or
Main scheduler script call to other script using the exec command  like that exec(./scheduleOne.php 11014) to possible the multiple request.


text:
Q: How to run AppleScript for ImageEvent class in sandboxed macOS application? We are developing an application for the Mac App Store using Qt 5.2.0.Framework on Mac OS X 10.9.
Here is a simple AppleScript which convert a .PNG image to .jpeg image.
tell application "Image Events"
    lanuch
    set theImageRef to POSIX file ":private:var:root:Desktop:1.png"
        tell theImageRef
              save in ":private:var:root:Desktop:save.jpeg"
              close
        end tell
end tell

This AppleScript works in a non-sandboxed application. It fails in a sandboxed application.
My question is: How do you use an AppleScript in a sandboxed application? Or is there an alternative to this?

A: There are several alternatives to this:

*

*command line sips (see man sips for scriptable image processing suite)

*Cocoa with NSImage and NSBitmapImageRep (see
How to save a NSImage as a new file)

*Core Foundation with CGImageRef and the like (see Saving CGImageRef to a png file?)

*QT has something similar as well in the QPixmap class(see How to save a QPixmap Object to a file?)

To use AppleScript within a sandboxed Application you want to use Target Access Groups as described here. But you will have problems to find an App that supports Target Access Groups unless you write your own. But then why use AppleScript for image processing?
The bundle-identifier to use in the entitlements is "com.apple.imageevents".


text:
Q: redirect user to a particular page after recieving notification in ngcordova push ionicframework android is there a way with ionic to bring the user to a specific page or tab when opening the app through the notification?
I send the push,my phone is in background and the user accesses the app tapping on the notification just arrived. Actually the app opens the page which is already opened, but I want it opens a destination page chosen by notification.
// ------------------------------ GCM NG-CORDOVA PUSH-----------------------------------
.run(function($ionicPlatform,ngFB,$state,$cordovaPush,$rootScope,$ionicScrollDelegate, $cordovaMedia) {
  $ionicPlatform.ready(function() {
var androidConfig = {
    "senderID": "XXXXXXXXXXX"
  };
 $cordovaPush.register(androidConfig).then(function(result) {
      // Success
      // alert(result);
    }, function(err) {
      // Error
      alert(err);
    });

    $rootScope.$on('$cordovaPush:notificationReceived', function(event, notification) {
      //alert(notification.event);
      switch(notification.event) {
        case 'registered':
          if (notification.regid.length > 0 ) {
          // alert('registration ID = ' + notification.regid);
          }
          break;

        case 'message':

        $ionicScrollDelegate.$getByHandle('chatScroll').scrollBottom();
          // this is the actual push notification. its format depends on the data model from the push server
          //alert('message = ' + notification.message + ' msgCount = ' + notification.msgcnt);
         alert(JSON.stringify(notification));
          if (notification.foreground)
            {
                // if the notification contains a soundname, play it.
               var soundfile = notification.soundname;
              // if the notification contains a soundname, play it.

              var media = $cordovaMedia.newMedia("/assets/www/"+ soundfile);
              media.play();
                alert(notification.payload.message);
            }
            else
            {
                window.location = '#/home';
                //$state.go('home');
            }
          break;

        case 'error':
          alert('GCM error = ' + notification.msg);
          break;

        default:
          alert('An unknown GCM event has occurred');
          break;
      }
    });

    // WARNING: dangerous to unregister (results in loss of tokenID)
   // $cordovaPush.unregister(options).then(function(result) {
      // Success!
    //}, function(err) {
      // Error
    //})

  });

})

Please Help me. Where i am doing wrong?


text:
Q: Is there something like the PHP function nl2br() for ASP.NET MVC? Is there stock standard function that does newline to
 encoding in ASP.Net MVC?

A: All these answers are quite correct, but you should do a mystring.Replace("\r?\n", "
"); to catch UNIX line endings as well, if your source (user input or db) might deliver that.

A: I don't believe there's a 'stock standard function' to do this exactly the same as PHP's nl2br() function however the following will do the equivelant:
myString.Replace("\r\n", "
");

A: mystring.Replace("\r\n","
");

A: There is now:
public static class StockStandardFunctions
{
    public static string Nl2br(this string input)
    {
        return input.Nl2br(true);
    }

    public static string Nl2br(this string input, bool is_xhtml)
    {
        return input.Replace("\r\n", is_xhtml ? "
\r\n" : "
\r\n");
    }
}

Amended to follow the php spec for nl2br a little more closely (thanks Max for pointing that out).  This still assumes \r\n new lines though...

A: What about something along the lines of:
public static string Nl2br(string str)
{
    return Nl2br(str, true);
}

public static string Nl2br(string str, bool isXHTML)
{
    string brTag = "
";
    if (isXHTML) {
        brTag = "
";
    }
    return str.Replace("\r\n", brTag + "\r\n");
}

Here's the function signature from the PHP documention:

string nl2br  (  string $string  [,
  bool $is_xhtml = true  ] )

The PHP function also appends a newline after the break tag.


text:
Q: Piping Cygwin into a Python program As a i'm new to the whole Piping thing and Python I had recently encountered a problem trying to pipe Cygwin's stdin & stdout into a python program usin Python's subprocess moudle.
for example I took a simple program:
cygwin = subprocess.Popen('PathToCygwin',shell=False,stdin=subprocess.PIPE,stdout=subprocess.PIPE)
cygwin.stdin.write('ssh')

After that I'm getting this error:
cygwin.stdin.write('ssh')
IOError: [Errno 22] Invalid argument

What am I doing wrong?

A: Well, your literal code won't work.  You are passing a string with the value 'PathToCygwin' and that isn't going to do anything.  I assume that you are passing a better string than that, but you didn't show us what.
I think your PathToCygwin is probably the problem.  If you don't get the path right, it won't work.
Here is my test code.  I ran this under the Cygwin version of Python, so I used a Cygwin-style path: instead of r"C:\cygwin\bin\bash.exe" I used a /cygdrive/c path:
>>> cpath = "/cygdrive/c/cygwin/bin/bash.exe"
>>> cygwin = subprocess.Popen(cpath,shell=False,stdin=subprocess.PIPE,stdout=su
bprocess.PIPE)
>>> cygwin.stdin.write("ssh")
>>>

Again, I ran this in the Cygwin-compiled version of Python.  If you are using the Windows native version of Python, you will probably need to use a C: path.
If you still are having trouble, would you please tell us exactly which version of Python you are using, and show us the actual path code you are using?


text:
Q: How many arguments takes the foldr function of Haskell? I am new to Haskell and I am reading the book  "Real World Haskell". In the Chapter 4 of the book the author asks as an exercise to rewrite the groupBy function using fold. One of the readers of the book (Octavian Voicu ) gave the following solution:

theCoolGroupBy :: (a -> a -> Bool) -> [a] -> [[a]]
theCoolGroupBy eq xs = tail $ foldr step (\_ -> [[]]) xs $ (\_ -> False)
                       where step x acc = \p -> if p x then rest p else []:rest (eq x)
                                          where rest q = let y:ys = acc q in (x:y):ys

My question is simple: I know that foldr takes 3 arguments: a function, an initial value and a list. But in the second line of the code foldr takes 4 arguments. Why this happens?
Thank you.

A: All functions in Haskell take just one argument. When we have a function with type a -> b -> c, it is just a shorter way to write a -> (b -> c), i.e. a function, which takes one argument and produces a function which takes another argument. See Currying for more information.
In this case, see the @sepp2k's answer. foldr produces a function and it needs another ("the 4th") argument.

A: In this case foldr is used to build up a function. (\_ -> False) is the argument to that function.

A: Scott's answer is correct, the result of the foldr is a function, so this is why it seems that foldr takes 4 arguments. The foldr functions does take 3 arguments (function, base, list):
*Main> :type foldr
foldr :: (a -> b -> b) -> b -> [a] -> b

I'll just give here an example that is less complex:
inc :: Int -> (Int -> Int)
inc v = \x -> x + v

test = inc 2 40  -- output of test is 42

In the above code, inc takes one argument, v, and returns a function that increments its argument by v.
As we can see below, the return type of inc 2 is a function, so its argument can simply be added at the end:
*Main> :type inc
inc :: Int -> Int -> Int
*Main> :type inc 2
inc 2 :: Int -> Int
*Main> :type inc 2 40
inc 2 40 :: Int

Parentheses could be used to emphasize that the return value is a function, but functionally it is identical to the above code:
*Main> (inc 2) 40
42

PS: I'm the author of the original comment :)

A: In this situation, I think it is best to look at the type signature of foldr:
foldr :: (a -> b -> b) -> b -> [a] -> b

and to match that to the expression we have (with added parenthesis for clarity):
(foldr step (\_ -> [[]]) xs) (\_ -> False)

The second argument of foldr is the same type as its result. In this case the second argument is a function. In this case, this means that the foldr expression with 3 arguments will be a function.
What you see to be the 4th argument of the foldr function could also be thought of as the 1st argument of the foldr result!