text:
Q: doctrine select statement always returns all fields of the table I have the following table
Test:
    tableName: test
    columns:
        test_id:
            name: test_id as id
            primary: true
            autoincrement: true
            type: integer
            notnull: true
        test_name:
            name: test_name as name
            type: string(255)
        test_title:
            name: test_title as title
            type: string(255)

and this dql statement
$dql = Doctrine_Query::create()->select('t.name')->from('Model_Test t');

the following sql ist generated
SELECT t.test_id AS t__test_id, t.test_name AS t__test_name FROM test t

but after fetching the result in doctrine, I have access to the title field even it is not selected:
foreach ($results as $result) {
    foreach ($result as $filed => $value) {
        echo "$filed => $value <hr>"; // echoes 'title' => null but title in db has other value
    }
}

also a dump via Zend_Debug::dump($results->toArray()); shows me all fields as if I would have done a select *
So how to limit the returned fields to match my selection?
Thanks in advance
Martin

A: I guess:
because
$results = $dql->execute();

fetches the result as an object, the non selected vars are filled with nulls
whereas
$results = $dql->fetchArray();

fetches an array and in this case only the selected fields appear (besides the primary key)

A: This one works for me, and only fetches the queried fields:
$events = Doctrine_Query::create()
     ->select("e.id, e.Title, e.Lat, e.Lon, e.Startdate, e.Location, e.Url")
     ->from('Event e')
     ->setHydrationMode(Doctrine::HYDRATE_ARRAY)
     ->execute();

The resulting array will only contain the selected fields

A: I am not sure, but I think doctrine selects just id and name, but when You try to access title it sees that title is not fetched from DB. So doctrine refetches that object (only this time using SELECT * or similar query).
If You have some kind of Doctrine query profiler -- you probably could see all additional queries required in foreach loop.
Just a wild quess, by the way...
Oh, you can use $query->execute(Doctrine::HYDRATE_ARRAY) if you want to select only some portion of fields.


text:
Q: PolymerElement Constructor I'm trying to change the standard constructor to add myConstructor.
Based on the code here I coded the following statements:
@CustomTag('main-app')
class MainApp extends PolymerElement {

  factory MainApp.custom() {
    MainApp = new Element.tag('main-app');
    myConstructor();
  }
MainApp.created() : super.created();
void myConstructor() {
    print("myConstructor Started");
  }

Unfortunately the Editor shows some problems:
The Statement MainApp = new Element.tag('main-app') shows the error:
A Value of Type 'Element' cannot be assigned to a variable of type 'Type'.
The Statement myConstructor() shows the Error: "Instance members cannot be accessed from a factory constructor"
anyone has a suggestion how I can solve the errors?
EDIT:
The current code is looking like following:
@CustomTag('main-app')
class MainApp extends PolymerElement {

  @observable int counter = 0;

      factory MainApp.custom() {
    MainApp mainApp = new Element.tag('main-app');
    mainApp.myConstructor();
    return mainApp;
  }

  /// Constructor used to create instance of MainApp.
  MainApp.created() : super.created();

MainApp ma = new MainApp.custom();

  void myConstructor() {
    print("myConstructor Started");
    counter = 1;
  }

The following error is showing up:
Exception: type 'HtmlElement' is not a subtype of type 'MainApp' of 'mainApp'.
  MainApp.MainApp.custom
  MainApp.MainApp.created

EDIT Version 2:
@CustomTag('main-app')
class MainApp extends PolymerElement {

  Controller controller = new Controller();

  @observable int counter = myConstructor();
  @observable int totalGlypto = 0;

  /// Constructor used to create instance of MainApp.
  MainApp.created() : super.created();

    static int myConstructor() {
    print("myConstructor Started");
    return controller.getTotal();
  }

  void setupCheckIn(Event e, var detail, Node target) {
    print("Setup started");
    controller.checkInGlypto();
    counter = controller.getTotal();
  }

  void resetCheckIn(Event e, var detail, Node target) {
    print("reset started");
  }

  void loadCheckIn(Event e, var detail, Node target) {
    print("load started");
    controller.loadData();
    counter = controller.getTotal();
  }

}

the code can be downloaded here

A: You are using the class MainApp like a variable. Change the following line
MainApp = new Element.tag('main-app');

to either
MainApp mainApp = new Element.tag('main-app');

or
var mainApp = new Element.tag('main-app');

A: ok, now I think I found an answer, the key is the following code:
@observable int get counter => myConstructor();

redpajama_set_name: RedPajamaStackExchange


text:
Q: Get Text from React Textfield Select How do I get the current text from a Material UI TextField Select Component? I'm storing the id in the state:
const [MunicipioId, setMunicipioId] = useState(0);
const handleChangeMunicipioSeleccionado = (e) => {
    setMunicipioId(e.target.value);
    setBarrioId(0);
    traerBarriosPorMunicipio(e.target.value);
}

And the component is the following:
                <Grid item xs={12} md={6} lg={6} xl={6}>
                <TextField
                variant = "outlined"
                onChange={handleChangeMunicipioSeleccionado}
                value={MunicipioId}
                label="Municipio"
                fullWidth
                select
                >
                {municipios.length > 0 ? municipios.map((municipio)=>(
                    <MenuItem key={municipio.MunicipioId} value={municipio.MunicipioId}>{municipio.MunicipioNombre}</MenuItem>
                )): <MenuItem disabled>No se encontraron municipios</MenuItem>}
                </TextField>
            </Grid>

I need to get the text from it, in this case {municipio.MunicipioNombre} from each item selected.

A: You can get the by giving the value attribute the data value in your case
value={municipio.MunicipioId}

here is a codepen link in which I formatted your code. I used data from the material UI official site
https://codesandbox.io/s/boring-driscoll-3rlhs?file=/src/App.js:0-1057


text:
Q: send C-< and M-! in emacs within tmux I can send C-< in emacs in xterm, but do not work within tmux.
M-! do not work in both situations.
C-< is used in outline-promote
M-! is used in shell-command
ps: I know Esc can do the shell-command function.


text:
Q: Check if key exists in multiple maps in one condition I need to check if the same key exists in two maps:
if v1, ok1 := map1["aaa"]; ok1 {
 ...
}
if v2, ok2 := map2["aaa"]; ok2 {
 ...
}

Is it possible to join these two conditions into one? I managed to do something like this:
v1, ok1 := map1["aaa"]
v2, ok2 := map2["aaa"]
if ok1 && ok2 {
 ...
}

but I'm curious whether it (assigning and checking) can be done in one if condition.

A: No, it can't be done. Spec: Index expressions:

An index expression on a map a of type map[K]V used in an assignment or initialization of the special form
v, ok = a[x]
v, ok := a[x]
var v, ok = a[x]

yields an additional untyped boolean value. The value of ok is true if the key x is present in the map, and false otherwise.

So you can use the special v, ok := m[k] form only if nothing else gets assigned.
However, if you don't use the zero value of the value type of the map, you can do the check using a simple tuple-assignment; by not using the special form but 2 simple index expressions.
For example if your value type is some interface type (e.g. interface{}), and you know you don't use the nil value, you may do the following:
if v1, v2 := m1["aaa"], m2["aaa"]; v1 != nil && v2 != nil {
    fmt.Printf("Both map contains key '%s': %v, %v\n", "aaa", v1, v2)
}

Of course with a helper function, you can do it in one step:
func idx(m1, m2 map[string]interface{}, k string) (
    v1, v2 interface{}, ok1, ok2 bool) {

    v1, ok1 = m1[k]
    v2, ok2 = m2[k]
    return
}

Using it:
if v1, v2, ok1, ok2 := idx(m1, m2, "aaa"); ok1 && ok2 {
    fmt.Printf("Both map contains key '%s': %v, %v\n", "aaa", v1, v2)
}

Try the examples on the Go Playground.

A: you could also use variadic parameter(three dots) to check multiple keys :
// check map 1 and map2 is null or not
func checkMap(m1, m2 map[string]interface{}, keys ...string) []bool {
    var isExist []bool

    for key := range keys {
        //checking value from map 1
        _, ok := m1[keys[key]]
        if ok {
            isExist = append(isExist, true) // append for the first time to avoid panic
        } else {
            isExist = append(isExist, false) // append for the first time to avoid panic
        }

        // checking value from map2
        _, ok = m2[keys[key]]
        if ok {
            isExist[key] = true
        } else {
            isExist[key] = false
        }
    }

    return isExist
}

And then you can check your keys in order like this :
result := checkMap(myMap, myMap2, "a", "b", "c", "d", "e", "f", "g")
fmt.Printf("result = %+v\n", result) // print the result

if result[0] {
    fmt.Println("key a exist in both map")
}

if result[1] {
    fmt.Println("key b exist in both map")
}


text:
Q: main.py: cannot connect to X server Estoy intentando ejecutar una aplicación en Python desde la consola integrada de ubuntu 18.04 que trae Windows 10, ya instale todas las librerías necesarias de pyqt4 pero el error continua
OS: Ubuntu 18.04.5 LTS on Windows 10 x86_64
¿Kernel: 4.4.0-18362-Microsoft
¿Uptime: 3 hours, 7 mins
Packages: 885
Shell: bash 4.4.20
Terminal: /dev/tty1
CPU: Intel i7-9750H (12) @ 2.592GHz
Memory: 15064MiB / 16303MiB

Código:
import sys

from PyQt4.QtGui import QApplication
from CfrmBackupsConfig import CfrmBackupsConfig

def main():
    app = QApplication(sys.argv)

    form = CfrmBackupsConfig()
    form.show()

    app.exec_()

if __name__ == '__main__':
    main()

A: cannot connect to X server, la consola de Ubuntu 18.04 en Windows 10 no te da el servidor gráfico necesario para poder correr pyqt4, es por ello que instale un servidor sobre mi Windows: https://sourceforge.net/projects/xming/ y con ello el problema quedo resuelto


text:
Q: Android - Crop image in both rectangle positions I'm starting an intent for selecting and finally cropping an image by user.
Currently the intent selecting a single rectangle, but I need the square rotated by 90 degrees too. So after cropping I need two images with 200x500 and 500x200 or one image with 500x500.
My current intent:
Intent intent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
intent.putExtra("crop", "true");
intent.putExtra("scale", false);
intent.putExtra("outputX", 200);
intent.putExtra("outputY", 500);
intent.putExtra("aspectX", 200);
intent.putExtra("aspectY", 500);
intent.putExtra("noFaceDetection", true);
intent.putExtra(MediaStore.EXTRA_OUTPUT, SAVE_PATH);

For sample selecting a wallpaper from gallery on an Android device. There are two rectangels that will overlapped.

*

*Image that I have!

*Image for what I want!

Sorry for my bad english ;-)


text:
Q: Group array of objects by key where key is an array Can we achieve a group by on an array of objects by object's key where key is also an array?
[
    {
        "name": "Apple",
        "tags": ["fruits"]
    },
    {
        "name": "Orange",
        "tags": ["fruits"]
    },
    {
        "name": "Tomato",
        "tags": ["fruits", "vegetables"]
    }
]

Wanted results in an object after the group by:
{
    "fruits": [
        {
            "name": "Apple",
            "tags": ["fruits"]
        },
        {
            "name": "Orange",
            "tags": ["fruits"]
        },
        {
            "name": "Tomato",
            "tags": ["fruits", "vegetables"]
        }
    ],
    "vegetables": [
        {
            "name": "Tomato",
            "tags": ["fruits", "vegetables"]
        }
    ]
}

Vanilla or Lodash solution is very welcome!
Edit
Thanks everyone, here is what I ended up using:
const groupBy = key => array =>
    array.reduce((obj, el) => {
        el[key].forEach(k => {
            obj[k] = obj[k] || []
            obj[k].push({ ...el })
        })
        return obj
    }, {})

const groupBySomething = groupBy(`something`)
const grouped = groupBySomething(data)

A: Here:

let arr = [
    {
        "name": "Apple",
        "tags": ["fruits"]
    },
    {
        "name": "Orange",
        "tags": ["fruits"]
    },
    {
        "name": "Tomato",
        "tags": ["fruits", "vegetables"]
    }
];

let response = {};
for(let i of arr){
  for(let j of i.tags){
     let tags =[...i.tags]
     if(response[j]){
        response[j].push({...i , tags: tags})
     } else{
        response[j] = [{...i, tags: tags}];
     }
  }
}

console.log(response)

A: This uses Array.prototype.reduce and Array.prototype.forEach

{
  const data = [
    {
        "name": "Apple",
        "tags": ["fruits"]
    },
    {
        "name": "Orange",
        "tags": ["fruits"]
    },
    {
        "name": "Tomato",
        "tags": ["fruits", "vegetables"]
    }
  ]

  const groupedData = data.reduce((carry, element) => {
    element.tags.forEach(tag => {
      carry[tag] = carry[tag] || []
      carry[tag].push({...element})
    })
    return carry;
  }, {})

  console.log(groupedData)
}

A: A slightly more terse version of @yunzen version.
input data:
const data = [
    {
        "name": "Apple",
        "tags": ["fruits"]
    },
    {
        "name": "Orange",
        "tags": ["fruits"]
    },
    {
        "name": "Tomato",
        "tags": ["fruits", "vegetables"]
    }
];

const convertData = data.reduce((target, currentElem) => {
        currentElem.tags.forEach(tag => {
            target[tag] ? target[tag].push({...currentElem}) : target[tag] = [{...currentElem}];
        });
        return target;
}, {});

console.log(convertData);


text:
Q: Problem with checking if process is running or not I am required to create processes that fork into child processes that would execute commands using execv(). Parent process will end immediately leaving the child process to run the new image. I have stored the child process id and when a command is called, I will check if that process is running or not. Here's the code.
for(size_t i = 0; i < currProcess; i++) {
        if (kill(processArr.pid, 0) != 0 && errno == ESRCH) {
            processArr[i].run = false;
        } else {
            processArr[i].run = true;
        }
    }

However, it seems like the processes do not end and are running forever. Do execv() image not end the process upon completion? Is there something wrong with the code?

A: You have said that you are checking if the child process is running, but you do not elaborate if and when it should end.
it would be nice to get more information or to look at the code that the executed process is running, and the processArr struct.
a few things you can do if you are confident that process should end is to try and remove the and errno check in the if statement and see if it changes the result.
this might be due to how you are trying to check errno, here is an explanation from the errno man page:
   A common mistake is to do

       if (somecall() == -1) {
           printf("somecall() failed\n");
           if (errno == ...) { ... }
       }

   where errno no longer needs to have the value it had upon return from
   somecall() (i.e., it may have been changed by the printf(3)).  If the
   value of errno should be preserved across a library call, it must be
   saved:

       if (somecall() == -1) {
           int errsv = errno;
           printf("somecall() failed\n");
           if (errsv == ...) { ... }
       }

hopefully it will help, and if not I would appreciate additional information.


text:
Q: passing URI as a runtime variable to distributed cache in mapreduce hadoop I am using distributed cache in my mapreduce program and I am passing three variables to this mapreduce program input file, output dir and config file.
I want to add the third argument i.e config file to the Distributed Cache.
I am setting the parameter as follows in run() method of the MapReduce Driver:-
conf.set("CONF_XML", args[2]);

How to add this file into distributed cache in the same method. how do I do that ?
Usually we add using URI(new (file path));
DistributedCache.addCacheFile(new URI(file_path), conf); << here how to pass the argument parameter?

A: Pass the file path argument to the DistributedCache API as URI
DistributedCache.addCacheFile(new Path(args[2]).toUri(),job.getConfiguration());


text:
Q: Cannot resolve type Mono.Runtime and Cannot resolve type System.CoreLib requested by System.Data.SQLite When I set provider for SQLite:
public class Configuration : DbConfiguration, IDbConnectionFactory
{
    public SqlTypeEnum sqlTypeEnum = SqlTypeEnum.Sql;

    public Configuration()
    {
        SetDefaultConnectionFactory(this);
    }

    public Configuration(SqlTypeEnum sqlTypeEnum)
    {
        this.sqlTypeEnum = sqlTypeEnum;
        SetProviderFactory("System.Data.SQLite", SQLiteFactory.Instance);
        SetProviderFactory("System.Data.SQLite.EF6", SQLiteProviderFactory.Instance);

        var providerServices = (DbProviderServices)SQLiteProviderFactory.Instance.GetService(typeof(DbProviderServices));

        SetProviderServices("System.Data.SQLite", providerServices);
        SetProviderServices("System.Data.SQLite.EF6", providerServices);
        SetDefaultConnectionFactory(this);
    }

    public DbConnection CreateConnection(string connectionString)
    {
        if(sqlTypeEnum == SqlTypeEnum.Sql)
            return new SqlConnection(connectionString);
        else
            return new SQLiteConnection(connectionString);
    }
}

This information appears on the console:

Cannot resolve type Mono.Runtime requested by System.Data.SQLite, Version=1.0.113.0, Culture=neutral, PublicKeyToken=db937bc2d44ff139

Cannot resolve type System.CoreLib requested by System.Data.SQLite, Version=1.0.113.0, Culture=neutral, PublicKeyToken=db937bc2d44ff139

after SetProviderFactory("System.Data.SQLite", SQLiteFactory.Instance);
Still, everything seems to be working fine, but I would want to repair that.

*

*.NET v4.5.2

*Entity Framework v6.4.4

Edit:
At last in my application I load the libraries of other projects, but I did a test directly for the project with the provider and it crashed an error indicating this problem: Unable to load DLL 'SQLite.Interop.dll'
However, none of these solutions can solve the problem. It seems to me that the reason may be that libraries are loaded (Assembly) and I do not have any projects attached.

A: I could not do that the information did not appear. This is a bug of the library that misinterprets targetframework. I have set:
<TargetFrameworks>netcoreapp2.2;netcoreapp3.0;net461</TargetFrameworks>

But run app on net461. Mono.Runtime and System.CoreLib do not apply to my framework.


text:
Q: Index notation: associative property I have given the following term, that I can write in index notation as following:
$$ (\mathbf{a} \cdot \nabla)\mathbf{b} = a_j \partial_j b_i$$
Now I can exchange the order and get
$$ \partial_j b_i a_j = (\partial_j b_i) a_j $$
which equals to
$$ (\partial_j b_i) a_j = (\nabla \mathbf{b})\cdot\mathbf{a}$$
Is this enough to show that
$$ (\mathbf{a} \cdot \nabla)\mathbf{b} = (\nabla \mathbf{b})\cdot\mathbf{a}$$?

A: In 7. f) of your source there is a remark noting that $B\cdot a \neq a\cdot B$, when $B$ is a 2-tensor.
This is because $a\cdot B$ is the contraction of $a$ with the first index of $B$, while $B\cdot a$ is to be interpreted as contraction of $a$ with the second index of $B$.
Hence in the present case we have
$$(\nabla b \cdot a)_i = (\nabla b)_{ij}a_j = \partial_ib_ja_j$$
c.f. with your equation $(\nabla b\cdot a)_i=\partial_jb_ia_j$, which should actually be $(a\cdot\nabla b)_i=a_j\partial_jb_i=\partial_jb_ia_j$.
Thus, the identity you actually derived is
$$(a\cdot \nabla)b = a\cdot (\nabla b)$$


text:
Q: Uploaded gz file in Google Cloud is damaged I need help in uploading the gzip file into gcs. I am using nest js and @google-cloud/storage package.

  @Post('/uploadFile')
  async uploadFile(@Req() req: Request, @Res() res: Response) {
    req.setEncoding('utf-8');
    req.on('data', (chunk) => {
      const storage = new Storage({ keyFilename: 'datastore.json' });
      const bucket = storage.bucket('bucket_name');
      let mimeType = req.headers.filetype;
      let file = req.headers.filename;
      const blob = bucket.file(file + '');
      let strOut = "";
      for (var i = 0; i < chunk.length; i++) {
          strOut += chunk[i].charCodeAt(0).toString(2);
      }
      blob.save(strOut, {
        metadata: {
          contentType: mimeType,
          contentEncoding: 'gzip'
        },
        resumable: false,
        gzip:true
      });
   });

I am facing an issue while downloading the data file got downloaded but shows damaged/corrupted may be i am uploading the .gz file wrong. I am streaming the .gz file like this

   fs.createReadStream("compressedData/" + names[i]).pipe(
        request.post(
          {
            headers: config.headers,
            url: "http://localhost:3000/uploadFile",
          },
          (err, res) => {
            if (err) throw err;
            console.log(res.body, config);
          }
        )
      );

here is my config from client side

   config = {
          headers: {
            filetype: "application/gzip",
            filename: "sitemap/test-upload/" + names[i],
            token: "sadjfbkjbkjvkjvkvkcvkjxsdnkn",
          },
        };


text:
Q: if i use querystring on a page navigateurl redirecting in a samepage I am trying to click on a link  in products.aspx and redirect to another page categories.aspx. When i use {*id} in routing to handle querystring on products.aspx link is not working well. Sending same products.aspx page.
My Routes:
   routes.MapPageRoute("productsgroup", "products/{groupname}/{*id}", "~/products.aspx");
   routes.MapPageRoute("productscat", "products/brand/{bname}", "~/categories.aspx");

Hyperlink in products.aspx page:
<asp:Hyperlink ID="hyper_link" runat="server" NavigateUrl='<% GetRouteUrl("productscat", new {bname=Eval("brand-name").ToString()})%>' Text="Category1"></asp:Hyperlink>

Hyperlink is in a asp:Repeater and Eval() is working fine on a link and link is seems normal, when i click on the hyperlink, url changes but not sending categories.aspx page.
If i delete querystring {*id} and not use than hyperlink works fine.
I am trying to understand why it's happening and what we can do about it.

A: There is a simple solution. Change route order and your target url and link will work.
routes.MapPageRoute("productscat", "products/brand/{bname}", "~/categories.aspx");
routes.MapPageRoute("productsgroup", "products/{groupname}/{*id}", "~/products.aspx");

Routing thinks target url is "productsgroup" because it knows the url and target url starts like that. Routing waits for the variable and second route like it doesn't exist for routing.
I hope it helps. Cheers.


text:
Q: Scaling a column into another column with normalized discrete values I've read the previous posts and understand that my question is answered in different ways but I need to verify if I am on the right track please.
I have a column in my data that ranges form 0.00012 to 1452. My goal is to rescale or normalize this column into a factor column ranging from 1 to 20 that are all discrete numbers then round to whole numbers.
I have read this post Scale a series between two points and also this
R- Normalizing certain columns from 0 to 1 with values equal to 0 that help but I can't get my final result.
A sample of the data is as follows:
df_sample <- data.frame(performance_time= c(0.00012,0.12,3.45,12.65,5.8,145,782.45,1452,92.78,101.32))
Output of interest should be a rescaled column of C ranging from 1 to 20 and all discreet values.
It would be great if I can perform it using dplyr.
Thank you for your help in advance.


text:
Q: Fail to implement PUT request with Flask-RESTful I'm trying to implement a REST API with Flask-RESTful. My API contains 4 requests: GET, POST, PUT, DELETE. Everything works perfectly except for the PUT request. It keeps returning Status Code 404, which the requested URL is not found. I'm using Postman to test my API. Here is my code. Can any show me where did I do it wrong? Thank you!
# Small API project using Flask-RESTful
from flask import Flask, request
from flask_restful import Resource, Api, reqparse
from flask_jwt import JWT, jwt_required

app = Flask(__name__)
# Encrypted key
app.secret_key = "Nam Dao"
api = Api(app)

students = []

class Student(Resource):
    parser = reqparse.RequestParser()
    parser.add_argument("major", type=str, required=True, help="This field cannot be left blank")

    def get(self, name):
        # filter function will return a filter object
        # next function will get the "next" student in the filter object.
        # if the Next function does not return anything => return None.
        for student in students:
            if student["name"] == name:
                return student, 200
        return {"message": "student not found"}, 404

    def post(self, name):
        if next(filter(lambda x: x["name"] == name, students), None) is not None:
            return {"message": f"A student with the name {name} already exists"}, 400

        request_data = self.parser.parse_args()

        print(request_data)
        student = {"name": name, "major": request_data["major"]}
        students.append(student)
        return student, 201

    def delete(self, name):
        for student in students:
            if student["name"] == name:
                students.remove(student)
                return {"message": "Item deleted"}, 200
        return {"message": "No student found"}, 204

    def put(self, name):
        data = request.get_json()
        for student in students:
            if student["name"] == name:
                student["major"] = data["major"]
                return {"message": "Student Major Changed"}, 200
        student = {"name": data["name"], "major": data["major"]}
        students.append(student)
        return {"message": "Student Added"}, 200

api.add_resource(Student, "/student/<string:name>")

class StudentsList(Resource):
    def get(self):
        return {"students": students}, 200

api.add_resource(StudentsList, "/students")

if __name__ == '__main__':
    app.run(debug=True)

A: I recheck my URL again and I was missing a letter, that's why it returns 404 Status Code. It was a very silly mistake. Everything works just fine


text:
Q: MATLAB mex c + Fortran Error I'm trying to mex a project made up of files written in c and fortran.
In order to make it easy I created this simple funcions:
mysum.f
  SUBROUTINE mysum(a,b)
  REAL :: a,b,r

  r = a+b
  WRITE(*,*) r
  END SUBROUTINE mysum

and test.c
#include <mex.h>
#include <stdio.h>

extern void mysum(double *a, double *b);
double a,b;

void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[]){

a   =(double) mxGetScalar(prhs[0]);
b   =(double) mxGetScalar(prhs[1]);

mysum(&a,&b);

return;
}

With Intel Fortran Compiler (x64) I run:

ifort /c mysum.f

and it creates mysum.obj
In Matlab (x64) I'm using Microsoft SDK as compiler and I write:

mex -O -largeArrayDims LINKFLAGS="$LINKFLAGS /NODEFAULTLIB:MSVCRT.lib"
  test.c mysum.obj

Unfortunatelly it gives this error:

test.obj : error LNK2019: unresolved external symbol mysum referenced in function mexFunction
  test.mexw64 : fatal error LNK1120: 1 unresolved externals

At this point I'm stuck and I don't know what to do.
I'm using the option /NODEFAULTLIB because there was a conflict otherwise with MSVCRT.lib.
I need some help please.

A: Or in the Fortran you can use the ISO C Binding and specify the names by which Fortran procedures will be seen by other languages and the linker, specifying case and not needing underscores.   You can also declare variables so that compatibility with C is guaranteed.  In your example, Fortran default real and C double probably don't match.   See https://stackoverflow.com/questions/tagged/fortran-iso-c-binding or the gfortran manual (its part of the language standard and so the documentation there is  more generally applicable).   For this example:
SUBROUTINE mysum(a,b) bind ( C, name = "mysum" )
use iso_c_binding
implicit none
REAL (c_double) :: a,b,r

r = a+b
WRITE(*,*) r
END SUBROUTINE mysum

A: You probably need to append an underscore to mysum in the C code:
extern void mysum_(double *a, double *b);

void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[]){
//...
  mysum_(&a,&b);
//...
}

Run nm mysum.obj to get the correct names for all subroutines.


text:
Q: Import Tally Data into Openerp I am working on module for which i am using tally_integrator module of openerp. after successfull installation when i am trying to import tally data i am getting following error
Client Traceback (most recent call last):
  File "/usr/lib/pymodules/python2.7/openerp/addons/web/common/http.py", line 180, in dispatch
    response["result"] = method(controller, self, **self.params)
  File "/usr/lib/pymodules/python2.7/openerp/addons/web/controllers/main.py", line 1052, in call_button
    action = self.call_common(req, model, method, args, domain_id, context_id)
  File "/usr/lib/pymodules/python2.7/openerp/addons/web/controllers/main.py", line 996, in call_common
    return self._call_kw(req, model, method, args, {})
  File "/usr/lib/pymodules/python2.7/openerp/addons/web/controllers/main.py", line 1010, in _call_kw
    return getattr(req.session.model(model), method)(*args, **kwargs)
  File "/usr/lib/pymodules/python2.7/openerp/addons/web/common/openerplib/main.py", line 250, in proxy
    args, kw)
  File "/usr/lib/pymodules/python2.7/openerp/addons/web/common/openerplib/main.py", line 117, in proxy
    result = self.connector.send(self.service_name, method, *args)
  File "/usr/lib/pymodules/python2.7/openerp/addons/web/common/http.py", line 608, in send
    raise xmlrpclib.Fault(openerp.tools.exception_to_unicode(e), formatted_info)

Server Traceback (most recent call last):
  File "/usr/lib/pymodules/python2.7/openerp/addons/web/common/http.py", line 593, in send
    return openerp.netsvc.dispatch_rpc(service_name, method, args)
  File "/usr/lib/pymodules/python2.7/openerp/netsvc.py", line 360, in dispatch_rpc
    result = ExportService.getService(service_name).dispatch(method, params)
  File "/usr/lib/pymodules/python2.7/openerp/service/web_services.py", line 586, in dispatch
    res = fn(db, uid, *params)
  File "/usr/lib/pymodules/python2.7/openerp/osv/osv.py", line 186, in execute_kw
    return self.execute(db, uid, obj, method, *args, **kw or {})
  File "/usr/lib/pymodules/python2.7/openerp/osv/osv.py", line 129, in wrapper
    return f(self, dbname, *args, **kwargs)
  File "/usr/lib/pymodules/python2.7/openerp/osv/osv.py", line 195, in execute
    res = self.execute_cr(cr, uid, obj, method, *args, **kw)
  File "/usr/lib/pymodules/python2.7/openerp/osv/osv.py", line 183, in execute_cr
    return getattr(object, method)(cr, uid, *args, **kw)
  File "/usr/lib/pymodules/python2.7/openerp/addons/tally_integrator/wizard/tally_connection.py", line 142, in tally_main
    _processData(s)
  File "/usr/lib/pymodules/python2.7/openerp/addons/tally_integrator/wizard/tally_connection.py", line 124, in _processData
    f = self.createTempFile(s)
  File "/usr/lib/pymodules/python2.7/openerp/addons/tally_integrator/wizard/tally_connection.py", line 106, in createTempFile
    f = open('temp.xml','w')
IOError: [Errno 13] Permission denied: 'temp.xml'

Please let me know what is that error i have changed the permission of following directory
/usr/lib/pymodules/python2.7/openerp
but i am still getting this error. Please help me resolve this problem.

A: assuming you have done the openerp installation by the book,  for any kind of permission denied errors on in the form of:
OSError: [Errno 13] Permission denied: '/usr/lib/pymodules/python2.7/openerp/addons/etl'

The general solution according to me is:
cd /usr/lib/pymodules/python2.7
chown -R openerp: openerp

The chown command is designed to change the ownership of the openerp folder under /usr/lib/pymodules/python2.7 to the user openerp.  That is the user under which your openerp-server process should be running.
I have been working on openerp for about 2 days now.  I am not an expert yet.

A: At the risk of stating the obvious, you don't have write permissions for that location.  As there is no path, I presume it will be opened in your current working directory.  Do a ps -ef to get your PID and then run ls -ld /proc/PID/cwd - this will show you the current working directory of the process and then check the write bits and user/group on the directory.


text:
Q: how to print logs in cmd console while execute android instrument test I open a cmd on windows system, and then input "adb shell am instrument -w com.demo.uia.test/android.support.test.runner.AndroidJUnitRunner" to run android test.
I want to print log in the cmd while run the test, can anyone tell me how to write code to print log? I have tied system.out.println("xx") and Log.i("xx","xx"), but it's useless.
I want to show the log in cmd line, not in logcat.
I solved the problem now, use sendStatus api.

A: I guess @MoMo did something like this to have logging output in command prompt window:
In your test class define a function:
private void out(String str) {
    Bundle b = new Bundle();
    b.putString(Instrumentation.REPORT_KEY_STREAMRESULT, "\n" + str);
    InstrumentationRegistry.getInstrumentation().sendStatus(0, b);
}

Then simply use it in @Test functions like:
out("Some message...");

The output appears when running the test in Command Prompt window with adb shell am instrument..., but it is not shown in Run window of Android Studio. It somehow filters the output of test runs, and I cannot find a setting to modify this filter.


text:
Q: Is a "clickable" element in Selenium also imply that it is "visible and present"? In the Selenium framework,  does ExpectedConditions.elementIsClickable  imply that the element is also  "visible, enabled, and present".  The ExpectedConditions.presenceOfElementLocatedBy  appears to be just a simple findElement call on its own.
By looking at the source code, here is what I gleamed so far about ExpectedConditions behaviors, from the methods :
1.  findElement() = can throw NoSuchElementException, or WebDriverException
2.  elementToBeClickable() = is visible, !null, and enabled, catches
      a StaleElementReferenceException
3.  visbilityOf()  =   displayed, catches no exception
4.  presenceOfElementLocated()  =   simple findElement call,  catches findElement()
      exceptions
5.  stalenessOf() =  true if findElement succeeds, can catch StaleElementReferenceException,
      or findElement() exceptions
6.  visibilityOfElementLocated() = same as stalenessOf, can catch
      StaleElementReferenceException or the findElement() exceptions

A: Yes, a clickable element requires element to be visible. Click() will fail and throw a  ElementNotVisibleException if the element is hidden.
Example: for the below hidden span, Click() will throw  a ElementNotVisibleException with message Element is not currently visible and so may not be interacted with.
var driver = new FirefoxDriver();
driver.Navigate().GoToUrl("data:text/html,Hello");
driver.FindElement(By.Id("hello")).Click();

A: Clickable means that element is Visible and Enabled. Another words element is Displayed and Enabled.
You can always check ExpectedConditions implementation in case any doubt.


text:
Q: What exactly is connection enlistment in C# As a follow up to Multiple connections to the same DB in the same TransactionScope, I'm trying to find what is meant exactly by the following in this guide here:

Connections are drawn from the pool and assigned based on transaction
context. Unless Enlist=false is specified in the connection string,
the connection pool makes sure that the connection is enlisted in the
Current context. When a connection is closed and returned to the pool
with an enlisted System.Transactions transaction, it is set aside in
such a way that the next request for that connection pool with the
same System.Transactions transaction will return the same connection
if it is available.

In another section it's mentioned that

Connections are drawn from the pool and assigned based on transaction context.
When a connection is closed, it is released back into the pool and into the appropriate subdivision based on its transaction context.

Based on the above, I've got two questions:

*

*Is it safe to assume that an enlisted connection, will NEVER be used in another transaction as long as the transaction exists, even though it's closed? Is there any documentation explaining if our assumptions that this is so?

*How can a connection NOT be available if it is only used in the enlisted transaction? What can be the case for this?

A:
Is it safe to assume that an enlisted connection, will NEVER be used
  in another transaction as long as the transaction exists, even though
  it's closed?

Yes.

Is there any documentation explaining if our assumptions that this is so?

You quoted it: "Connections are drawn from the pool and assigned based on transaction context."

How can a connection NOT be available if it is only used in the enlisted transaction? What can be the case for this?

It can be in-use.  eg in a TransactionScope:
using (var con = new SqlConnection(...))
{
   con.Open();
   using (var con2 = new SqlConnection(...))
   {
     con2.Open(); //con is not available, as it's open and in-use so a new connection will be opened and enlisted
   }
}


text:
Q: Testing Python "Hello World" in AWS Lambda I will apologies first hand if my question formatting is messed up. A noob programmer here
I was following steps defined in the AWS Lambda Developer Guide to run the Hello World code. Ref Page 44
def my_handler(event, context):
    message = 'Hello {} {}!'.format(event['first_name'],
                                    event['last_name'])
    return {
        'message' : message
}

Test error in AWS

I believe my error is that the code is looking for events but the input test event on the test page is providing 3 key values which have no relation to my code.
testpage

A: Make sure the Test Event in the AWS Console provides values that the program expects. It's passing three keys key1, key2, key3 while the program expects first_name and last_name
Just change the Test Event's values to the following instead
{
    "first_name": "foo",
    "last_name": "bar
}


text:
Q: Test script if host is back online E.g. system: Ubuntu/Debian.
As many of you do this probably via ping and a terminal, I always forget this terminal when switching to other task. So a notification pop-up would be useful. So can I do better as this?
while; do
  if ping -c 1 your.host.com; expr $? = 0; then
     notify-send "your.host.com back online"; sleep 30s;
  else
     sleep 30s;
  fi;
done

You will need zsh and libnotify to let the snippet work. As script:
#!/usr/bin/env zsh
while; do if ping -c 1 $1; expr $? = 0; then notify-send "$1 back online"; sleep 30s; else sleep 30s; fi; done

A: The idea looks right to me.  By using while :; do ... you can make it portable to normal Bourne shells.  The expr calls seems unnecessary.  Also, you probably want to break out of the loop when the host is found.
while :; do
    if ping -c 1 $1; then
        notify-send "$1 back online"
        break
    fi
    sleep 30s
done


text:
Q: C# - Replace two different parts of string at once I have a string which i want to change to a newer version by replacing some parts of it which are different.
Let's say i have this string:
My=name,My=surname

And i want to return:
name.surname

So i want to replace both My with "" and , with .. Is it possible?

A: str = str.Replace("My=", "").Replace(",", ".");

A: Well, if you can guarantee that neither name or surname contains the string "My" then, the answer from Tim is the right one. However if "name" or  "surname" contain the string "My" things are more complex
string input = "My=Steve,My=Myland";

StringBuilder sb = new StringBuilder();
string[] parts = input.Split(',');
foreach (string p in parts)
{
    string[] subs = p.Split('=');
    sb.Append(subs[1] + ".");
}
if(sb.Length > 0) sb.Length--;
Console.WriteLine(sb.ToString());


text:
Q: How to design a database schema for storing text in multiple languages? We have a PostgreSQL database. And we have several tables which need to keep certain data in several languages (the list of possible languages is thankfully system-wide defined).
For example lets start with:
create table blah (id serial, foo text, bar text);

Now, let's make it multilingual.
How about:
create table blah (id serial, foo_en text, foo_de text, foo_jp text,
                              bar_en text, bar_de text, bar_jp text);

That would be good for full-text search in Postgres. Just add a tsvector column
for each language.
But is it optimal?
Maybe we should use another table to keep the translations?
Like:
create table texts (id serial, colspec text, obj_id int, language text, data text);

Maybe, just maybe, we should use something else - something out of the SQL world?
Any help is appreciated.

A: I think it is best if you create two tables. One for languages, one for ids and so on.
first_table( id )
second_table( s_id, id_first_table, language_id, language_text)

A: Here's a great article the Mozilla developers put together on making their database multilingual.  It's specific to CakePHP, but the info can easily be applied to other systems.  Also, note that it makes SQL queries significantly more complex, which is a drawback.  That will generally be true regardless of your i18n implementation, though.

*

*Part 1

*Part 2

*Part 3


text:
Q: Enters the method but does not display anything I am trying to call a method to ViewController class form AppDelegate, it enter to the method but the problem is that is not displaying anything , I was looking for, but I can´t find the answer. Some one could help me? thanks
this is the code :
AppDelegate.m
- (void)applicationWillEnterForeground:(UIApplication *)application
{

    if (mainDelegate.isflagON=TRUE)
    {

        ViewController *vc=[ViewController new];
        [vc pause];

    }

}

ViewController.m
- (void)viewDidLoad
{

    [super viewDidLoad];
    AppDelegate *mainDelegate = [[UIApplication sharedApplication] delegate];
    if (mainDelegate.isflagON==false)
    {
        mainDelegate.isflagON=true;
        CGSize viewSize = self.view.bounds.size;
        // Add this line

        GameScene *scene = [[GameScene alloc] initWithSize:viewSize];
        scene.scaleMode = SKSceneScaleModeAspectFill;
        self.scene = scene;

        // Configure the view.
        skView = (SKView *)self.view;
        skView.showsFPS = YES;
        skView.showsNodeCount = YES;

        // Present the scene.
        [skView presentScene:scene];

    }else
    {
        [self doPause];
    }
}

-(void) imprime
{
    [self doPause];

}

- (void)doPause {

    CGRect myImageRect = CGRectMake(0.0f, 0.0f, 200.0f, 200.0f);
    backImageView = [[UIImageView alloc] initWithFrame:myImageRect];
    [backImageView setImage:[UIImage imageNamed:@"dialogBox.png"]];
    [self.view addSubview:backImageView];
    [self.view sendSubviewToBack:backImageView];

    //set the position of the button

    buttonContinuar = [UIButton buttonWithType:UIButtonTypeCustom];

    [buttonContinuar setBackgroundImage:[UIImage imageNamed:@"dialogButton.png"]
                               forState:UIControlStateNormal];
    buttonContinuar.frame = CGRectMake(40.0f, 50.0f, 120, 35);
    [buttonContinuar addTarget:self action:@selector(buttonWasClicked:) forControlEvents:UIControlEventTouchUpInside];
    [buttonContinuar setTitle:@"Continuar" forState:UIControlStateNormal];
    //add the button to the view
    [self.view addSubview:buttonContinuar];

    buttonMapa = [UIButton buttonWithType:UIButtonTypeCustom];
    //[button setTitle:@"Continuar" forState:UIControlStateNormal];

    [buttonMapa setBackgroundImage:[UIImage imageNamed:@"dialogButton.png"]
                          forState:UIControlStateNormal];
    buttonMapa.frame = CGRectMake(40.0f, 85.0f, 120, 35);
    [buttonMapa addTarget:self action:@selector(buttonMapaClicked:) forControlEvents:UIControlEventTouchUpInside];
    [buttonMapa setTitle:@"Mapa" forState:UIControlStateNormal];
    //add the button to the view
    [self.view addSubview:buttonMapa];

    buttonMenu = [UIButton buttonWithType:UIButtonTypeCustom];
    //[button setTitle:@"Continuar" forState:UIControlStateNormal];

    [buttonMenu setBackgroundImage:[UIImage imageNamed:@"dialogButton.png"]
                          forState:UIControlStateNormal];
    buttonMenu.frame = CGRectMake(40.0f, 120.0f, 120, 35);
    [buttonMenu addTarget:self action:@selector(buttonMenuClicked:) forControlEvents:UIControlEventTouchUpInside];
    [buttonMenu setTitle:@"Menu" forState:UIControlStateNormal];
    //add the button to the view
    [self.view addSubview:buttonMenu];

}

A: You can try this
- (void)applicationWillEnterForeground:(UIApplication *)application
{

    if (mainDelegate.isflagON=TRUE)
    {

        ViewController *vc=[[ViewController alloc]init];
        [vc pause];

    }

}


text:
Q: Enabling Reporting Services 2005 on VS 2012 I have this SSRS Reports SQL 2005 and i need this to attached on my MVC Application using VS 2012.
VS 2012 Report Viewer version 11 doesn't support RS 2005 and supports only RS 2008 later that's why i added report viewer version 9.0 to my toolbox.
I created Webform Page where report viewer will be attached but when it doesn't render to the from and says.
Error Creating Control - ReportViewer1 Failed to created designer ......

Does anyone can provide the details to deal with this Issue.
Thanks and Regards

A: To all other other people who encountered
Error Creating Control and  'RSClientController' is undefined when attaching ReportViewer version 9.0 to VS 2012, i got the solution.
What i did is to set my web config file and asp.net source below
Report.aspx
<%@ Register assembly="Microsoft.ReportViewer.WebForms, Version=9.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" namespace="Microsoft.Reporting.WebForms" tagprefix="rsweb" %>

Web.Config
<httpHandlers>
  <add verb="*"  path="Reserved.ReportViewerWebControl.axd" type = "Microsoft.Reporting.WebForms.HttpHandler, Microsoft.ReportViewer.WebForms, Version=9.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
</httpHandlers>

<compilation debug="true" targetFramework="4.0">
  <assemblies>
    <add assembly="Microsoft.ReportViewer.WebForms, Version=9.0.0.0, Culture=neutral, PublicKeyToken=B03F5F7F11D50A3A"/>
    <add assembly="Microsoft.ReportViewer.Common, Version=9.0.0.0, Culture=neutral, PublicKeyToken=B03F5F7F11D50A3A"/>
  </assemblies>
</compilation>

 <system.webServer>
    <validation validateIntegratedModeConfiguration="false"/>
    <modules runAllManagedModulesForAllRequests="true"/>
    <handlers>
       <add name="Reserved-ReportViewerWebControl-axd" path="Reserved.ReportViewerWebControl.axd" verb="*" type="Microsoft.Reporting.WebForms.HttpHandler" resourceType="Unspecified" preCondition="integratedMode"/>
    </handlers>
  </system.webServer>

Even though on the Designer View, Report Viewer still show Error Creating Control but when you run your application, the report will render normally.
Hope this will help you.
Best Regards


text:
Q: SQL case in select query I have following query
Select
        a,b,c,
        case totalcount
            when 0 then 0
            else abcd/totalcount
        end AS 'd',
        case totalcount
            when 0 then 0
            else defg/totalcount
        end AS 'e'
    From
        Table1

In this query, I have same case statement in select query...Can i make it into single select statement.
"totalcount" is some value... abcd and defg are two column values from table1. If totalcount is zero, i dont want to divide, else I wish to divide to get an average value of abcd and defg.

A: No, since you seem to be requiring two output columns in your desired resultset... Each Case statement can generate at most one output value.
It doesn't matter how many columns the case statement needs to access to do it's job, or how many different values it has to select from (how many When... Then... expressions), it just matters how many columns you are trying to generate in the final resultset.

A: At first view, I would say no, since you seem to use the exact same condition leading to different results.
Besides, this looks odd to me, why would you need two SELECT CASE for only one condition? This makes no sense.
Could you be more specific or give a real-world example of what you're trying to ask, with "real" data so that we might better answer your question?
EDIT #1
Given that:

Yes...it's two different fields....and the valud i need is calculated one...which is Value = a/b. But i need to check if b is zero or not

I would still answer no, as if they are two different fields, and you want both results in your result set, then you will need to write two CASE statements, one for each of the fields you need to verify whether it is zero-valued or not. Keep in mind that one CASE statement is equivalent to one single column only. So, if you need to check for a zero value, you are required to check for both independently.
By the way, sorry for my misunderstanding, that must be a language barrier, unfortunately. =) But my requirement for "real" data example holds, since this might light us all up with some other related solutions, we never know! =)
EDIT #2
Considering you have to check for a value of 0, I would perhaps rewrite my code as follows, for the sake of readability:
select a, b, c
        , case when condition1 <> 0 then abcd / condition1 else 0 end as Result1
        , case when condition2 <> 0 then defg / condition2 else 0 end as Result2
    from Table1

In my opinion, it is leaner and swifter in the code, and it is easier to understand what is the intention. But after all, the result would be the same! No offense made here! =)
EDIT #3
After having read your question edit:

"totalcount" is some value... abcd and defg are two column values from table1. If totalcount is zero, i dont want to divide, else I wish to divide to get an average value of abcd and defg.

I say, if it is the average that you're after, why not just use the AVG function which will deal with it internaly, without having to care about zero values?
select a, b, c
        , AVG(abcd) as Result1
        , AVG(defg) as Result2
    from Table1

Plus, considering having no record, the average can only be 0!
I don't know about your database engine, but if it is Oracle or SQL Server, and I think DB2 as well, they support this function.

A: You need to elaborate more - what is the condition? With what you have entered so far, it looks like you are just using the result of the expression, making the CASE statement redundant.
For example, see my inline comments:
SELECT a,b,c,
    case condition
        when 0 then 0        --this is unnecessary
        else abcd/condition, --this is just using the result of the condition?
    case condition
        when 0 then 0        --this is unnecessary
        else defg/condition  --this is just using the result of the condition?
from Table1

so you could just refactor this as:
SELECT  a
       ,b
       ,c
       ,expression
       ,expression
from Table1

if you actually meant the else abcd/condition as evaluate another condition or use a default value then you need to expand on that so we can answer accurately.
EDIT: if you are looking to avoid a divide by zero and you only want to evaluate condition once, then you need to do it outside of the SELECT and use the variable inside the SELECT. I wouldn't be concerned about the performance impact of evaluating it multiple times, if the condition doesn't change then its value should be cached by the query execution engine. Although it could look ugly and unmaintainable, in which case you could possibly factor condition into a function.

A: If all you're trying to do is avoid dividing by zero, and if it's not critical that an attempt to divide by zero actually produces zero, then you can do the following:
Select
    a,b,c,
    abcd / NULLIF(totalcount,0) AS 'd',
    defg / NULLIF(totalcount,0) AS 'e'
From
    Table1

This transforms an attempt to divide by zero into an attempt to divide by NULL, which always produces NULL.
If you need zero and you know that abcd and defg will never be NULL, then you can wrap the whole thing in an ISNULL(...,0) to force it to be zero.  If abcd or defg might legitimately be null and you need the zero output if totalcount is zero, then I don't know any other option than using a CASE statement, sorry.
Moreover, since it appears totalcount is an expression, for maintainability you could compute it in a subquery, such as:
Select
    a,b,c,
    abcd / NULLIF(totalcount,0) AS 'd',
    defg / NULLIF(totalcount,0) AS 'e'
From
(
    Select
        a,b,c,
        abcd,
        defg,
        (... expression goes here ...) AS totalcount
    From
        Table1
) Data

But if it's a simple expression this may be overkill.

A: Technically this is possible. I'm not suggesting it's a good idea though!
;with Table1 as
(
select 1 as a, 2 as b, 3 as c, 0 as condition, 1234 as abcd, 4567 AS defg UNION ALL
select 1 as a, 2 as b, 3 as c, 1 as condition, 1234.0 as abcd, 4567 AS defg
)
,
cte AS
(
Select
a,b,c,
case condition
    when 0 then CAST(CAST(0 as decimal(18, 6)) as binary(9)) + CAST(CAST(0 as decimal(18, 6)) as binary(9))
    else CAST(CAST(abcd/condition as decimal(18, 6)) as binary(9)) + CAST(CAST(defg/condition as decimal(18, 6)) as binary(9))
end AS d
From
Table1
)
Select
     a,
     b,
     c,
     cast(substring(d,1,9) as decimal(18, 6)) as d,
     cast(substring(d,10,9) as decimal(18, 6)) as e
From cte


text:
Q: jquery .after not working for non appeneded objects I need to create two objects separately and then add one after the other and return combined object from function. My requirement is that i have to append this object outside the function and function should return 2 created objects as one.
See code below. it only returns div .. no table  ?
function html() {
var _tab = $("
").attr("id", "table_1")
var _div = $("
").attr("id", "div_1").text("test");
return  _div.after(_tab);
}

$("body").append(html()); // only returns div .. no table

A: I had to use .add() for this ...Solved !!!
_div.add(_tab);

A: Actually this is quite strange behavior, jquery documentation clearly states that this should work in jquery > 1.4 (http://api.jquery.com/after/#after-content-content see section inserting disconnected nodes)
However in my fiddle it does not work in jquery 1.9.1 but does work in 1.6.4->1.8.3
http://jsfiddle.net/XSXYW/
apparantly i need code to post fiddle links

What version are you using?

A: function html() {
    var _tab = $("
").attr("id", "table_1")
    _tab.html('
Hi all
');
    var _div = $("
").attr("id", "div_1").text("test");
    return  _div.after(_tab);
    }

    $("body").append(html());

Is working in a glory. The problem is there is no rows in the table.

A: return _div + _tab

as simple as this
after add an element after the object and return the object only it cannot group the 2 as they are siblings and _div has to remain _div or you imagine the mess in the dom if _div was becoming div+tab ? how you'd get to _div ?


text:
Q: Hide console when py-file only (no pyw) [ANKI add-on] I am about to adjust the music fiddler add-on for ANKI SRS for windows users.
Anki ONLY runs add-ons with with ending .py, not pyw. Is there any way to hide the console that automatically pops up when I run the code.
If not, is there a way no to unselect the console windows (i basically have to click on the main anki windows after every five seconds because the console that as already closed again was in selection).
The command I use so far for opening windows is for example:
    os.system('"nircmd.exe changesysvolume"'+ change)
The complete code is below
The console runs the nircmd.exe and the number of volume units the system sound should change.
Is there a possibility to adjust the code?
# -*- coding: utf-8 -*-
# Music-Fiddler (a plugin for Anki)
# coded by D_Malik, malik6174@gmail.com
# Version 1
# License: GNU GPL, version 3 or later; http://www.gnu.org/copyleft/gpl.html

"""
A simple plugin that fiddles with music volume to reinforce quick reviewing.

Before using:
- This plugin was made for Linux. It will require modification to work on another OS.
- Ensure that the "amixer" command works on your computer. If it doesn't, you're going to need     to modify the code somehow. Don't ask me how.//Amixer has been replaced by nircmd.exe for windows
- Change all lines (in the plugin source) marked with "CHANGEME" according to your preferences.
"""

    import os
from aqt import mw
from aqt.utils import showInfo
from os import system
from aqt.qt import *
from anki.hooks import addHook

    def resetMusicTimer():
    "Boosts volume back up and starts the music timer."
    #CHANGEME: The next lines are a python dictionary associating deck names with times (in         milliseconds) between volume-decrements.
    #Eg, when using the deck "brainscience", volume will decrement every 5 seconds. When using     a deck without a listed name, "other" is used.
    #Change this according to your decks. Decks with shorter, easier cards need less time.
    deckMusicTimes = {
                 "rocketsurgery"    :   3000,
                 "brainscience"     :   5000,
                     "other"            :   5000,
             }
    if mw.col.decks.current()['name'] in deckMusicTimes:
            mw.musicTimeToDecrement = deckMusicTimes[mw.col.decks.current()['name']]
    else:
        mw.musicTimeToDecrement = deckMusicTimes["other"]
    boostMusicVolume()
    mw.musicTimer = QTimer(mw)
    mw.musicTimer.setSingleShot(True)
    mw.musicTimer.start(mw.musicTimeToDecrement)
    mw.connect(mw.musicTimer, SIGNAL("timeout()"), decrementMusicVolume)
    #showInfo(mw.state)

def changeMusicVolume(change):
    "Changes volume according to string; can be either absolute ('40') or change ('2%-')."
    os.system('"nircmd.exe changesysvolume"'+ change) #CHANGEME somehow, if amixer doesn't work

def boostMusicVolume():
    #showInfo("boosted") #To test changes, you can uncomment this line.
    os.system('"nircmd.exe changesysvolume 50000"') #CHANGEME somehow, if amixer doesn't work
    #CHANGEME: Set to however high you want your volume to go each time it's boosted back.
    #Protip: your music-playing program might have its own "volume multiplier" that you can adjust easily.

def killMusicVolume():
    #showInfo("killed") #To test changes, you can uncomment this line.
    os.system('"nircmd.exe mutesysvolume 1"') #CHANGEME somehow, if amixer doesn't work
    #CHANGEME: Set to how low volume should go when it dies, eg due to undoing a card.

def decrementMusicVolume():
    "When reviewing, decrements volume, then sets a timer to call itself. When not reviewing, kills volume and stops timer."
    if mw.state == "review":
        #showInfo("music volume goes down") #To test changes, you can uncomment this line.
        os.system('"nircmd.exe changesysvolume -5000"') #CHANGEME somehow, if amixer doesn't work
        mw.musicTimer.start(mw.musicTimeToDecrement) #(start the timer again)
    else:
        killMusicVolume()
        mw.musicTimer = None #(kill the timer if you're not reviewing)

addHook("showQuestion", resetMusicTimer)

A: It seems using the subprocess  module instead of os.system will solve your problem. Please see How to avoid console window with .pyw file containing os.system call? and How do I hide the console when I use os.system() or subprocess.call()?.


text:
Q: Adding Selectable ScrollView Brakes The View I am working on a task manager app. Recently trying to edit an item inside the scroll view. While trying to do so my views just jammed and I can not see my scroll view on the view. Instead of scroll view my add NewTaskView appears.
You may see the whole project in https://github.com/m3rtkoksal/TaskManager
struct TaskListView: View {
@State private(set) var data = ""
@State var isSettings: Bool = false
@State var isSaved: Bool = false
@State var shown: Bool = false
@State var selectedTask = TaskElement(dateFrom: "", dateTo: "", title: "", text: "")
var body: some View {
    NavigationView {
        ZStack {
            Color(#colorLiteral(red: 0.9333333333, green: 0.9450980392, blue: 0.9882352941, alpha: 1)).edgesIgnoringSafeArea(.all)
            VStack {
                TopBar()
                HStack {
                    CustomTextField(data: $data, tFtext: "Find task", tFImage: "magnifyingglass")
                    Button(action: {
                        self.isSettings.toggle()
                    }, label: {
                        ZStack {
                            RoundedRectangle(cornerRadius: 15)
                                .frame(width: 50, height: 50, alignment: .center)
                                .foregroundColor(Color(#colorLiteral(red: 0.4274509804, green: 0.2196078431, blue: 1, alpha: 1)))
                            Image("buttonImage")
                                .resizable()
                                .frame(width: 30, height: 30, alignment: .center)
                        }
                        .padding(.horizontal, 15)
                    })
                }
                CustomSegmentedView()
                ZStack {
                    TaskFrameView()
                    VStack {
                        Spacer()
                        HStack {
                            Spacer()
                            Button( action: {
                                self.isSaved.toggle()
                            }, label: {
                                ZStack {
                                    RoundedRectangle(cornerRadius: 25)
                                        .foregroundColor(Color(#colorLiteral(red: 1, green: 0.7137254902, blue: 0.2196078431, alpha: 1)))
                                    Text("+")
                                        .foregroundColor(.white)
                                        .font(.title)
                                        .fontWeight(.bold)
                                }
                                .frame(width: 50, height: 50)

                            })
                        }
                    }
                    NavigationLink(
                        destination: NewTaskView(isShown: $shown, task: selectedTask),
                        isActive: $shown,
                        label: {
                            Text("")
                        })
                }
            }
        }
        .navigationBarHidden(true)
        Spacer()
    }
    .navigationBarHidden(true)
}
}

The first image is my mixed-up view
Second is NewTaskView and the last one is proper TaskListView

While this code works like a charm without editable scroll view
struct TaskListView: View {
@State private(set) var data = ""
@State var isSettings: Bool = false
@State var isSaved: Bool = false
var body: some View {
    NavigationView {
        ZStack {
            Color(#colorLiteral(red: 0.9333333333, green: 0.9450980392, blue: 0.9882352941, alpha: 1)).edgesIgnoringSafeArea(.all)
            VStack {
                TopBar()
                HStack {
                    CustomTextField(data: $data, tFtext: "Find task", tFImage: "magnifyingglass")
                    Button(action: {
                        self.isSettings.toggle()
                    }, label: {
                        ZStack {
                            RoundedRectangle(cornerRadius: 15)
                                .frame(width: 50, height: 50, alignment: .center)
                                .foregroundColor(Color(#colorLiteral(red: 0.4274509804, green: 0.2196078431, blue: 1, alpha: 1)))
                            Image("buttonImage")
                                .resizable()
                                .frame(width: 30, height: 30, alignment: .center)
                        }
                        .padding(.horizontal, 15)
                    })
                }
                CustomSegmentedView()
                ZStack {
                    TaskFrameView()
                    VStack {
                        Spacer()
                    HStack {
                        Spacer()
                    Button( action: {
                        self.isSaved.toggle()
                    }, label: {
                        ZStack {
                            RoundedRectangle(cornerRadius: 25)
                                .foregroundColor(Color(#colorLiteral(red: 1, green: 0.7137254902, blue: 0.2196078431, alpha: 1)))
                            Text("+")
                                .foregroundColor(.white)
                                .font(.title)
                                .fontWeight(.bold)
                        }
                        .frame(width: 50, height: 50)

                    })
                    }
                    }
                    NavigationLink(
                        destination: NewTaskView(),
                        isActive: $isSaved,
                        label: {
                            Text("")
                        })
                }
            }
        }
        .navigationBarHidden(true)
        Spacer()
    }
    .navigationBarHidden(true)
}

}

A: Because that is what you told it to show in your struct ScrollViewTask. You have a ZStack that contains a ScrollView that contains a VStack with a ForEach that is supposed to display your TaskElementViews(while not part of the answer, why not just use a List) as well as your NewTaskView. In essence, you would always have a NewTaskView displayed on top of any TaskElements you have. I suspect that your code is simply not actually displaying TaskElements, either due to a lack of data, or other incorrect coding. Regardless, your NewTaskView would always overlay it.
Below is a folded version of your code that makes it clear:
struct ScrollViewTask: View {
@ObservedObject private var obser = observer()
@State var selectedTask = TaskElement(dateFrom: "", dateTo: "", title: "", text: "")
@State var shown: Bool = false
var body: some View {
    ZStack {
        ScrollView(.vertical) {...}
        .onAppear {...}

        NewTaskView(isShown: $shown, task: selectedTask)
    }
}

A: struct ScrollViewTask: View {
@ObservedObject private var obser = observer()
@State var selectedTask = TaskElement(dateFrom: "", dateTo: "", title: "", text: "")
@State var shown: Bool = false
var body: some View {

    ScrollView(.vertical) {
        VStack {
            ForEach(self.obser.tasks) { task in
                TaskElementView(task:task)
                    .onTapGesture {
                        self.selectedTask = task
                        self.shown.toggle()
                    }
            }
        }
    }
    .onAppear {
        self.obser.fetchData()
    }
    .sheet(isPresented: $shown, content: {
        NewTaskView(isShown: $shown, task: selectedTask)
    })
}
}


text:
Q: bolt CMS not routing to singular page of contenttype? I have a contenttype called textimonials in my contenttypes.yml file, like so:
#Testimonials
testimonials:
    name: Testimonials
    singular_name: Testimonial
    fields:
        name:
            type: text
            class: large
        position:
            type: text
        body:
            type: textarea
            height: 150px
    listing_template: testimonials.twig
    record_template: testimonial.twig

Now the documentation says the following:

Whenever your browser gets a page on a Bolt website, it uses an URL
  like /entries or /page/lorem-ipsum. Bolt knows how to handle URLs like
  these, and displays the information the browser requested. Bolt does
  this by mapping the URL to a so-called Route. This Route is the
  controller that (when called) fetches the content from the database,
  selects the template to use, renders the HTML page according to that
  template and the content and serves it to the browser.
At the same time, if you create a new record, Bolt will know what the
  URL for that content is. So when that URL is requested by a browser,
  it can map it back to the correct content.
For example, if you have a 'Pages' contenttype, with 'Page' as a
  singular_name, your site will automatically have pages like:

http://example.org/pages
http://example.org/page/lorem-ipsum-dolor

Well i have bolt installed on localhost , so now when i navigate to http://localhost:8080/boltCMS/testimonials , i see my testimonials.twig , but when i navigate to http://localhost:8080/boltCMS/testimonials/1 , i get a error of :

Page testimonials/1 not found.

Why ? my database is populated , so why am i getting this error ?
The templates and routes documentation can be found HERE.
Thank you.

A: There is also a singular_slug setting for a contenttype.
Bolt tries to automatically work it out, but you can configure it to be whatever you want too.

A: Try the singular_name 'Testimonial'.
http://localhost:8080/boltCMS/Testimonial/1


text:
Q: Coin changes to 3-leaf clover after playing sometime In Temple Run 2, I have completed Level 8. I have unlocked Scarlet and Barry bones. After playing a while the coins turned from diamond shape to 3-leaf clover. How do I bring back the coins?

A: Indeed, the coins are back to coins now that it is past St. Patricks's Day (March 17.)
There have also been some other times when the colors of coins changed temporarily, connected to holiday events.  For example, there were pink and red hearts for coins near Valentines' Day, for example.


text:
Q: Angularjs select using ng-options i want to filter cities using states with 2 select inputes
when the first select change it value the second one should be changed according to the first select.
i have an array of items :
$scope.items = [
     {
         name:'state1',
         cities : [
              {id:1,name:'city1'},
              {id:2,name:'city2'},
         ]
     },
     {
         name:'state2',
         cities : [
              {id:1,name:'city1'},
              {id:2,name:'city2'},
         ]
     },
];

i tried this but its not working :
first for states :
<select ng-model="state" ng-options="s.id as s.name in states"  ></select>

second for cities :
<select ng-model="city" ng-options="s.cities.id as s.cities.name for s in items | filter:{s.name:state}" ></select>

A: The first dropdown selects the whole country object. The options of the second dropdown are the cities of the selected country :
<select class="country" ng-model="selectedCountry" ng-options="country.name for country in items">
    <option value="">Choose country</option>
</select>

<select ng-if="selectedCountry" class="city" ng-model="selectedCity" ng-options="city.name for city in selectedCountry.cities">
    <option value="">Choose city</option>
</select>

Fiddle


text:
Q: Changing data type for one class attribute causes a segfault during construction of a subclass object This version of code works well:
class Object
{
public:

    // Object( string name, string state ) <-- string version
    Object( string name, bool state )
    {
        this->name = name ;
        this->state = state ;
    }

protected:
    string name ;
    bool state ;
    // string state ; <-- string version
};

class Tool : public Object
{
public:
    Tool(string name):Object(name,state)
    {
        this->state = true ;

        //this->state = "true" ; <-- string version
    }
};

int main ()
{

    Tool* tool = new Tool("name") ;

    cin.get() ;
    return 0 ;
}

...but if I make the state attribute a string (and substitute lines of code with the nearby "string versions" which I commented out) then, after a compilation with no issues, the program gives a segfault at runtime.
There are no problems when creating base class objects.
The debugger outputs:
#0 0x45b74c std::basic_string<char, std::char_traits<char>, std::allocator<char> >::basic_string(std::string const&) () (??:??)
#1 ??   ?? () (??:??)

Why does making the state a string cause problems?

A: Tool(string name):Object(name,state)

You're trying to use an uninitialized member state (the protected member of the base class Object) as the argument of the Object's constructor, it should be initialized by Object's constructor. Using an uninitialized variable leads to UB, means anything could happen. In your case it causes a segment fault when using std::string.
BTW: You should get a compile warning for it. Such as clang with -Wall.
source_file.cpp:28:35: warning: base class 'Object' is uninitialized when used here to access 'Object::state' [-Wuninitialized]
    Tool(string name):Object(name,state)
                                  ^


text:
Q: PHP ini error reporting not working. Error 500 all parse/syntax errors Have PHP 5.5.8 running with IIS 8.  For some reason, since I have updated PHP, I get no error messages, just an error 500 page.  Pages with no errors function correctly.
I have set in the php.ini (in c:\php\php.ini) as follows
error_reporting = E_ALL
display_errors = on

I have the cgi mappings in IIS8 set to c:\php\php-cgi.exe for *.php extensions
The php install is in c:\php  Here is the phpinfo()
one strange item at the bottom is: Environment Path C:\Program Files (x86)\PHP\v5.4  -- there is no php or folder here ANYMORE.  And the path variable has been changed to c:\php.  Why is the old install location still showing???
PHP Version 5.5.8

System  Windows NT computername 6.2 build 9200 (Windows Server 2012 Standard Edition) i586

Build Date  Jan 8 2014 15:26:19

Compiler    MSVC11 (Visual C++ 2012)

Architecture    x86

Configure Command   cscript /nologo configure.js "--enable-snapshot-build" "--enable-
debug-pack" "--disable-zts" "--disable-isapi" "--disable-nsapi" "--without-mssql" "--without-pdo-mssql" "--without-pi3web" "--with-pdo-oci=C:\php-sdk\oracle\instantclient10\sdk,shared" "--with-oci8=C:\php-sdk\oracle\instantclient10\sdk,shared" "--with-oci8-11g=C:\php-sdk\oracle\instantclient11\sdk,shared" "--with-enchant=shared" "--enable-object-out-dir=../obj/" "--enable-com-dotnet=shared" "--with-mcrypt=static" "--disable-static-analyze" "--with-pgo"

Server API  CGI/FastCGI

Virtual Directory Support   disabled

Configuration File (php.ini) Path   C:\Windows

Loaded Configuration File   C:\PHP\php.ini

Scan this dir for additional .ini files     (none)

Additional .ini files parsed    (none)

Is there something in IIS that is overriding the display error page?  I had no issues with an older version of php.

A: Strangely, if you have:
error_reporting = E_ALL
display_errors = on
log_errors = on

then you get the ERROR 500 page for ALL errors
Just change only
log_errors = off

then you are good to go


text:
Q: Best practice on Linux servers and CPU/power throttling? I am running a couple of Debian 6 (2.6.32) and 7 (3.2) Linux servers and all of them have energy saving settings enabled in their BIOS. Furthermore Linux shows that the CPUs are throttled if the servers are idling.
I wonder if this could cause any harm - could there be e.g. performance impacts because Linux would not be able to handle throttling correctly?
Is there a best practice for Linux servers and power/CPU throttling?
Do you guys switch your energy profiles to "performance" or do you leave both the BIOS and the OS with their default settings?
The reason I am asking is that I encountered several performance issues on physical Dell servers although all values (CPU/load, memory, I/O, network etc.) seemed to be normal. After changing the BIOS power settings to "performance" in those specific cases, I was able to get rid of the performance issues.

A: Interesting question...
In general, I base the system performance profile on the application and intended use of the server. I typically work with:

*

*Low-latency transaction-heavy systems.

*Virtualization hosts (VMware).

*Linux-based ERP servers.

The systems that require deterministic performance and low-latency are typically set to a high-performance profile, disabling all C-States/P-States and any power throttling.
The Virtualization hosts can follow the same model, but if I'm power-constrained (like in a co-location facility) or the workload is minimal across the hosts/cluster, I will leave the default balanced power/performance profile enabled. That's typically because I'm charged for power and cooling in a data center, and may need to be able to consolidate more physical servers into a given footprint.
The ERP servers are typically standalone. Lighter workloads get the default balanced profile. Systems that require more specific tuning and have a heavier workload (24x7 operation) may see high-performance power profiles applied.
-- edit --
Again, performance tends to be more deterministic under the high-performance power profiles. It really depends on your specific application and what your users are experiencing (we can't tell you what to do). You state yourself that disabling the BIOS power-saving features corrected a performance problem you were having.
For Linux, download the PowerTop utility and experiment to understand what your CPUs are doing under realistic workloads.

A: I think it might be a benefit for others stumbling accross this question if I post my latest knowledge gain here as a reply.
I talked to Dell and Intel since in my specific situation, Linux is not able to scale up throttled CPUs again in certain situations. Dell replied that this issue is known and occurs both with VMWare  hypervisors and many Linux variants, so it is not Debian or Dell model specific. As far as I can tell, all Dell systems using Intel CPUs can be affacted and of course it is also possible that other hardware vendors share this problem.
Dell claims in a mail written in German:

*

*Linux fails to negotiate power settings with the hardware in my specific cases

*Updating both the OS and firmware might help

*Using the "Performance" profile is a known workaround

Looking at Dell's mail it seems that there is no way to fix this, only a workaround.
Therefore the reply to my own question would be:
In order to prevent possible performance or CPU scaling issues with your servers, I highly recommend to put all your servers in the datacenter into "max. power" mode.


text:
Q: Exception of type 'Foundation.You_Should_Not_Call_base_In_This_Method' was thrown I want to integrate freshChat in xamarin IOS so I added IOS binding library and added ApiDefinition, LibFDFreshChatSDK.a & Struct and Create Dll from it.
Copy the generated DLL and added a reference in Xamarin IOS.
When I create an object of FreshchatConfig by passing  AppId and AppKey in parameter it throws exception

"Exception of type
  'Foundation.You_Should_Not_Call_base_In_This_Method' was thrown"

// @interface FreshchatConfig : NSObject
[BaseType(typeof(NSObject))]
[Model]
public interface FreshchatConfig
{
    // @property (nonatomic, strong) NSString * appID;
    [Export("appID", ArgumentSemantic.Strong)]
    string AppID { get; set; }

    // @property (nonatomic, strong) NSString * appKey;
    [Export("appKey", ArgumentSemantic.Strong)]
    string AppKey { get; set; }

    // @property (nonatomic, strong) NSString * domain;
    [Export("domain", ArgumentSemantic.Strong)]
    string Domain { get; set; }

    // @property (nonatomic, strong) NSString * themeName;
    [Export("themeName", ArgumentSemantic.Strong)]
    string ThemeName { get; set; }

    // @property (nonatomic, strong) NSString * stringsBundle;
    [Export("stringsBundle", ArgumentSemantic.Strong)]
    string StringsBundle { get; set; }

    // @property (assign, nonatomic) BOOL gallerySelectionEnabled;
    [Export("gallerySelectionEnabled")]
    bool GallerySelectionEnabled { get; set; }

    // @property (assign, nonatomic) BOOL cameraCaptureEnabled;
    [Export("cameraCaptureEnabled")]
    bool CameraCaptureEnabled { get; set; }

    // @property (assign, nonatomic) BOOL notificationSoundEnabled;
    [Export("notificationSoundEnabled")]
    bool NotificationSoundEnabled { get; set; }

    // @property (assign, nonatomic) BOOL teamMemberInfoVisible;
    [Export("teamMemberInfoVisible")]
    bool TeamMemberInfoVisible { get; set; }

    // @property (assign, nonatomic) BOOL showNotificationBanner;
    [Export("showNotificationBanner")]
    bool ShowNotificationBanner { get; set; }

    // @property (assign, nonatomic) BOOL responseExpectationVisible;
    [Export("responseExpectationVisible")]
    bool ResponseExpectationVisible { get; set; }

    // -(instancetype)initWithAppID:(NSString *)appID andAppKey:(NSString
    *)appKey;
    [Export("initWithAppID:andAppKey:")]
    IntPtr Constructor(string appID, string appKey);
}

A: Try removing [Model] from the API definition for FreshchatConfig, e.g.:
// @interface FreshchatConfig : NSObject
[BaseType(typeof(NSObject))]
public interface FreshchatConfig


text:
Q: Javascript: Regex to replace two characters and all their surrounding whitespace I have a string and would like to replace all instances of the two characters "<" and ">" together with all its surrounding whitespace (no tabs, no newlines, possibly empty) by " < " and " > ", respectively.

Can I do this with a one-liner replace regex expression?

The slow and hard way would be
while (entry.value.indexOf(" <") > -1) {
    entry.value = entry.value.replace(" <","<");
}
while (entry.value.indexOf("< ") > -1) {
    entry.value = entry.value.replace("< ","<");
}
while (entry.value.indexOf(" >") > -1) {
    entry.value = entry.value.replace(" >",">");
}
while (entry.value.indexOf("> ") > -1) {
    entry.value = entry.value.replace("> ",">");
}
entry.value = entry.value.replace("<"," < ").replace(">"," > ");

Shortening the whitespace is explained at Regex to replace multiple spaces with a single space, but I do not assume whitespaces around the two characters.
The use case I have are saving math expressions in a database to be presented on a website using MathJax. Doing so, one runs into exactly this problem, see http://docs.mathjax.org/en/latest/tex.html#tex-and-latex-in-html-documents.
Typical expressions are
"Let $i$ such that $i<j$..."
"Let $<I>$ be an ideal in..."

(the later wouldn't even render here in the preview in normal text mode.)

A: Copy pasting Wiktor's comment here. \s matches any whitespace character, * indicates to match 0 or more of those whitespace characters, [<>] matches any < or >, the g flag indicates to do a global replace instead of just replacing the first match, and the parentheses are to create a capture group so that we can use $1 to refer to the match as a backreference in the replacement string.
See some example input output below.
'<>' // => ' <  > ' (two spaces between the carets)
'<\t\t\n\ \n<' // => ' <  < ' (again two spaces)
'>a     \t b<    ' // => ' > a     \t b < '
'a>\n   b   <c    ' // => 'a > b < c    '

a = 'fpo<  \n>\naf      ja\tb<>\t<><>asd\npfi b.<< >    >';
b = a.replace(/\s*([<>])\s*/g, ' $1 ');

console.log(b);


text:
Q: Book : Ron Larson Calculus Find the Limit if it exists? I answered a question to determine whether a particular limit of a function exists and I got the right answer that it didn't exist but for a different reason to what the book states.
Question
Find the limit(if it exists) and if it does not exist explain why.
$\lim\limits_{x\to-3^-}\left(\frac{x}{\sqrt {x^2-9}}\right)$
My answer
The domain is restricted to the closed interval $[-3 , 3]$
The limit does not exist because the function is only continuous on the right hand side of $x=3$
Books Solution
The Limit does not exist. The function decreases without bound as x approaches -3 from the left .
Can someone please explain if my solution would suffice and also what the book means by this , since i thought that the function was undefinded for values of $ x<-3$

A: The domain is not $[-3,3].$ The domain is
$$\{x: x^2 >9\}=(- \infty,3) \cup (3, \infty).$$
We have
$$\frac{x}{\sqrt{x^2-9}} \to - \infty$$
as $x \to -3^-$.

A: Note that he asks you to compute the left-sided limit
$$
\lim_{x \to - 3^-} f(x)
$$
where $f$ is the expression of the function. Notice the $-$ as an exponent of the $3$. Therefore your solution doesn't suffice. The book is correct: the limit "is" $- \infty$, so it doesn't exist.

A: To find the interval where the function is defined notice that we need $x^2>9$, that is $x\in (-\infty,-3)\cup (3,\infty)$.
To see why it grows without bound write $ f(-3-\epsilon)=\frac{-3-\epsilon}{\sqrt{\epsilon^2+6\epsilon}}$ for $\epsilon >0$. Do you see why this grows to $-\infty$ as $\epsilon$ decreases?


text:
Q: Angular 2 method returns different results when called in ngOnInit verse a button click I'm building a web site using the Angular 2 CLI, the page is a reactive form, and I've created a method called addQuestion() that is called in ngOnInit.  When it is ran that way it works as I'd like, adding a Question object with and array of answers.  When I run the same method from a button press, from the page it adds a Question object without the array of answers attached.  I've highlighted the line that is not working correctly.
Can someone explain what I'm doing wrong?
To be more clear, the method:

*

*Creates a Question object

*Then creates 4 answer objects and adds them to the Question object

*Then pushes the Question object into a Questions array

When I run this method from ngOnIt it creates the full Question object with the embedded answers array (filled with 4 answers) and adds it to the questions array.
When I run the method from a button press on the page itself with:
Add Question

it adds the Question object, but with a empty answers array.  I added an arrow below to where I think the error is occurring.  I added some console log commands right before this line and they show that they answers are getting added correctly, but after this push it's like they disappear.  I'm thinking this is some sort of scope error, but I'm too much of a junior developer to figure it out on my own.
export class QuestionListComponent implements OnInit {

  @Input('quizForm')
  public quizForm: FormGroup;

  @Input('questions')
  public questions: Question[];

  nextId: number;

  constructor(private cd: ChangeDetectorRef) { }

  // <previous> 1. Create FormGroup quizForm
  // <previous> 2. Add Quiz controls to FormGroup (via toFormGroup)
  // 3. Add questions FormArray to FormGroup
  // 4. Add first Question to questions FormArray

  ngOnInit() {
    console.log('Initializing question list', this.questions);
    this.nextId = 1;
    this.quizForm.addControl('questions', new FormArray([]));
    this.addQuestion();
  }

  //_.uniqueId(),
  private getNextId(): number{
    return this.nextId++
  }

  addQuestion() {
    const question: Question = {
        id: this.getNextId(),
        title: 'My Question',
        instructions: 'Instructions here',
        time: 30000,
        answerId: 1,
        answers: []
    };

    for(var i=1;i<=4;i++){
      const a: Answer = {
        id: i,
        data: "Answer #" + i.toString(),
        type: "TEXT"
      }
      question.answers.push(a);
    }
    console.log("question equals=" + question);
    console.log("question answer 2 data = " + question.answers[1].data);

    this.questions.push(question); <--- This is the error line of code
    this.cd.detectChanges();
    return false;
  }

Edit:  An additional piece of information.  I based my code on this excellent Reactive Forms tutorial, and in his code he used interfaces instead of classes.  I don't have a lot of experience with interfaces so I'm wondering if this is important to my situation.  Here's the interfaces:
export interface Question {
  id: number;
  title: string;
  instructions: string;
  time: number;  // The number of Milliseconds the question will be shown
  answerId: number; //the array id of the correct answer
  answers?: Answer[];
}

export interface Answer {
  id: number;
  data: string;
  type: string; // to be enum AnswerType in the future
}

I'll try switching them to classes and see if that solves my problem.  Here is the HTML code, as I suspect the problem might be here as well.

      Question {{question.id}} (Remove)
      <app-question-form [questions]="quizForm.controls.questions" [question]="question">
      </app-question-form>

    Add Question

Edit: More clues.  This SO question asks about a similar problem, and the answer to that question says "You will not be able to access this input inside Component Two's contractor, only inside its "ngOnInit". See this for reference".  If that's true, it's the first time I've heard of it.  I thought that was the reason for the Input decorator/annotation, was to pass objects between components.

A: Have you tried to use the keyword let instead of const for your variables?

A: Your questions is null or undefined whatever you define the type whiich is Question[] , so it call null then didn't include the method of push so error is throw.
@Input('questions')
  public questions: Question[] = [];

A: I found the bug, and I'll still admit I'm perplexed.  In the child component I was passing the object that was getting corrupted.  The object was a Question object and it contained an array of answer objects and that list was called answers.  This Object was getting passed to the child using the @Input() decorator.  You can see the interface listed above.
My bug was that my answers array was getting destroyed or reset so it was empty when I called the method from the parent component.  So what was causing the problem?  In the child components ngOnInit() I was also creating another variable called answers.  Heres the line of code...
 this.questionForm.addControl('answers', new FormArray([]));

Which is a FormArray object and unrelated to the answers which is a property of a object I'm passing...but with this line in my code, my object gets corrupted...and the answers array gets wiped.  When I change the name of the FormArray to something other than 'answers' it works fine.
Is this a bug in Angular?


text:
Q: Job failing at particular step, no exceptions logged or in console I have a baffling issue that I've been fighting with for a few days that the cause for it seems to be quite elusive. In a nutshell, I have three steps in a particular job, and the job always fails after Step #2. I've verified that the Tasklets being executed are returning as expected, the listeners afterStep indicate that the expected return value for ExitStatus is "CONTINUE", but it never reaches the beforeStep for the next Step, stating that the job has failed. I've stepped through the code to find that it fails at SImpleJobLauncher.run. I set logging to trace, and I believe I've determine where the first occurrence of this issue is logged.
  2017-06-15 10:24:42 [jobLauncherTaskExecutor-2] DEBUG o.s.batch.core.step.AbstractStep.execute 281 - Step execution complete: StepExecution: id=3397, version=3, name=STEP THAT ISN'T RUNNING, status=COMPLETED, exitStatus=CONTINUE, readCount=0, filterCount=0, writeCount=0 readSkipCount=0, writeSkipCount=0, processSkipCount=0, commitCount=1, rollbackCount=0
  2017-06-15 10:24:42 [jobLauncherTaskExecutor-2] DEBUG o.s.t.s.AbstractPlatformTransactionManager.getTransaction 367 - Creating new transaction with name [org.springframework.batch.core.repository.support.SimpleJobRepository.updateExecutionContext]: PROPAGATION_REQUIRED,ISOLATION_DEFAULT
  2017-06-15 10:24:42 [jobLauncherTaskExecutor-2] DEBUG o.s.j.d.DataSourceTransactionManager.doBegin 248 - Acquired Connection [jdbc:oracle:thin:@localhost:1521:orcl, UserName=USERNAME, Oracle JDBC driver] for JDBC transaction
  2017-06-15 10:24:42 [jobLauncherTaskExecutor-2] DEBUG o.s.j.d.DataSourceTransactionManager.doBegin 265 - Switching JDBC Connection [jdbc:oracle:thin:@localhost:1521:orcl, UserName=USERNAME, Oracle JDBC driver] to manual commit
  2017-06-15 10:24:42 [jobLauncherTaskExecutor-2] TRACE o.s.t.s.TransactionSynchronizationManager.bindResource 193 - Bound value [org.springframework.jdbc.datasource.ConnectionHolder@4ab1bdf6] for key [org.apache.commons.dbcp.BasicDataSource@58aa1d72] to thread [jobLauncherTaskExecutor-2]
  2017-06-15 10:24:42 [jobLauncherTaskExecutor-2] TRACE o.s.t.s.TransactionSynchronizationManager.initSynchronization 272 - Initializing transaction synchronization
  2017-06-15 10:24:42 [jobLauncherTaskExecutor-2] TRACE o.s.t.i.TransactionAspectSupport.prepareTransactionInfo 474 - Getting transaction for [org.springframework.batch.core.repository.support.SimpleJobRepository.updateExecutionContext]
  2017-06-15 10:24:42 [jobLauncherTaskExecutor-2] DEBUG o.s.jdbc.core.JdbcTemplate.update 869 - Executing prepared SQL update
  2017-06-15 10:24:42 [jobLauncherTaskExecutor-2] DEBUG o.s.jdbc.core.JdbcTemplate.execute 616 - Executing prepared SQL statement [**UPDATE BATCH_JOB_EXECUTION_CONTEXT SET SHORT_CONTEXT = ?, SERIALIZED_CONTEXT = ? WHERE JOB_EXECUTION_ID = ?**]
  2017-06-15 10:24:42 [jobLauncherTaskExecutor-2] TRACE o.s.t.s.TransactionSynchronizationManager.getResource 140 - Retrieved value [org.springframework.jdbc.datasource.ConnectionHolder@4ab1bdf6] for key [org.apache.commons.dbcp.BasicDataSource@58aa1d72] bound to thread [jobLauncherTaskExecutor-2]
  2017-06-15 10:24:42 [jobLauncherTaskExecutor-2] TRACE o.s.t.s.TransactionSynchronizationManager.getResource 140 - Retrieved value [org.springframework.jdbc.datasource.ConnectionHolder@4ab1bdf6] for key [org.apache.commons.dbcp.BasicDataSource@58aa1d72] bound to thread [jobLauncherTaskExecutor-2]
  2017-06-15 10:24:42 [jobLauncherTaskExecutor-2] DEBUG o.s.jdbc.core.JdbcTemplate$2.doInPreparedStatement 879 - SQL update affected 1 rows
  2017-06-15 10:24:42 [jobLauncherTaskExecutor-2] TRACE o.s.t.s.TransactionSynchronizationManager.getResource 140 - Retrieved value [org.springframework.jdbc.datasource.ConnectionHolder@4ab1bdf6] for key [org.apache.commons.dbcp.BasicDataSource@58aa1d72] bound to thread [jobLauncherTaskExecutor-2]
  2017-06-15 10:24:42 [jobLauncherTaskExecutor-2] TRACE o.s.t.i.TransactionAspectSupport.commitTransactionAfterReturning 502 - Completing transaction for [org.springframework.batch.core.repository.support.SimpleJobRepository.updateExecutionContext]
  2017-06-15 10:24:42 [jobLauncherTaskExecutor-2] TRACE o.s.t.s.AbstractPlatformTransactionManager.triggerBeforeCommit 930 - Triggering beforeCommit synchronization
  2017-06-15 10:24:42 [jobLauncherTaskExecutor-2] TRACE o.s.t.s.AbstractPlatformTransactionManager.triggerBeforeCompletion 943 - Triggering beforeCompletion synchronization
  2017-06-15 10:24:42 [jobLauncherTaskExecutor-2] DEBUG o.s.t.s.AbstractPlatformTransactionManager.processCommit 759 - Initiating transaction commit
  2017-06-15 10:24:42 [jobLauncherTaskExecutor-2] DEBUG o.s.j.d.DataSourceTransactionManager.doCommit 310 - Committing JDBC transaction on Connection [jdbc:oracle:thin:@localhost:1521:orcl, UserName=USERNAME, Oracle JDBC driver]
  2017-06-15 10:24:42 [jobLauncherTaskExecutor-2] TRACE o.s.t.s.AbstractPlatformTransactionManager.triggerAfterCommit 956 - Triggering afterCommit synchronization
  2017-06-15 10:24:42 [jobLauncherTaskExecutor-2] TRACE o.s.t.s.TransactionSynchronizationManager.clearSynchronization 331 - Clearing transaction synchronization
  2017-06-15 10:24:42 [jobLauncherTaskExecutor-2] TRACE o.s.t.s.AbstractPlatformTransactionManager.triggerAfterCompletion 973 - Triggering afterCompletion synchronization
  2017-06-15 10:24:42 [jobLauncherTaskExecutor-2] TRACE o.s.t.s.TransactionSynchronizationManager.doUnbindResource 243 - Removed value [org.springframework.jdbc.datasource.ConnectionHolder@4ab1bdf6] for key [org.apache.commons.dbcp.BasicDataSource@58aa1d72] from thread [jobLauncherTaskExecutor-2]
  2017-06-15 10:24:42 [jobLauncherTaskExecutor-2] DEBUG o.s.j.d.DataSourceTransactionManager.doCleanupAfterCompletion 368 - Releasing JDBC Connection [jdbc:oracle:thin:@localhost:1521:orcl, UserName=USERNAME, Oracle JDBC driver] after transaction
  2017-06-15 10:24:42 [jobLauncherTaskExecutor-2] DEBUG o.s.jdbc.datasource.DataSourceUtils.doReleaseConnection 327 - Returning JDBC Connection to DataSource
  2017-06-15 10:24:42 [jobLauncherTaskExecutor-2] DEBUG o.s.b.c.job.flow.support.SimpleFlow.resume 183 - Completed state=JOB NAME.STEP THAT ISN'T RUNNING with status=CONTINUE
  2017-06-15 10:24:42 [jobLauncherTaskExecutor-2] DEBUG o.s.b.c.job.flow.support.SimpleFlow.resume 167 - Handling state=JOB NAME.FAILED
  2017-06-15 10:24:42 [jobLauncherTaskExecutor-2] DEBUG o.s.b.c.job.flow.support.SimpleFlow.resume 183 - Completed state=JOB NAME.FAILED with status=FAILED
2017-06-15 10:24:42 [jobLauncherTaskExecutor-2] DEBUG o.s.batch.core.job.AbstractJob.execute 308 - Job execution complete: JobExecution: id=1224, version=1, startTime=Thu Jun 15 10:24:42 EDT 2017, endTime=null, lastUpdated=Thu Jun 15 10:24:42 EDT 2017, status=FAILED, exitStatus=exitCode=FAILED;exitDescription=, job=[JobInstance: id=871, version=0, Job=[JOB NAME]], jobParameters=[{timestamp=1497536682001}]

Job setup is as follows. It uses java annotation instead of xml
@Autowired
private JobBuilderFactory jobBuilderFactory;

@Bean
    public Job importCostDataJob(@Qualifier("firstStep") Step firstStep,
                                 @Qualifier("secondStep") Step secondStep,
                                 @Qualifier("stepThatIsntRunning") Step stepThatIsntRunning,
                                 @Qualifier("customJobListener") CustomJobListener customJobListener
    ) {

        return jobBuilderFactory.get("JOB NAME")
                                .incrementer(new RunIdIncrementer())
                                .listener(customJobListener)
                                .flow(firstStep)
                                .next(secondStep)
                                .next(stepThatIsntRunning)
                                .build()
                                .build();
}

The closest thing that I can figure is for whatever reason that SQL query in bold is causing the issue, but I can't see has to how or why? It's not making it as far as the listener for the failed step, so not too sure where else I could check that may shed some light on this.
Anyone else ever ran into this at all?