text:
Q: How to refer to the variable stored by the structure, which is also part of other structs I'm trying to learn how to use structures, but I'm stuck with (probably very simple) problem. How do I refer to variable x, which is stored by the structure POINT, which belongs RECT structure? Beginnings are always difficult for me.
#include <iostream>
using namespace std;

struct Point {
    int x, y;
};

struct Rect {
    Point bottom_left, top_right;
};

void printPoint(const Point* p){
    cout << "(" << p->x << "," << p->y << ")";
}

void printRect(const Rect* r){
    cout << "["; printPoint(&r->top_right);
    cout << ","; printPoint(&r->bottom_left);
    cout << "]" << endl;
}

bool haveIntersection(const Rect* r1, const Rect* r2){
    cout << &r1->bottom_left->x;
}

int main() {
    Rect r1 = { {1,1}, {4,3} };
    Rect r2 = { {2,0}, {3,4} };
    Rect r3 = { {0,4}, {1,5} };
    printRect(&r1);
    haveIntersection(&r1, &r2);
}

A: Your struct are
struct Point {
    int x, y;
};

struct Rect {
    Point bottom_left, top_right;
};

If you declare Rect object:
Rect rectangle;
Rect* rectanglePtr = new Rect();

You can access the x,y values in this way:
rectangle.bottom_left.x;
rectanglePtr->bottom_left.x;

edit
in your case, haveIntersection become:
bool haveIntersection(const Rect* r1, const Rect* r2) {
    /* Warning: you aren't using r2 var and return nothing */
    cout << (r1->bottom_left).x;
}

A: Simply like this r1.bottom_left.x
Notice that r1.bottom_left returns a Point&. Therefor you can just work with it like any other Point


text:
Q: Decay multiple functions inside caller method This question is related mostly to an issue of large code maintenance and re-usability that I have. I have a several classes which have a method like this:
void MyClassX::Draw(){

   ///Some large chunk of code#1 here

   ///Another large chunk of code#2 goes here

   ///Another large chunk of code#3 goes here

}

void MyClassY::Draw(){

   ///Some large chunk of code#1 here

   ///Another large chunk of code#2 goes here

}

The difference between the variations of that method are that some of those chunks of code are optional in different classes.
Now, it may sound silly, but because that method does some performance critical real-time processing (3D rendering). I don't use functions for those code chunks and don't want to wrap them with those as I am trying to reduce a number of functions calls in general. What I want is to define those functions in some block (for example using #define) and just declare those instead of the whole code chunks in the appropriate places inside void Draw(). I wouldn't want to use pre-processor for it because it is hard to edit such a code (no proper error hinting or debugging). Another option I thought would be inline functions. But because the compiler doesn't guarantee to inline I am not sure this way is efficient. Are there other tricks? Maybe through C++ templates usage? Can I force some function body to decay inside caller method?
P.S. Because of performance consideration I also don't use inheritance for those classes as it basically also could solve that problem by defining all those chunks as functions in the base class. Also inside void Draw() I try to reduce conditional branching to a bare minimum.

A: There are ways to force inline functions on some compilers, such as __forceinline on MSVC or __attribute__((always_inline)) on GCC. It's very compiler-specific but you can guarantee it with a few caveats. There I recommend checking your compiler documentation as well as getting used to analyzing disassembly to some broad level (enough to recognize function calls, e.g., which is fairly easy because you can trace through it with a debugger and notice when it's branching).
That said, I really think you might be looking at this wrong. I could be wrong, and perhaps you have very special needs I've not encountered before, but I'm in a performance-critical field where, aside from correctness, efficiency is often directly proportional to the perceived quality of the product (I'm also in 3D, including path tracing).
I'm used to working with a profiler in hand and I've learned to take the idea of trusting the optimizer with a grain of salt. There's things optimizers and standard libs don't do so well, and I'm used to doing things like rolling my own memory allocators with considerable gains.
But I have never, ever encountered a case in my numerous profiling sessions where the compiler did a poor job with respect to the overhead of function calls. I have seen optimizers have hiccups and do a poor job with instruction selection or register allocation, where rewriting the code a certain way which shouldn't actually help did help emit more efficient assembly. That includes turning some big chunks of code into more functions, which you wouldn't think should aid performance but helped the compiler with those two areas (register allocation and instruction selection).
One of the more helpful things I've found in optimization is that optimizers might be great, but they don't understand what kind of user input is going to be received at runtime. That's a key aspect of common case execution that only someone who understands the design of the product can anticipate. So one of the things I've found is that putting the rare case branches of code into separate, unlined functions so that the logic isn't all inlined in one giant blob actually helps somehow (didn't investigate the disassembly for all of these cases, just noticed improvements in times). I think it's just kind of helping the compiler not look at all of your code as kind of a flat playing field, helping it to optimize a bit more selectively/locally since there's only so many registers, for example, and putting everything in one gigantic function might confuse the optimizer as to which part needs more attention.
That said, I have found it generally helpful to work with more centralized code during profiling and optimization. That's not because having more centralized code in a large function actually speeds things up, but because it's easier to work with something a bit less structured when you're trying to squeeze out micro-level efficiencies. It's easier to impose more structure after you've micro-tuned things than to be trying to unravel it before you go through those exhaustive profiling sessions, so it can be helpful to write code in this way sometimes and sacrifice some neatness and structure for big blocks of code. But the benefit there is more in the ease of changing that kind of code after profiling it and gaining that efficiency knowledge in hindsight to help organize the code; I've never actually seen such code actually make things faster.
So I really think you would do better not to focus on inlining that much and leave it more up to the optimizer. There's usually better things to optimize with clearer gains even at the smallest of micro-efficiency levels.

redpajama_set_name: RedPajamaStackExchange


text:
Q: java user defined function in oracle using byte[] Given this table in Oracle
create table test (bytes raw(100), chset varchar2(50))
insert into test (bytes, chset) values (hextoraw('454647'), 'iso-8859-1')

or in MSSQL
create table test (bytes varbinary(100), chset nvarchar(50))
insert into test (bytes, chset) values (0x454647, 'iso-8859-1')

I'm looking for a comprehensive example of how to create a UDF for Oracle in Java that makes use of Java's text encoding support.
In MSSQL I would create this .Net assembly:
using System.Text;
using Microsoft.SqlServer.Server;

namespace Whatever
{
    public class Common
    {
        [SqlFunction]
        public static string Decode(byte[] Bytes, string EncodingName)
        {
            return Encoding.GetEncoding(EncodingName).GetString(Bytes);
        }
    }
}

and use these commands to register the assembly and define the udf:
create assembly MyAssembly from '...\MyAssembly.dll'

create function decode(@bytes varbinary(max), @chset nvarchar(100))
returns nvarchar(max) as external name MyAssembly.[Whatever.Common].Decode

and use it in a query like this:
> select *, dbo.decode(bytes, chset) decoded from test

bytes      chset       decoded
0x454647   iso-8859-1  EFG

update
so far I've created this Java class:
import java.nio.*;
import java.nio.charset.*;

public class Common
{
    public static String Decode(byte[] Bytes, String CharsetName)
    {
        return Charset.forName(CharsetName).decode(ByteBuffer.wrap(Bytes)).toString();
    }
}

and used these commands to create the UDF:
create directory jdir as 'C:\...';
create java class using bfile (jdir, 'Common.class');

create function jdecode(bytes raw, chset varchar2) return nvarchar2 as language java
name 'Common.Decode(java.lang.byte[], java.lang.String) return java.lang.String';

but when I try to use it I get this error:
> select jdecode(hextoraw('454647'), 'iso-8859-1') from dual

ORA-29531: no method Decode in class Common

update 2
turns out java.lang.byte[] isn't a thing, changing it to just byte[] got things working. Thanks Tim!
create function jdecode(bytes raw, chset varchar2) return nvarchar2 as language java
name 'Common.Decode(byte[], java.lang.String) return java.lang.String';

there's a handy table here: http://download.oracle.com/docs/cd/B19306_01/java.102/b14187/chsix.htm#BABJIJEB

A: Do you really need a user defined function (UDF) java or otherwise when oracle already provides sufficient utilities for such conversions?
The UTL_I18N package supplies all the needed functionality.  The MAP_CHARSET funtion maps from ISO character set names to Oracle character set names, then the RAW_TO_CHAR function converts your raw data of the specified character set to a VARCHAR2 in the database character set.
SQL Fiddle
Oracle 11g R2 Schema Setup:
create table test (bytes raw(100), chset varchar2(50));
insert into test (bytes, chset) values (hextoraw('454647'), 'iso-8859-1');

Query 1:
select t.*
     , UTL_I18N.RAW_TO_CHAR( bytes
                           , UTL_I18N.MAP_CHARSET(chset,0,1)) decoded
 from test t

Results:
| BYTES |      CHSET | DECODED |
|-------|------------|---------|
|  RUZH | iso-8859-1 |     EFG |


text:
Q: How to iterate through a Stream of integers? and at the mean time during the iteration I have to check it for some conditions I am writing a code for post, but I am facing some issues in the validations.
getDocumentIds is a list of integers and what I need is to iterate through the list and check whether that particular id is valid or not.
I have tried with the below code but, when i pass the list of values it is taking only the first value. It is not taking the values after the first one.
    Document document=
    Optional.ofNullable(repositoryService.findById(Document.class,
    memberNoteResource.getDocumentIds().stream()
    .iterator().next())).orElse(null);

    if (document == null) {
        throw new ApiException(ApiErrorCode.DEFAULT_400,
                "Save unsuccessful document id is not part of member note");
    }

The expected result is, I have to check for all the "getDocumentIds" passed and if some id is not present then i have to throw an error

A:
getDocumentIds is a list of integers and what I need is to iterate
  through the list and check whether that particular id is valid or not.

You could use anyMatch to validate if, for any of the id, there is no document present(assuming return value null).
if(memberNoteResource.getDocumentIds()
       .stream()
       .anyMatch((id)-> repositoryService.findById(Document.class,id) == null)) {
    throw new ApiException(ApiErrorCode.DEFAULT_400,
             "Save unsuccessful document id is not part of member note");
}

A: I guess what you wanted is something like
    memberNoteResource.getDocumentIds().stream()
        .map((id)-> {
            repositoryService.findById(Document.class, id);
        }).map(Optional::ofNullable);

Then you can further chain it with .filter() to do some more check.


text:
Q: Magento 2.3.3: I am using valet-linux and struggling to set up multi-store in Magento As the title states I am using valet-linux and everything on single site/store works fine. The part I am struggling with is getting multi-store working with valet-linux.
I have tried adding different drivers in the driver folder for valet but not having much luck?
Anyone experienced with valet-linux?


text:
Q: Argo CD and Kustomize all. I'm using Argo CD v1.6.1 and am trying to deploy an application using Kustomize. Argo CD doesn't seem to recognize my Kustomize manifest files. Looking at the Kustomize documentation on the Argo CD page, it looks like it only supports the following Kustomize options:

*

*namePrefix is a prefix appended to resources for Kustomize apps

*nameSuffix is a suffix appended to resources for Kustomize apps

*images is a list of Kustomize image overrides

*commonLabels is a string map of an additional labels

Are these the only things I'm going to be able to manipulate in my base manifest files using Kustomize? I was hoping I'd be able to use the patchesStrategicMerge option with my overlay files I've got which allow me to manipulate anything in the base.yaml files. It doesn't seem to recognize kind: Kustomization and apiVersion: kustomize.config.k8s.io/v1beta1
Thank you.

A: ArgoCD's main task is to deploy manifests. Kustomize is the right place for any more complex edits. It sounds like you already have an overlays structure in your kustomize application so the missing piece may be about pointing your Argo Application to the correct overlay.
Assuming you have a repo with the following structure:
repo
 |_ app
 |_ kustomize
   |_ base
   |  |_ resource.yml
   |  |_ kustomization.yml
   |_ overlays
      |_ prod
         |_ patch.yml
         |_ kustomization.yml

Then you would want your Argo Application to have:
source:
    repoURL: <REPO_URL>
    targetRevision: <REVISION>
    path: kustomize/overlays/prod

This would mean it is using your overlays kustomization file which should pull in your base kustomzition file and the patches.
The additional fields you have mentioned are like an extra overlay and would not be recommended to do more complex actions like a strategic merge.


text:
Q: Acquiring stream from pool I have a deployed ASP.NET MVC application and sometimes it is throwing the error listed below.

Acquiring stream from pool. xx.x.xx.xxx:xxxxx
  [DEBUG] � Socket 04e15a2f-0331-4d7c-b0a8-c8a0e24dac30 was reset
  [DEBUG] � Socket was reset. 04e15a2f-0331-4d7c-b0a8-c8a0e24dac30
  [DEBUG] � Releasing socket 04e15a2f-0331-4d7c-b0a8-c8a0e24dac30      [DEBUG] � Are we alive? True

I could not identify what is causing the error.


text:
Q: F# - Recursion on list

Input: [x1; x2; ... ; xn]
Output ([x1; x3; ...; xn], [x2; x4; ...; xn], [x3; x5; ...; xn], ....)

What I have so far is:
let rec split = function
| x0 :: x1 :: xs -> (x0::xs) :: split(x1::xs)
| _ -> []

Which yields:
Input: [1;2;3;4;5;6]
Output: [[1; 3; 4; 5; 6]; [2; 4; 5; 6]; [3; 5; 6]; [4; 6]; [5]]

I don't quite see how I can build a tuple of lists recursively.
Any ideas?

A: I don't know why u want to do this, and if its some sort of exercise/homework I don't want to give you the answer BUT I will give you a hint, best start with something that does something sort of in the right direction.
This code takes a list and in a very unnecesary convoluted way, recursive returns a tuple of three of them.
let rec tripleList : List<'a> -> (List<'a> * List<'a> * List<'a>) =
    function
    | []    -> ([],[],[])
    | (x :: xs) ->
        let (tail1,tail2,tail3) = tripleList xs
        (x :: tail1,x :: tail2,x :: tail3)

> tripleList [1..10];;
val it : List<int> * List<int> * List<int> =
  ([1; 2; 3; 4; 5; 6; 7; 8; 9; 10], [1; 2; 3; 4; 5; 6; 7; 8; 9; 10],
   [1; 2; 3; 4; 5; 6; 7; 8; 9; 10])

you don't need to do the whole thing as a single function either, you could create 3 functions, 1 that builds each part of the tuple, and then a fourth function that calls the 3 functions to assemble the answer. That may be a simpler place to start.
So a similar sort of thing would be...
let rec tripleList1 : List<'a> -> List<'a> =
    function
    | []    -> []
    | (x :: xs) ->
        (x :: tripleList1 xs)

let rec tripleList2 : List<'a> -> List<'a> =
    function
    | []    -> []
    | (x :: xs) ->
        (2 * x :: tripleList2 xs)

let rec tripleList3 : List<'a> -> List<'a> =
    function
    | []    -> []
    | (x :: xs) ->
        (3 * x :: tripleList3 xs)

let tripleList : List<int> -> (List<int> * List<int> * List<int>) =
    fun xs ->
        (tripleList1 xs,tripleList2 xs,tripleList3 xs)

I prefer the first approach, but both are perfectively valid, and makes the distinction between the need for recursive functions to create the recusrive data structure List<'a>, whilst the tuple just requires a simple standalone function
so maybe try to write a function that takes.
[1,2,3,4,5,6,7] -> [1,3,5,7]
and then see if you can generalise that, and then assemble the pieces in another function
(note don't be misled by my example, they have the right structure but they fundamentally don't do what you need, you need to filter out values somehow in each part)


text:
Q: Eclipse C++: How do you quickly switch between header and implementation files? How do you switch between header (.h) and implementation files (.cpp) in Eclipse when using the C++/CDT environment with a keyboard shortcut?
In XCode you can quickly switch between headers and implementation with applekey option and up/down arrow keys. I was hoping that eclipse had something similar, but I haven't found it yet.

A: Ctrl + Tab is the default shortcut and here is a list of some of the more useful shortcut keys in Eclipse.

A: Ctrl + Tab.
See in menu Window --> Preferences --> "General" category (far left) --> Keys --> "Toggle Source/Header"

A: Ctrl + Tab is the default shortcut. You can change it in Window->Preferences->General->Keys - Toggle Source/Header

A: F3 to jump between declarations and definitions of specific methods
This is another good one to know in this context:

*

*double click on the method name with the mouse, selecting it

*hit F3 (shortcut for Right Click > Open Declaration)

This takes you from the declaration (.hpp) to definition (.cpp) and vice versa depending on which one you are currently in, which is useful if you want to go to the other file to see a specific method when the file is large.
Tested in Eclipse CDT 2019-09.

A: You can also Ctrl + click on an identifier ( method name of member,... ). That way you seldomly need Ctrl + Tab.


text:
Q: FabricJS: Failed to execute 'drawImage' when using an Image subclass for a project I need adding images of various types to canvas, saving to JSON and loading again. The different types does not have any specific properties, I only need the type to be different.
I have created a new class based on fabric.Image like this:
fabric.Icon = fabric.util.createClass(fabric.Image, {
      type: "icon",
      initialize: function (element, options) {
        this.callSuper("initialize", element, options);
      },
      _render: function (ctx) {
        this.callSuper("_render", ctx);
      },
    });
    fabric.Icon.fromObject = function (object, callback) {
      return fabric.Object._fromObject("Icon", object, callback);
    };

After this I add new object of this new type using a SVG image:
let newImage = new Image();    //HTML Image type, not FabricJS
newImage.onload = () => {
   let icon = new fabric.Icon(newImage);   //my subclass of fabric.Image class
   this.canvas.add(icon);
};
newImage.src = "image.svg";

When I export the canvas into JSON with
let savedJSON = canvas.toJSON()

and load it back with
canvas.loadFromJSON(savedJSON, function () {
    canvas.requestRenderAll();
}

I get the following error

Uncaught TypeError: Failed to execute 'drawImage' on 'CanvasRenderingContext2D': The provided value is not of type '(CSSImageValue or HTMLImageElement or SVGImageElement or HTMLVideoElement or HTMLCanvasElement or ImageBitmap or OffscreenCanvas)'

When I use standard fabric.Image class, everything works correctly. Should I override some other method in my subclass? Or should I differentiate the various Image types in some another way?

A: Well, not really a solution to this problem, but I found the correct way to differentiate between objects which persists within saving and loading - setting the custom property on the Object.prototype by overriding its toObject method like here:
Fabric js extending toObject with custom properties, loses default ones
Problem solved!

A: The fabric Image class has a slightly more complicated restore mechanism, since it wants an image element in the constructor, that is not serializable.
this is how it is implemented in fabricJS:
  /**
   * Creates an instance of fabric.Image from its object representation
   * @static
   * @param {Object} object Object to create an instance from
   * @param {Function} callback Callback to invoke when an image instance is created
   */
  fabric.Image.fromObject = function(_object, callback) {
    var object = fabric.util.object.clone(_object);
    fabric.util.loadImage(object.src, function(img, isError) {
      if (isError) {
        callback && callback(null, true);
        return;
      }
      fabric.Image.prototype._initFilters.call(object, object.filters, function(filters) {
        object.filters = filters || [];
        fabric.Image.prototype._initFilters.call(object, [object.resizeFilter], function(resizeFilters) {
          object.resizeFilter = resizeFilters[0];
          fabric.util.enlivenObjects([object.clipPath], function(enlivedProps) {
            object.clipPath = enlivedProps[0];
            var image = new fabric.Image(img, object);
            callback(image, false);
          });
        });
      });
    }, null, object.crossOrigin);
  };

I'm afraid you have to copy it and swap the fabric.Image with fabric.Icon


text:
Q: Any ideas howto increase speed of selecting elements from a large list of string I have a large list of strings(1 million elements). Just for example:
largeList = ['abc','def','ghi','kkl_year12_month12']

I have to extract the string elements which share the following items:
criteria_1 = ['year12', 'year14'] ##in my real case they are 2 thousands.

criteria_2 = 'month12'  ##in my real case it is just one.

I did as follows:
answer = [x for x in largeList if any(y in x for y in criteria_1) and 'month12' in x]

But my method is extremely slow.
Any ideas to increase the speed?

A: Depending on how many elements will be filtered by criteria_2 filtering you largeList first might improve speed.
>>> def find1(largelist1,crit1,crit2):
>>>    return  [x for x in largeList if any(y in x for y in crit1) and crit2 in x]

>>> def find2(largelist1,crit1,crit2):
>>>         filt_l = (x for x in largelist1 if crit2 in x)
>>>         return [x for x in filt_l if any(y in x for y in crit1)]

>>> %timeit find1(largeList,criteria_1,criteria_2)
100000 loops, best of 3: 2.18 µs per loop
>>> %timeit find2(largeList,criteria_1,criteria_2)
1000000 loops, best of 3: 1.39 µs per loop

additionally it might help to use numpys arrays.

A: The other answers suggest to check first for the second criteria (because it is the most simple and therefore quickest check). This can also be done by changing the order of the criteria around the and keyword:
answer = [x for x in largeList if 'month12' in x and any(y in x for y in criteria_1)]

if 'month12 in x' yields false the second criteria any(y in x for y in criteria_1) will not be evaluated.


text:
Q: What is the "(line: String) => { }" structure known as in Scala? And how does it work? I am beginning to learn Scala, and I've run across this piece of code from https://github.com/sryza/aas/blob/master/ch05-kmeans/src/main/scala/com/cloudera/datascience/kmeans/RunKMeans.scala
def buildCategoricalAndLabelFunction(rawData: RDD[String]): (String => (String,Vector)) = {
   ...
   (line: String) => {
       val buffer = line.split(',').toBuffer
       ...
       val label = buffer.remove(buffer.length - 1)
       val vector = buffer.map(_.toDouble)
       ...
       (label, Vectors.dense(vector.toArray))
   }
}

What I don't understand is what (line: String) => {...} is doing. Where is line being initialized? It seems to me like the program is taking in line as input from the rawData argument, but I don't understand how that is happening.
If someone could explain what this Scala structure is called - or even better, how it works - I would really appreciate it!

A: It defines a function, using the anonymous function syntax, this is similar to arrow functions in JavaScript and other languages.
This syntax provides a way to create a function that doesn't have a name. These can be returned by other functions, assigned to variables (effectively naming them), passed to functions as parameters etc ...


text:
Q: Having trouble a query and specifically with joins The code below is completely wrong and does not work at all. Im basically trying to look through my tables and compile a list of DeptName and the total student number for a department where a department has more than 40 students.
Im confused about joins in general and if someone could explain and show where im going wrong. im sure there is also other problems so any help with them would help
So basically one department is connected to one module, and a student is enrolled in a module. A student cannot take a module outside of their department. So each student should have one module that connects to one department
All of the ID fields in other tables are foreign keys as you can guess and changing the tables is not what I want to do here I just want to do this query as this stands
Relevant tables columns
Table Department DeptID, DeptName, Faculty, Address
Table Modules ModuleID, ModuleName, DeptID, Programme
Table Students StudentID,StudentName,DoB,Address,StudyType,`
Table Enrolments EID,StudentID,ModuleID,Semester,Year
SELECT Department.DeptName, COUNT(Student.StudentID) AS 'No of Students'  FROM Department LEFT JOIN Module ON Department.DeptID= Module.DeptID LEFT JOIN Enrolment ON Module.ModuleID=  Enrolment.StudentID LEFT JOIN Student.StudentID
GROUP BY(Department.DeptID)
HAVING COUNT(Student.StudentID)>=40

I have not included every table here as there are quite a lot.
But unless i've got this completely wrong you don't need to access a ModuleID in a staff table for the module they teach or something not relevant to this at all. As no student or Dept details are in there.
If that is the case i will fix it very quickly.

A: SELECT Department.DeptName, COUNT(Student.StudentID) AS 'No of Students'
FROM Department
    LEFT JOIN Module
        ON Department.DeptID= Module.DeptID
    LEFT JOIN Enrolment
-- problem #1:
        ON Module.ModuleID=  Enrolment.StudentID
-- problem #2:
    LEFT JOIN Student.StudentID
-- problem #3:
GROUP BY(Department.DeptID)
HAVING COUNT(Student.StudentID)>=40

*

*You're joining these two tables using the wrong field. Generally when the modeling is done correctly, you should use USING instead of ON for joins

*The right side of any JOIN operator has to be a table, not a column.

*You have to group by every column in the select clause that is not part of an aggregate function like COUNT. I recommend that you select the DeptID instead of the name, then use the result of this query to look up the name in a subsequent select.

Note : Following code is untested.
WITH bigDepts AS (
  SELECT DeptId, COUNT(StudentID) AS StudentCount
  FROM Department
    JOIN Module
        USING ( DeptID )
    JOIN Enrolment
        USING ( ModuleID )
    JOIN Student
        USING ( StudentID )
  GROUP BY DeptID
  HAVING COUNT(StudentID)>=40
)
SELECT DeptID, DeptName, StudentCount
FROM Department
    JOIN bigDepts
        USING ( DeptID )

A: Instead of left join you need to use inner join since you need to select related rows only from those three tables.
Groupy by and having clause seems fine. Since you need departments with more than 40 students instead of >= please use COUNT(e.StudentID)>40
SELECT d.DeptName, COUNT(e.StudentID) AS 'No of Students'  FROM Department d INNER JOIN Module m ON d.DeptID= m.DeptID inner JOIN Enrolment e ON m.ModuleID=  e.StudentID LEFT JOIN Student.StudentID
GROUP BY(d.DeptName)
HAVING COUNT(e.StudentID)>40

A: So your join clause was a bit iffy to students as you wrote it, and presumably these should all be inner joins.
I've reformatted your query using aliases to make it easier to read.
Since you're counting the number of rows per DeptName you can simply do count(*), likewise in your having you are after counts greater than 40 only. Without seeing your schemas and data it's not possible to know if you might have duplicate Students, if that's the case and you want distinct students count can amend to count(distinct s.studentId)
select d.DeptName, Count(*) as 'No of Students'
from Department d
join Module m on m.DeptId=d.DeptId
join Enrolment e on e.StudentId=m.ModuleId
join Students s on s.StudentId=e.studentId
group by(d.DeptName)
having Count(*)>40

Also, looking at your join conditions, is the Enrolement table relevant?
select d.DeptName, Count(*) as 'No of Students'
from Department d
join Module m on m.DeptId=d.DeptId
join Students s on s.StudentId=m.moduleId
group by(d.DeptName)
having Count(*)>40


text:
Q: C# - Draw grid lines on multiline textbox I'm looking to know how I can draw a grid in a multine textbox, where in each square of the grid there will be a letter, something like this:

But, for a multiline textbox, I want to use some fixed width font, like, CONSOLAS, so, this is will help a lot...
I tried to change this code ( How to customize Winforms textbox text characters separated? ) to work on textbox, but, didn't work.

A: I think that you want to show the operator some fill-in box: A box where he should type something that fits some format, like a postcode, or telephone number, or the house number in an address, or car registration sign
For this, consider to use a MaskedTextBox control.

With the MaskedTextBox you can easily define the format of some input string: how many characters, where do we want a Letter, and where a Digit? Where should brackets occur.
A MaskedTextBox control is just like an ordinary Textbox, only with a specific format. The Mask:

*

*The "#" character in the mask is used for digit only

*The "&" character accepts letter only

*The "!" character accepts letter or digit

*You can use any mask symbol, letter and digit other than # & and !

See the image what happens with certain formats.
The mask shows a predefined format what to expect: where do we want brackets, where do we want spaces, numbers, etc. The mask prevents typing incorrect characters.
The control notifies you when the operator has typed text that matches a complete mask.


text:
Q: Dealing with commas and quote in a CSV file I have searched the internet about the comma issues about csv document.But my trouble is about dealing with the value containing not only comma but also quote.
like String value = "FName,\"FName2,FName3";
I want to display the string FName,"FName2,FName3  in the csv document.Though i tried a couple of approaches,but failed.
When the string contains comma,I can use double quote to surround it like code below.
outBuff.append("\\").append(cellData).append("\\").append(",");

But when the string contains "" and ,
How can i deal with this issue?
I can only use the pulest java,and can not use the third part library.
Thanks.

A: Consider using os specialized CSV parser, like one from Apache Commons
It will handle most of corner cases for you

A: StringBuffer sbStudentData = new StringBuffer();

sbStudentData.append(",\"").append(LastName).append(",\"").append(FirstName)

it will work fine like Last name,First name.

A: try enclosing your double quote with two double qoutes:
 String value = "FName,\"\"\"FName2,FName3";


text:
Q: Symbolic link in svn working copy for a switched directory I work on several (2-20) projects of non-shared-ancestry in a single repo, that share common resources of GBs of binary data stored in the repository at only a single place. These projects utilize svn switch to map their appropriate folder to the single svn URL where they share the binary data.
I want to do the same in my working copies when more than one is checked out, thus avoiding redownloading the same GBs of binary data I already have.
(Note: Another bad news is that the projects also utilize an svn 1.7 executable in order to modify themselves.)
what I did
What I've done is checking out project A, do the switch -es; then check out project B, but instead of regular switch, do svn switch --set-depth=empty --ignore-ancestry http://foobar, so this working copy of project B knows where it should point to. Then, I did mv foobar old_foobar and mklink /D foobar ../project_A/foobar. (1)
the problem now
The problem is now that if I do svn status in the wc with the symbolic link, it lists all the files in "foobar " as non-versioned (as ? status).
I also use TortoiseSVN and it shows the icon overlay as yellow triangular "!" (meaning perhaps confilcted?), but I have no actual conflict (nor tree conflict) in svn status and if I do svn up in "foobar", it says that it is up-to-date.
constraints
The binary file containers do not change very often and even if they do, the changes are usually backward-compatible. Thus it is not a problem (for me, at least) that the working copy has a wrong idea about the file version in them.
I should not change the project or repo structure as I am not allowed to do that "officially".
I use svn 1.7 and since the projects actually utilize a self-contained svn executable binary for work on themselves, I would like to stick to that if possible.
question
Is there a way to utilize symbolic links (or anything else) in order to avoid duplicating the same GBs of data on my hard drive? (Also avoiding downloading it if possible.)

(1): I'm on Windows; for easyness, let's say the that in my file system, folders "project_B" and "project_A" are neighbours ie. share a single common ancestor and that folder foobar is top level in both projects.

A: We have a situation where multiple projects may be nested inside each other.
The solution we used might work well for you;

*

*For a project, check it out of the repository as normal.

*Create a svn:ignore entry for the path that will contain the data, and make sure that path isn't tracked.

*Check out the data to that path.

*For additional projects, do step 1 and 2, but create a symlink instead.

Now all your projects will just ignore those extra files, but you can still manage the data through svn.
Yes, it means you'll need to remember to svn update && svn update data/ to be sure your project is completely up to date, but it's not much of a hassle.


text:
Q: Email validation using JQuery Ajax I've been having a hard time trying to validate an email with ajax
using PHP and Javascript. What I want to do, is to check if the email
already exists in the database, if so, display a message and then go
back to the form, otherwise display a success message and close the
form. The problem is that if the email exists it is displaying the
"error message" and then displays the success message. I've checked
similar questions and tried the code in them but none of them applied
correctly to my requirements. Thank you.
Here's what I've got:
// JavaScript Document
$('#btnSubmit').click(function(){
    if(  validateForm() ){
        // code to submit all the info, display the success message and close the form
    }
    else return false;
});

// I created a function to validate all the fields in the form
function validateForm() {
    var firstName = $('#txtFirstName').val();
    var lastName = $('#txtLastName').val();
    var email = $('#txtMail').val();

    // to validate firstName and lastName I do it like this:
    if(!firstName || firstName.length === 0) {
        message = "All fields are mandatory\\nFirst Name is required";
        messageDialog("Warning", message, "warning", 2);
        return false;
    }
    if( !firstName.match(letters) ) {
        message = "Invalid name";
        messageDialog("Warning", message, "warning", 2);
        return false;
    }
    // So far, no problem at all. But when I tried to validate email:
    else {
        // use ajax to check if a user has been previously registered
        // using this email
        $.ajax({
            url:"check_user.php",   // url that will use
            data:{                  // data that will be sent
                email:email
            },
            type:"POST",            // type of submision
            dataType:"text",        // what type of data we'll get back
            success:function(data)
            {
                // if check_user returns a number different than 0
                // means that there's already a user registered with that email
                if(data > 0 ) {
                    message = "This email is registered already!";
                    messageDialog("Error", message, "error", 2);
                    return false;
                 }
                 else { return true;}
            }
        });

    }

    // if everything is right then return true so the submit function continue its execution
    return true;
}

A: You perform an ajax request, which by default is asynchronous, which means it doesn't wait for the response of your request before doing the rest of your function.
So in your case, once the request is made, it will return true as stated as the end of your function. Then, when the response of your ajax request comes back, it will trigger your success function, which will display the error message.
You can do something like that, using the async parameter of the $.ajax function to make sure that it will wait for the response of your request before going any further.
function validateForm() {
    var firstName = $('#txtFirstName').val();
    var lastName = $('#txtLastName').val();
    var email = $('#txtMail').val();

    // to validate firstName and lastName I do it like this:
    if(!firstName || firstName.length === 0) {
        message = "All fields are mandatory\\nFirst Name is required";
        messageDialog("Warning", message, "warning", 2);
        return false;
    }
    if( !firstName.match(letters) ) {
        message = "Invalid name";
        messageDialog("Warning", message, "warning", 2);
        return false;
    }
    // So far, no problem at all. But when I tried to validate email:
    else {
        // use ajax to check if a user has been previously registered
        // using this email
        var valid = false;
        $.ajax({
            url:"check_user.php",
            async: false,
            data:{                  // data that will be sent
                email:email
            },
            type:"POST",            // type of submision
            dataType:"text",        // what type of data we'll get back
            success:function(data)
            {
                // if check_user returns a number different than 0
                // means that there's already a user registered with that email
                if(data == 0 ) {
                    valid = true;
                }
            }
        });
        if(!valid) {
             message = "This email is registered already!";
             messageDialog("Error", message, "error", 2);
             return false;
        } else { return true; }
    }
    }

A: I don't see any success message, but I assume that your validate() function returns true when the e-mail address already exists.
This is caused by the fact that your ajax call is asynchronous and is not yet finished when your validate() function finishes. Apart from that what your return from your anonymous success function, is not what is returned from your ajax call; you don't even use the return value from your ajax call.
You can either make your ajax call synchronous and use a variable to set the return value from it or you can return the return value of your ajax call as well and continue processing when the ajax call is finished.

A: In Ajax call the success function is async that means your function will return always true if it arrive to check your email.
to correct this, you have to remove return true from your last else and inside success function call a function that will close your form like this :
// JavaScript Document
$('#btnSubmit').click(function(){
    if(  validateForm() ){
        // code to submit all the info, display the success message and close the form
    }
    else return false;
});

// I created a function to validate all the fields in the form
function validateForm() {
    var firstName = $('#txtFirstName').val();
    var lastName = $('#txtLastName').val();
    var email = $('#txtMail').val();

    // to validate firstName and lastName I do it like this:
    if(!firstName || firstName.length === 0) {
        message = "All fields are mandatory\\nFirst Name is required";
        messageDialog("Warning", message, "warning", 2);
        return false;
    }
    if( !firstName.match(letters) ) {
        message = "Invalid name";
        messageDialog("Warning", message, "warning", 2);
        return false;
    }
    // So far, no problem at all. But when I tried to validate email:
    else {
        // use ajax to check if a user has been previously registered
        // using this email
        $.ajax({
            url:"check_user.php",   // url that will use
            data:{                  // data that will be sent
                email:email
            },
            type:"POST",            // type of submision
            dataType:"text",        // what type of data we'll get back
            success:function(data)
            {
                // if check_user returns a number different than 0
                // means that there's already a user registered with that email
                if(data > 0 ) {
                    message = "This email is registered already!";
                    messageDialog("Error", message, "error", 2);
                    return false;

                 } else {
                   // code to submit all the info, display the success message and close the form
                 yourfunctiontocloseyourform()
                 }
            }
        });
        return false;

    }

}


text:
Q: RSA, SSLStream - Key Exchange i'm using SSLStream to communicate a client and a server using OpenSSL certificates.
And the client that i will use is a machine that has it's own software, that needs to use RSA cryptography.
I made a server and a client, just to test, using my computer as client, and other computer as a server, and i made a simple key exchange, just to test the sslstream and de rsa cryptograhy between these machines.

Both machines send the public key like this:
byte[] modulus = pubkey.Modulus;
sslStream.Write(modulus, 0, modulus.Length);
sslStream.Flush();

And both machines receive the key and create like this:
 byte[] exponent = {1, 0, 1};
 byte[] modulus = new byte[256];
 sslStream.Read(modulus, 0, modulus.Length);

 clientPublicKey.D = null;
 clientPublicKey.DP = null;
 clientPublicKey.DQ = null;
 clientPublicKey.Exponent = exponent;
 clientPublicKey.InverseQ = null;
 clientPublicKey.Modulus = modulus;
 clientPublicKey.P = null;
 clientPublicKey.Q = null;

But, testing this with the original client that i will use, the key exchange is not the same way.

Is there another way exchange keys? Because i'm sure that the original machine use another way to exchange theses keys with my server.


text:
Q: What are the differences between http and socket inside of ini file in uWSGI? I'm learning nginx and uwsgi to deploy my Django web app.
While learning them, I got confused with "socket" and "http".
I think I should write .ini like the following.
when I use only uwsgi
...
http=127.0.0.1:8001
...
when I use uwsgi and nginx and I want to make clients connect to my server through nginx
...
socket=127.0.0.1:8001
...
When I only use uwsgi to run my server, I guess I should use "http" instead of "socket"
in .ini file
http=127.0.0.1:8001
because if i use "socket" it emits errors when clients connect to my server, like this.
invalid request block size: 21573 (max 4096)...skip
However, when I use nginx with uwsgi, I should use socket instead of http.
If I use http, I guess the server emitted timeout error.
My codes
this is my codes that works
in /etc/nginx/sites-available/blog.conf
upstream blog{
    server 127.0.0.1:8001;
}

server {
    listen 80;
    server_name 127.0.0.1;
    charset     utf-8;

    client_max_body_size 75M;   # adjust to taste

    location /static {
        alias /django_static/djProject;
    }

    location / {
        include /etc/nginx/uwsgi_params;
        uwsgi_pass  blog;
    }
}

in project directory, app.ini
[uwsgi]
plugins=python3
chdir={myProject location}
module=djProject.wsgi:application
# Settings module, relative to the chdir path
env='DJANGO_SETTINGS_MODULE=djProject.settings'
# Python virtual env path
home=/home/su/uwsgi/uwsgi-tutorial
# File used for uwsgi to send signals and start/stop

socket=127.0.0.1:8001
#http=127.0.0.1:8001
master=True
processes=4
harakiri=20
max-requests=5
vacuum=True
enable-threads=true

static-map = /static=/django_static/djProject

In conclusion
How different are they to use http and socket in .ini file and when should I use them respectively?

A: expanding on what Ranjeet said, you need to make sure everything is communicating using compatible protocols.  Nginx's uwsgi_pass option tells it to use a "special" uwsgi protocol.  while uWSGI's socket option is documented as using its "default protocol" which seems to actually mean it uses the same "special" uwsgi protocol, but you could use the uwsgi-socket option to be more explicit.
looking through uwsgi's the code in uwsgi.c and socket.c it's pretty obvious that uwsgi-socket is just an alias for socket. it'd be nice if the docs also said that!
if you configure uWSGI with the http option you're telling it to use the http protocol, which won't do anything useful because NGINX is trying to talk to it using the above special uwsgi protocol.  note that you could also configure NGINX to talk to uWSGI using HTTP, but this would lose information as you're basically then proxying and NGINX would have to rewrite headers to say it was proxying and would basically end up doing more work
see also https://uwsgi-docs.readthedocs.io/en/latest/tutorials/Django_and_nginx.html which has got lots of stuff about getting things taking to each other, you can just ignore the Django bits!

A: Don't confuse with these two different items (uwsgi and http).
As you already mentioned, you are deploying python application with uwsgi and nginx server.
Before go further, look on the client request to server (nginx)
Browser <-> nginx <-> socket <-> uwsgi <-> python application.
Nginx is responsible for to serve html, javascript and css files.
Nginx can't communicate with python application directly. Because python application standard way to publish applications via web server is WSGI. That's why we need a uwsgi server. That basically communicate with python application and handle request and response from/to web server nginx.
And Web server/ HTTP server communicate with uwsgi server via socket connection.

However, when I use nginx with uwsgi, I should use socket instead of http. If I use http, I guess the server emitted timeout error.

Yes your right.


text:
Q: WooCommerce custom out of stock text + specific product id Here is what I am trying to do

*

*Detect if a specific product is in stock

*If yes, edit the custom stock message

*display a custom message above the A2C button (where stock quantity notification is)

Problem: ALL products are at the moment being edited. I am not successfully applying it do specific product IDs.
This is what I tried so far
add_filter( 'woocommerce_get_availability', 'wcs_custom_get_availability', 1, 2);
function wcs_custom_get_availability( $availability, $_product ) {
    global $product;

    // custom
    if ( $_product->is_in_stock() && $product_id = '6498' ) {
        $availability['availability'] = sprintf( __('✔ Available but low in stock | 30-day No Questions Asked Money-Back Guarantee Applies', 'woocommerce'), $product->get_stock_quantity());
    }

    // Out of stock
    if ( ! $_product->is_in_stock() ) {
        $availability['availability'] = __('Sorry, All sold out!', 'woocommerce');
    }

    return $availability;

}
Thanks!

A: Try this code
add_filter( 'woocommerce_get_availability', 'wcs_custom_get_availability', 10, 2);
function wcs_custom_get_availability( $availability, $_product ) {
    // custom
    if ( $_product->is_in_stock() && $_product->get_id() == '6498' ) {
        $availability['availability'] = sprintf( __('✔ Available but low in stock | 30-day No Questions Asked Money-Back Guarantee Applies', 'woocommerce'), $_product->get_stock_quantity());
    }

    // Out of stock
    if ( ! $_product->is_in_stock() ) {
        $availability['availability'] = __('Sorry, All sold out!', 'woocommerce');
    }

    return $availability;
}


text:
Q: Create a new button to change the state of new student I am having a problem creating a new button to change the state of a new student.
First I created an XML file:
...
<record model="ir.ui.view" id="student_form">
<field name="name">sim.student.form</field>
<field name="model">sim.student</field>
<field name="type">form</field>
<field name="arch" type="xml">
<form string="Student">
<field name="name"/>
<field name="student_name"/>
<field name="father_name"/>
<field name="gender"/>
<field name="contact_no"/>
<button name="setuju" states="draft" string="Approve" type="object"/>
</form>
</field>
</record>
...

Next I created a Python file:
from osv import fields, osv
import time
import netsvc
import pooler

class sim_student(osv.osv):
    _name = "sim.student"
    _description = "Data Siswa"

    def setuju(self, cr, uid, ids, context=None):
        workflow = netsvc.LocalService('workflow')

        for name in ids:
            workflow.trg_create(uid, self._name, name, cr)

        return self.write(cr, uid, ids, {'state': 'confirmed'}, context=context)

    _columns = {
        'name': fields.char('Registration Number',size=256,required=True),
        'student_name': fields.char('Student Name',size=256,required=True),
        'father_name': fields.char('Father Name',size=256),
        'gender':fields.selection([('male','Male'),('female','Female')],'Gender'),
        'contact_no':fields.char('Contact Number',size=256),
        'state': fields.selection([('new', 'New'), \
                                    ('confirmed', 'Received'), \
                                    ('cancelled', 'Cancelled')], \
                                'Status', readonly=True, select=True)
    }

sim_student()

Then I createe an init.py file :
import sim

Finally I created an openerp.py file :
{
'name': 'Student Information Management',
'version': '0.1',
'category': 'Tools',
'description': """Data Siswa.""",
'author': 'Wasis Lukito',
'summary': 'Test, Test, dan Test',
'website': 'http://wasis.wordpress.com/',
'depends': ['base'],
#'init_xml': [],
#'update_xml': ['sim_view.xml'],
#'demo_xml': [],
#'installable': True,
'data': ['sim_view.xml',],
'css':['static/src/css/lunch.css'],
'demo': [],
'installable': True,
'application' : True,
'certificate' : '001292377792581874189',
'images': [],
}

When I executed the code, however, it produced this error message:
No handler found.

And this is the error from the console:
C:\Program Files\OpenERP 7.0alpha-20121206-000102\Server\server\.\pytz\tzinfo.py
:5: DeprecationWarning: the sets module is deprecated
ERROR: couldn't create the logfile directory. Logging to the standard output.
2013-01-15 15:21:39,977 2136 ←[1;32m←[1;49mINFO←[0m ? openerp: OpenERP version 7
.0alpha-20121206-000102
2013-01-15 15:21:39,994 2136 ←[1;32m←[1;49mINFO←[0m ? openerp: addons paths: C:\
Program Files\OpenERP 7.0alpha-20121206-000102\Server\server\openerp\addons
2013-01-15 15:21:40,023 2136 ←[1;32m←[1;49mINFO←[0m ? openerp: database hostname
: localhost
2013-01-15 15:21:40,039 2136 ←[1;32m←[1;49mINFO←[0m ? openerp: database port: 54
32
2013-01-15 15:21:40,055 2136 ←[1;32m←[1;49mINFO←[0m ? openerp: database user: op
enpg
ERROR: couldn't create the logfile directory. Logging to the standard output.
2013-01-15 15:21:40,799 2136 ←[1;33m←[1;49mWARNING←[0m ? openerp.addons.google_d
ocs.google_docs: Please install latest gdata-python-client from http://code.goog
le.com/p/gdata-python-client/downloads/list
2013-01-15 15:21:41,548 2136 ←[1;37m←[1;41mCRITICAL←[0m ? openerp.modules.module
: Couldn't load module web
2013-01-15 15:21:41,568 2136 ←[1;37m←[1;41mCRITICAL←[0m ? openerp.modules.module
: unexpected indent (sim.py, line 10)
2013-01-15 15:21:41,585 2136 ←[1;31m←[1;49mERROR←[0m ? openerp.service: Failed t
o load server-wide module `web`.
The `web` module is provided by the addons found in the `openerp-web` project.
Maybe you forgot to add those addons in your addons_path configuration.
Traceback (most recent call last):
  File "C:\Program Files\OpenERP 7.0alpha-20121206-000102\Server\server\.\opener
p\service\__init__.py", line 53, in load_server_wide_modules
  File "C:\Program Files\OpenERP 7.0alpha-20121206-000102\Server\server\.\opener
p\modules\module.py", line 414, in load_openerp_module
  File "C:\Program Files\OpenERP 7.0alpha-20121206-000102\Server\server\openerp\
addons\web\http.py", line 593, in wsgi_postload
  File "C:\Program Files\OpenERP 7.0alpha-20121206-000102\Server\server\openerp\
addons\web\http.py", line 482, in __init__
  File "C:\Program Files\OpenERP 7.0alpha-20121206-000102\Server\server\openerp\
addons\web\http.py", line 549, in _load_addons
  File "C:\Program Files\OpenERP 7.0alpha-20121206-000102\Server\server\.\opener
p\modules\module.py", line 133, in load_module
  File "C:\Program Files\OpenERP 7.0alpha-20121206-000102\Server\server\openerp\
addons\sim\__init__.py", line 1, in <module>
  File "C:\Program Files\OpenERP 7.0alpha-20121206-000102\Server\server\openerp\
addons\sim\sim.py", line 10
     def setuju(self, cr, uid, ids, context=None):
    ^
 IndentationError: unexpected indent
2013-01-15 15:21:41,849 2136 ←[1;32m←[1;49mINFO←[0m ? openerp.service.netrpc_ser
ver: starting NET-RPC service on 0.0.0.0:8070
2013-01-15 15:21:41,877 2136 ←[1;32m←[1;49mINFO←[0m ? openerp.netsvc: Starting 1
 services
2013-01-15 15:21:41,897 2136 ←[1;32m←[1;49mINFO←[0m ? openerp: OpenERP server is
 running, waiting for connections...
2013-01-15 15:21:41,913 2136 ←[1;32m←[1;49mINFO←[0m ? openerp.service.wsgi_serve
r: HTTP service (werkzeug) running on 0.0.0.0:8069

The error seems to come from "def setuju(...". What is wrong with my script?

A: Please remove the key 'certificate' from the openerp file If your module doens't have a certificate. Also please remove the workflow from the setuju() function. I dont see a workflow defined for your class.
From the log the error is because indentation error. Please check you have correct number of spaces before def setuju()

A: To develop on OpenERP, even if have experience with it, you will frequently find situations like this. It's a must to learn know where your log files are check them for errors.
This will depend on how you installed the server, but according to the documentation it should be on C:\Program Files\OpenERP X.X\Server\openerp-server.log.. If not, look it up in the server configuration file .
If you are serious about OpenERP development, I would advise you to:

*

*Stop the server services and start it manually in a console terminal instead. Not only it gives you instant information on warnings and errors, but it will also display the results from python print statements and let you go into (Pdb) debug mode.

*Install your OpenERP server in an Ubuntu Server VM. It may have a learning curve to use Linux, but there's a lot of help available, and in the long run you will find a lot easier to get help and solve troubles in that platform.


text:
Q: Dagger field injection not working with simple java classes I am trying field injection with dagger although constructor injection is working absolutely fine but i don't know what is wrong with field injection. May be I am doing wrong. I am adding the code snippets. I am getting null pointer exception on engine.start() because the engine dependency is not fed. It is similar to A->B->C dependencies where A->B is fed but B->C is not. Its been long I am unable to resolve.
package com.raghav.java.car;

import javax.inject.Inject;

public class App
{
    @Inject
    Car car;

    App() {
        DaggerCarComponent.create().inject(this);
    }

    public static void main( String[] args )
    {
        App app = new App();
        app.perform();
    }

    private void perform() {
        car.run();

    }
}

public interface Engine {
    void start();
}

class FordEngine implements Engine {

    public void start() {
        System.out.println("Engine started -- Vroom Vroom");
    }
}

public interface Car {
        void run();
}

class MarutiCar implements Car {

    @Inject
    Engine engine;

    public void run() {
        engine.start();
        System.out.println("WOW!! Maruti Running ");
    }

}

@Singleton
@Component(modules = {CarModule.class})
public interface CarComponent {

    void inject(App app);

}

@Module
class CarModule {

    @Singleton
    @Provides
    public Car provideCar() {
        return new MarutiCar();
    }

    @Singleton
    @Provides
    public Engine provideEngine() {
        return new FordEngine();
    }
}

A: if you want to do nested injection you need to use constructor injection otherwise that wont happen automatically because when you provide a dependency out of Dagger style (through constructor injection or argument injection in module) dagger has no idea about that. change your classes like below:
change your MarutiCar like this:
class MarutiCar implements Car {

Engine engine;

@Inject
public MarutiCar(Engine engine)
{
    this.engine = engine;
}

public void run() {
    engine.start();
    System.out.println("WOW!! Maruti Running ");
    }

}

and your FordEngine class like this:
class FordEngine implements Engine {

@inject
public FordEngine()
{
}

public void start() {
    System.out.println("Engine started -- Vroom Vroom");
    }
}

then change your CarModule like below:
@Module
class CarModule {

@Singleton
@Provides
public Car provideCar(MarutiCar marutiCar) {
    return marutiCar;
    }

@Singleton
@Provides
public Engine provideEngine(FordEngine fordEngine) {
    return fordEngine;
    }
}

UPDATE: DAGGER WONT INJECT FIELDS OF A CLASS THAT IS NOT CREATED BY ITSELF.
you are creating the MarutiCar instance by your self how you expect dagger to know what it needs ? you can start a new chain of dagger creation in that class to achieve this which is a weird thing to do.
you need to tell dagger what you need by showing dependencies through constructor or module method argument so that dagger instantiate them for you to know what they need. dagger doesnt provide your nested dependencies injected fields because it hasnt created them so it has no idea about their dependencies, unless you start another chain of dagger creation like what you did in your App class.
there is another way if you dont want to use constructor injection which i only show this for you Car and MarutiCar class:
@Module
class CarModule {

@Singleton
@Provides
public Car provideCar(Engine engine) {
    MarutiCar marutiCar = new MarutiCar(engine);
    }

@Singleton
@Provides
public Engine provideEngine(FordEngine fordEngine) {
    return fordEngine;
    }
}

and the MarutiCar class would be like this (no need for @inject)
class MarutiCar implements Car {

Engine engine;

public MarutiCar(Engine engine)
{
    this.engine = engine;
}

public void run() {
    engine.start();
    System.out.println("WOW!! Maruti Running ");
    }

}


text:
Q: Cased edges in gap-planar graph (intersections, redraw path) For illustrating my thesis on k-gap-planar graphs I'd like to find an elegant and parametrizable way to produce drawings of such graphs with cased edges (to make clear to which of the edges the intersection is charged).
Reference article with similar drawings
What I've accomplished so far is rather cluttered and I hope it can be simplified.
I've used the tikzpackage "intersections" to place a white disc on top of each crossing and repeat the edge that should pass the intersection without beeing gapped. "intersections" allows to name the involved paths, but I couldn't find out how to let the named paths be drawn again without defining them anew (see code and image below).
The combination of calculation the crossings by "intersections" and putting the edges on different layers via "pgfonlayer"-environment to control the drawing sequence did not work. Maybe this package is not compatible with edges on different layers.
I appreciate any relevant suggestions :)

\documentclass{standalone}
\usepackage{tikz}
\usetikzlibrary{intersections}
\begin{document}

\tikzstyle{vertex}=[circle, draw=black, fill=black, radius = 1mm,
scale = 0.8,anchor=center]

\tikzstyle{crossing}=[circle, radius=0.5pt, fill= white]

\tikzstyle{cased}=[draw=white,line width = 12pt,
double=black,very thick, distance = 2pt]

\begin{tikzpicture}[every node/.style={vertex}]
    \pgfmathtruncatemacro{\n}{4}
    \foreach \pos
    [evaluate=\pos as \angle using (360/\n/2)+\pos*360/\n)]
    in {2,...,\n}
    {%inner  vertices
        \path node (i\pos) at (\angle:2) {};%
    };
    \foreach \pos
    [evaluate=\pos as \angle using (360/\n/2)+\pos*360/\n)]
    in {1,2,...,\n}
    {%outer vertices
        \node (o\pos) at (\angle:6) {};
    };

    %bent outer edges
    \pgfmathtruncatemacro{\distA}{10}
    \path[name path=e_o1_o3] (o1.center) .. controls
    +(30:\distA) and +(60:\distA) .. (o3.center);
    \draw[name path=e_o2_o4] (o2.center) .. controls
    +(120:\distA) and +(150:\distA) .. (o4.center);

    %straight edges between inner and outer
    %o4.center
    \draw[name path=e_o4_i4]  (o4.center) -- (i4.center);
    %o2.center
    \draw[name path=e_o2_i2]  (o2.center) -- (i2.center);
    %o3.center
    \draw[name path=e_o3_i3]  (o3.center) -- (i3.center);

    %bent edges between inner and outer
    %offset=1
    \pgfmathtruncatemacro{\distI}{2}
    %o1.center
    \draw[name path=e_o1_i4]  (o1.center) .. controls
    +(-20:\distI) and +(140:\distI) .. (i4.center);
    \path[name path=e_o1_i2]  (o1.center) .. controls
    +(-70:\distI) and +(130:\distI) .. (i2.center);
    %o4.center
    \draw[name path=e_o4_i3]  (o4.center) .. controls
    +(-110:\distI) and +(50:\distI) .. (i3.center);
    %o2.center
    \path[name path=e_o2_i3]  (o2.center) .. controls
    +(20:\distI) and +(-140:\distI) .. (i3.center);
    %o3.center
    \draw[name path=e_o3_i2]  (o3.center) .. controls
    +(160:\distI) and +(-40:\distI) .. (i2.center);
    \path[name path=e_o3_i4]  (o3.center) .. controls
    +(110:\distI) and +(-50:\distI) .. (i4.center);

    %bent edges between inner and outer
    %offset=2 (opposite)
    \pgfmathsetmacro{\distG}{5.5}
    %o1.center
    \path[name path=e_o1_i3]  (o1.center) .. controls
    +(-10:\distG) and +(70:\distG) .. (i3.center);
    %o4.center
    \path[name path=e_o4_i2]  (o4.center) .. controls
    +(-100:\distG) and +(-20:\distG) .. (i2.center);
    %o2.center
    \draw[name path=e_o2_i4]  (o2.center) .. controls
    +(80:\distG) and +(160:\distG) .. (i4.center);

    \foreach \pos
    [remember=\pos as \last (initially \n)]
    in {1,2,...,\n}
    {%straight outer edges
        \draw[name path=e_o\pos_o\last] (o\pos.center) --
        (o\last.center);
    };
    \foreach \pos
    [remember=\pos as \last (initially \n)]
    in {2,...,\n}
    {%straight inner edges
        \draw (i\pos.center) -- (i\last.center);
    };

    %crossings
    \begin{scope}[every node/.style={crossing}]
        %crossing e_o1_o3 and e_o2_o4
        \path [draw,name intersections={of={e_o1_o3 and e_o2_o4}}]
        (intersection-1) node (a) {} ;
        %repeat edge drawing
        \draw[name path=e_o1_o3] (o1.center) .. controls
        +(30:\distA) and +(60:\distA) .. (o3.center);
        %crossing e_o1_i2 and e_o2_i4
        \path [draw,name intersections={of={e_o1_i2 and e_o2_i4}}]
        (intersection-1) node (b) {} ;
        %repeat edge drawing
        \draw[name path=e_o1_i2]  (o1.center) .. controls
        +(-70:\distI) and +(130:\distI) .. (i2.center);
        %crossing e_o1_i3 and e_o4_i4
        \path [draw,name intersections={of={e_o1_i3 and e_o4_i4}}]
        (intersection-1) node (d) {} ;
        %repeat edge drawing
        \draw[name path=e_o1_i3]  (o1.center) .. controls
        +(-10:\distG) and +(70:\distG) .. (i3.center);
        %crossing e_o1_i3 and e_o3_i4
        \path [draw,name intersections={of={e_o1_i3 and e_o3_i4}}]
        (intersection-1) node (c) {} ;
        %crossing e_o2_i3 and e_o3_i2
        \path [draw,name intersections={of={e_o2_i3 and e_o3_i2}}]
        (intersection-1) node (e) {};
        %repeat edge drawing
        \draw[name path=e_o2_i3]  (o2.center) .. controls
        +(20:\distI) and +(-140:\distI) .. (i3.center) ;
        %crossing e_o2_i3 and e_o4_i2
        \path [draw,name intersections={of={e_o2_i3 and e_o4_i2}}]
        (intersection-1) node (f) {} ;
        %crossing e_o3_i4 and e_o4_i3
        \path [draw,name intersections={of={e_o3_i4 and e_o4_i3}}]
        (intersection-1) node (i) {} ;
        %repeat edge drawing
        \draw[name path=e_o3_i4]  (o3.center) .. controls
        +(110:\distI) and +(-50:\distI) .. (i4.center);
        %crossing e_o3_i4 and e_o4_i2
        \path [draw,name intersections={of={e_o3_i4 and e_o4_i2}}]
        (intersection-1) node (g) {} ;
        %crossing e_o3_i3 and e_o4_i2
        \path [draw,name intersections={of={e_o3_i3 and e_o4_i2}}]
        (intersection-1) node (h) {} ;
        %repeat edge drawing
        \draw[name path=e_o4_i2]  (o4.center) .. controls
        +(-100:\distG) and +(-20:\distG) .. (i2.center);
    \end{scope}
\end{tikzpicture}
\end{document}

A: Welcome! You could just use the very nice knots library. Instead of drawing all these paths, finding intersections, redrawing them ourselves, let knots do that for us. One basically needs to replace all the \draw commands by \strand, and that's it.
\documentclass{standalone}
\usepackage{tikz}
\usetikzlibrary{knots,%bbox
}
\begin{document}

\tikzset{vertex/.style={circle, draw=black, fill=black, radius = 1mm,
scale = 0.8,anchor=center}}

\begin{tikzpicture}[every node/.style={vertex},%bezier bounding box
    ]
    \begin{knot}[%draft mode=crossings,
    knot gap=9,%<- controls the gap size
    flip crossing/.list={1,...,9}]
    \pgfmathtruncatemacro{\n}{4}
    \foreach \pos
    [evaluate=\pos as \angle using (360/\n/2)+\pos*360/\n)]
    in {2,...,\n}
    {%inner  vertices
        \path node (i\pos) at (\angle:2) {};%
    };
    \foreach \pos
    [evaluate=\pos as \angle using (360/\n/2)+\pos*360/\n)]
    in {1,2,...,\n}
    {%outer vertices
        \node (o\pos) at (\angle:6) {};
    };

    %bent outer edges
    \pgfmathtruncatemacro{\distA}{10}
    \strand (o2.center) .. controls
        +(120:\distA) and +(150:\distA) .. (o4.center);

    %straight edges between inner and outer
    %o4.center
    \strand  (o4.center) -- (i4.center);
    %o2.center
    \strand  (o2.center) -- (i2.center);
    %o3.center
    \strand  (o3.center) -- (i3.center);

    %bent edges between inner and outer
    %offset=1
    \pgfmathtruncatemacro{\distI}{2}
    %o1.center
    \strand  (o1.center) .. controls +(-20:\distI) and +(140:\distI) .. (i4.center);
    %o4.center
    \strand  (o4.center) .. controls +(-110:\distI) and +(50:\distI) .. (i3.center);
    %o2.center
    %o3.center
    \strand  (o3.center) .. controls +(160:\distI) and +(-40:\distI) .. (i2.center);
    %bent edges between inner and outer
    %offset=2 (opposite)
    \pgfmathsetmacro{\distG}{5.5}
    %o1.center
    %o4.center
    %o2.center
    \strand  (o2.center) .. controls
    +(80:\distG) and +(160:\distG) .. (i4.center);

    \foreach \pos
    [remember=\pos as \last (initially \n)]
    in {1,2,...,\n}
    {%straight outer edges
        \draw (o\pos.center) --  (o\last.center);
    };
    \foreach \pos
    [remember=\pos as \last (initially \n)]
    in {2,...,\n}
    {%straight inner edges
        \draw (i\pos.center) -- (i\last.center);
    };
    %crossings
    \strand (o1) .. controls +(30:\distA) and +(60:\distA) .. (o3);
    \strand (o1) .. controls +(-70:\distI) and +(130:\distI) .. (i2);
    \strand (o1) .. controls +(-10:\distG) and +(70:\distG) .. (i3);
    \strand (o2) .. controls +(20:\distI) and +(-140:\distI) .. (i3) ;
    \strand (o3) .. controls +(110:\distI) and +(-50:\distI) .. (i4);
    \strand (o4) .. controls +(-100:\distG) and +(-20:\distG) .. (i2);
    \end{knot}
\end{tikzpicture}
\end{document}

Notice that

*

*you can flip crossings, as illustrated. I hope to have reproduced your conventions, but if not, you can always unflip a crossing;

*draft mode=crossings, allows you to find out which crossing belongs to which number;

*\tikzstyle is deprecated;

*if you use the bbox library, you can even fix the bounding box automatically. As of now, you'd need to download the this file as tikzlibrarybbox.code.tex and put it somewhere where LaTeX can find it, such as the same directory as the file you are compiling. If I understood correctly, this library may become part of the official libraries in the future. Unfortunately I fail to understand even the most basic GitHub commands and messages, so I am not sure.)


text:
Q: Dropdown does not show in IE & on mobile devices I'm using the https://github.com/Recras/angular-jquery-timepicker to allow time selection in an angular application.It's working well in chrome.
However, in IE the dropdown does not show proper GMT value(ideally it should show plus 5.30 hours).
On mobile device, the dropdown disappears as soon as we touch on it.


text:
Q: How do i install Broadcom wireless driver after compile a custom kernel? i have compiled a custom kernel(ck-patchs,ubuntu-patchs) for my netbook, everything workis good, but not wireless, i can't install "Wireless Broadcom STA driver" i got this message :
Desculpe, a instalação deste driver falhou.
Por favor, dê uma olhada no arquivo de log para obter detalhes: /var/log/jockey.log

That is saying to i take a look on jockey.log because can't install the driver
so jockey.log :
http://pastebin.com/PreqBcUs

A: I think "ndiswrapper" application can help you more. By this app you can easily install your wifi devices in BC brand.
http://sourceforge.net/apps/mediawiki/ndiswrapper/index.php?title=Main_Page
https://help.ubuntu.com/community/WifiDocs/Driver/Ndiswrapper


text:
Q: How to know which user has marked a reply as Best Reply in a Sharepoint Community I recently created a community site in Sharepoint 2013 and noticed that when someone marked a reply as Best Reply, I cannot see which user has done this action.
Is there a way to get this information ?


text:
Q: list box tkinter не правильно выставляются строки Столкнулся с проблемой. В agelistbox я добавляю слова python js, но они выписываются по два слова в одну строчку, а мне надо, чтобы в одной строчке было по одному слову, как это сделать?
Часть кода с listbox:
def new_window():
    new_window = tk.Toplevel(window)
    new_window.geometry(f"700x300+500+300")
    new_window.resizable(width=False, height=False)
    new_window.title("user1")
    agelistbox=tk.Listbox(new_window, height = 10, width = 15)
    agelistbox.place(x=0, y=0)
    age = ["python", "js"]
    for ages in age:
        agelistbox.insert(tk.END, age)

Код всей программы:
import tkinter as tk
from tkinter import messagebox
window = tk.Tk()
window.geometry(f"700x300+500+300")
window.title("user")
window.resizable(width=False, height=False)
window["bg"] = "#141212"

def exit():
    window.destroy()

def information():
    information = entrypassword.get()
    if information:
        print(information, end="-пароль   ")
    else:
        print("Пароль не был введён")

def infname():
    information = entryname.get()
    if information:
        print(information, end="-имя")
    else:
        print("Имя не было введено")

def recordpassword():
    information = entrypassword.get()
    information1 = entryname.get()
    recordfile = open("C:\\sublime,pycharm.i.t.d\\passwords and names.txt", "a", encoding = "utf-8")
    recordfile.write(f"{information}\n")
    recordfile.close()

def recordname():
    information = entrypassword.get()
    information1 = entryname.get()
    recordfile = open("C:\\sublime,pycharm.i.t.d\\passwords and names.txt", "a", encoding = "utf-8")
    recordfile.write(f"{information1}\n")
    recordfile.close()

def new_window():
    new_window = tk.Toplevel(window)
    new_window.geometry(f"700x300+500+300")
    new_window.resizable(width=False, height=False)
    new_window.title("user1")
    agelistbox=tk.Listbox(new_window, height = 10, width = 15)
    agelistbox.place(x=0, y=0)
    age = ["python", "js"]
    for ages in age:
        agelistbox.insert(tk.END, age)

new_window_button = tk.Button(window, text="Продолжить регистрацию...", command=new_window, activebackground="#7a6d6d", bg = "#141212", fg = "#ffffff")
exitbutton = tk.Button(window, text="exit", command=exit, activebackground="#7a6d6d", bg = "#141212", fg = "#ffffff")
entrypassword = tk.Entry(window)
textpassword = tk.Label(window, text="Введите пароль: ", font="Arial 12", bg = "#141212", fg = "#ffffff")
entryname = tk.Entry(window)
textname = tk.Label(window,text="Введите имя: ", font = "Arial 12", bg = "#141212", fg = "#ffffff")
infbutton = tk.Button(window, text="Сохранить", command=lambda:[information(), infname()], activebackground="#7a6d6d", bg = "#141212", fg = "#ffffff")
recordbutton = tk.Button(window, text="Записать данные", command=lambda:[recordpassword(), recordname()], activebackground="#7a6d6d", bg = "#141212", fg = "#ffffff")

new_window_button.place(x=2, y=75)
exitbutton.place(x=2, y=273)
recordbutton.place(x=70, y= 50)
infbutton.place(x=2, y=50)
entrypassword.place(x=132, y=28)
entryname.place(x=108, y=4)
textpassword.place(x=1, y=25)
textname.place(x=1, y=1)
window.mainloop()

A: Вы в цикле итерируетесь по списку, и каждый раз вставляете полный список, а не отдельный элемент:
age = ["python", "js"]  # age - полный список
for ages in age:
    agelistbox.insert(tk.END, age)  # и тут полный список вставляете

Должно быть так
age = ["python", "js"]
for ages in age:
    agelistbox.insert(tk.END, ages)  # <= ages вместо age

Я бы еще поменял, чтобы у полного списка было множественное число, а у отдельного элемента - единственное, так логичнее.
ages = ["python", "js"]
for age in ages:
    agelistbox.insert(tk.END, age)


text:
Q: Some help on mod_dav, svn and Limit-ing access please. Here's the entry in my Apache configuration file
 <Location /svn/repo1>
DAV svn
SVNPath /var/svn/repositories/repo1
AuthType Basic
AuthName "SVNRepo"
AuthUserFile /var/httpd/passwd
Order deny,allow
Require valid-user
<Limit PUT POST DELETE PROPFIND PROPPATCH MKCOL COPY MOVE LOCK UNLOCK>
    Require user svn
</Limit>

Not sure if its obvious what I'm trying to do, but I want to allow ANY authenticated user read-only access to the repository, but LIMIT PUT POST etc to only 1 particular (authenticated) user. Haven't been able to crack this, was hoping somebody had come across this before?
Thanks in advance.

A: I would do it the other way around:
<Location /svn>
  DAV svn
  SVNParentPath /var/svn

  # Authentication: Digest
  AuthName "Subversion repository"
  AuthType Digest
  AuthUserFile /etc/svn-auth.htdigest

  Require valid-user

  # Authorization: Authenticated users only for non-read-only
  #                (write) operations; allow anonymous reads
  <LimitExcept GET PROPFIND OPTIONS REPORT>
    Require user svn
  </LimitExcept>
</Location>

as suggested in for example: http://svnbook.red-bean.com/en/1.6/svn-book.html#svn.serverconfig.httpd.authz.blanket
the location you use (/svn/repo1) indicates you have several svn repositories you would like to manage? If so I would use the per directory config of svn:  http://svnbook.red-bean.com/en/1.6/svn-book.html#svn.serverconfig.httpd.authz.perdir
It prevents apache server reloads if you need to adjust the permsissions.


text:
Q: Close dialog, when pressed OK button on it If the user clicks on a button, a dialog shows up, asking to input a string, and there's an 'OK' button on the same dialog, when the user presses that, the dialog should close. That's at least the plan, the problem is: after adding the eventhandler to the OK button, my application freezes, when the user would open the dialog.
addNewFamButton = FindViewById<Button>(Resource.Id.newFamilyButton);
addNewFamButton.Click += (sender, e) => {
    Dialog dialog = new Dialog(this);
    dialog.SetContentView(Resource.Layout.addNewFamily);
    dialog.SetTitle("Add new family to the list");
    dialog.Show();

    // Problem starts here:
    Button saveNewFamily = FindViewById<Button>(Resource.Id.dialogButtonOK);
    saveNewFamily.Click += (object o, EventArgs ea) => { dialog.Dispose(); };
};

I tried it with dialog.Cancel() too, but I got the same results. If I remove the last two lines, the dialog works, but obviously won't close.
FIXED: Thanks to user370305 for the simple solution:
Button saveNewFamily = dialog.FindViewById<Button>(Resource.Id.dialogButtonOK);

A: Your OK button is part of Dialog view, so you have to find that view using your dialog object reference, something like, (I am not familiar with xamarin but this one gives you hint)
Change your line,
// Problem starts here:
Button saveNewFamily = FindViewById<Button>(Resource.Id.dialogButtonOK);

with
Button saveNewFamily = dialog.FindViewById<Button>(Resource.Id.dialogButtonOK);

A: try this
        // create an EditText for the dialog
        final EditText enteredText = new EditText(this);
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("Title of the dialog");
        builder.setView(enteredText);
        builder.setPositiveButton("OK", new DialogInterface.OnClickListener()
        {
            @Override
            public void onClick(DialogInterface dialog, int id)
            {
               // perform any operation you want
                enteredText.getText().toString());// get the text

              // other operations
                dialog.cancel();  // close the dialog

            }
        });
        builder.create().show();


text:
Q: Salesforce - pass parameter to controller from inputfield How can you pass a parameter from visualforce page with an inputfield to the controller?
With inputText works, but I need inputField:
<apex:inputText id="firstname" value="{!firstname}" html-placeholder="{!Offer__c.Name__c}" disabled="true"/>
<apex:commandButton action="{!submit}" value="Submit"/>

A: If you have a contact record exposed in Controller as below:
public Contact currentContact {get;set;}
Then you can reference this in a Visualforce page as below:

You can get more information here apex:inputField


text:
Q: ksh wildcard filename parameter to use in for loop I am attempting to write a shell script that will take a file name with a wildcard, find all files matching that pattern in current directory, and copy them. My problem is every time I try and use a variable only the first match echo's and thats it.
./copyfiles.ksh cust*.txt

#! /usr/bin/ksh
IN_FILE=${1}
for file in $IN_FILE
do
    echo "$file"
done

cust1.txt

This seems to only match the first one even though cust1.txt, cust2.txt, and cust3.txt all exist and when I run it with for file in cust*.txt it works.

A: The shell expands your argument of "cust*.txt" to a list then passes the list to your script, which then only processes $1 which is cust1.txt.
You want to use $@ which will process all arguments passed:
#! /usr/bin/ksh
for file in "$@"
do
    echo "$file"
done

I believe there is a limit to how many arguments can be passed this way though.  How many files are you having to process?  Make sure your version of the shell can handle the number of arguments you are likely to process. If I recall you may need a solution utilizing xargs but I'm a tad rusty to help with that.

A: In ./copyfiles.ksh cust*.txt the files cust*.txt will be expanded first.
When you do not want to change your copyfiles.ksh script. call it with
./copyfiles.ksh "cust*.txt"

You can also change your script, with something like
IN_FILE="$@" # INFILES would be a better name


text:
Q: How does SPSS calculate composite variable for MANOVA/Multivariate multiple regression? I have analysed my data using multivariate multiple regression (8 IVs, 3 DVs), and significant composite results have been found.
Before reporting my findings, I want to discuss in my results chapter (briefly) how the composite variable is created.
I have done some reading, and in the sources I have found, authors simply state that a 'weighted linear composite' or a 'linear combination of DVs' is created by SPSS (the software I am using).
They do not explain how they are weighted, and as someone relatively new to multivariate statistics, I am still unclear.
Are the composite DVs simply a mean score of the three DVs I am using, or is a more sophisticated method used on SPSS?
If the latter is true, could anyone either a) explain what this method is, or b) signpost some useful (and accessible) readings which explain the method of creating composite variables?
Many thanks

A: Multivariate tests in GLM are created using the multivariate general linear hypothesis form $L\beta M = K$ where $L$ is a matrix of contrast coefficients applied to the predictors, $\beta$ is the matrix of population regression coefficients, $M$ is a transformation matrix of the dependent variables, and $K$ is the matrix of null-hypothesized values for $L\beta M$, typically (and by default) $0$. As @ttnphns indicates, that these are matrices rather than scalars.
In the case of these particular tests, $L$ is actually a vector $l$ consisting of 0 values for the intercept and all but one of the predictors, which has a 1. $\hat{\beta}$, or the estimated matrix of regression coefficients, is used for $\beta$, and $M$ is an identity matrix of order equal to the number of dependent variables, in your case three.
The regression of each dependent on the set of predictor variables is the same here as if you were to run each one separately. The same regression coefficients and univariate test statistics will result either way. The null hypotheses tested in the multivariate case are simply the intersections of the univariate null hypotheses: the population $\beta$ for a given predictor is 0 for each of the dependent variables.
What's done in the multivariate case is simply to pool information about the correlations among the dependent variables to create more powerful tests of the same hypotheses you'd test about each dependent variable separately.


text:
Q: How can I prevent the SD version of a TV show from downloading in iTunes when I purchase an HD show? When I buy a TV show in iTunes in high-definition, at the time iTunes starts to download the show, it actually begins downloading two versions of the show: one in standard definition, and one in high definition.
This is a waste of my bandwidth!
I only care to have the HD version of a TV show downloaded.  I've tried to cancel the SD version download that's paired with the HD one I ordered, and that temporarily solves the problem, but the next time I use iTunes to download something else, it seems to remember and restarts previously cancelled SD downloads!  Must I completely download the SD version, and then delete it in order to clear the queue?  That doesn't save my bandwidth :-(
Is there any way to prevent iTunes from downloading the SD version of a TV show I buy in HD?

A: There is no way to prevent this permanently, automatically.
For each individual purpose, you can contact iTunes Music Store customer support, and as them to remove the SD version from your downloads queue, but bear in mind that you will not be able to transfer the movie to any iPods etc that only support SD (most of them, except for the very latest incarnations).
Source: Second result of a google search


text:
Q: Can't focus an Input created with JS I start saying that I'm a newbie ,my problem is that I can't focus the input field that i created in pure Js, I can focus it only right-clicking or using Tab.Could anyone explain me where is the problem here and how could i fix it using simply pure JS?
As you can see i've simply added some elements in my DOM.
HTML:

+ nuova voce

JAVASCRIPT:
function nuovavoce() {

  var div = document.createElement('div');
  var caselle = document.createElement("form");
  var input1 = document.createElement("input");
  var input2 = document.createElement("input");

  document.getElementById("cla").appendChild(div);
  div.style.backgroundColor = "black";
  div.style.position = "absolute";
  div.style.left = "0px";
  div.style.width = "100%";
  div.style.height = "100%";
  div.style.top = "0px";

  div.appendChild(caselle);
  caselle.setAttribute("method", "post");
  caselle.setAttribute("enctype", "multipart/form-data");
  caselle.setAttribute("onsubmit", "");

  caselle.appendChild(input1);
  input1.style.position = "static";
  input1.style.width = "80%";
  input1.style.height = "";
  input1.style.marginLeft = "";
  input1.style.marginTop = "";
  input1.setAttribute("name", "titolo");
  input1.setAttribute("type", "text");

  caselle.appendChild(input2);
  input2.style.position = "static";
  input2.style.width = "80%";
  input2.style.height = "";
  input2.style.marginLeft = "";
  input2.style.marginTop = "";
  input2.setAttribute("type", "submit");
  input2.setAttribute("name", "submit_categoria");
}

A: I would suggest to use .focus() method.  At the end of your function you need to add:
add input1.focus();

function nuovavoce() {

    var div = document.createElement('div');
    var caselle = document.createElement("form");
    var input1 = document.createElement("input");
    var input2 = document.createElement("input");

    document.getElementById("cla").appendChild(div);
    div.style.backgroundColor = "black";
    div.style.position = "absolute";
    div.style.left = "0px";
    div.style.width = "100%";
    div.style.height = "100%";
    div.style.top = "0px";

    div.appendChild(caselle);
    caselle.setAttribute("method", "post");
    caselle.setAttribute("enctype", "multipart/form-data");
    caselle.setAttribute("onsubmit", "");

    caselle.appendChild(input1);
    input1.style.position = "static";
    input1.style.width = "80%";
    input1.style.height = "";
    input1.style.marginLeft = "";
    input1.style.marginTop = "";
    input1.setAttribute("name", "titolo");
    input1.setAttribute("type", "text");

    caselle.appendChild(input2);
    input2.style.position = "static";
    input2.style.width = "80%";
    input2.style.height = "";
    input2.style.marginLeft = "";
    input2.style.marginTop = "";
    input2.setAttribute("type", "submit");
    input2.setAttribute("name", "submit_categoria");
    input1.focus();
}

+ nuova voce


text:
Q: Attempt at centring drawer items makes them have zero text https://snack.expo.dev/5spvLQAsL
In the above snack, I have made a simple edit on line 29 from the default:
drawerStyle: {
  flex:1,
  alignItems: "center",
  justifyContent: "center"
},

Yet, this somehow causes the text to disappear. How can I centre a list of drawer items without having their label text seemingly disappear?


text:
Q: Redirect loop issue in Silex SecurityServiceProvider I've got a issue creating a login form to authenticate users. I followed exactly the example in this page: http://silex.sensiolabs.org/doc/providers/security.html#defining-more-than-one-firewall, but I've got a redirect loop when I try to access my site.
I'd like to secure my entire website, so I wrote this lines:
$app->register(new Silex\Provider\SecurityServiceProvider(), array(
        'security.firewalls' => array(
            'login' => array(
                'pattern' => '^/login$',
            ),
            'secured' => array(
                'pattern' => '^.*$',
                'form' => array('login_path' => '/login', 'check_path' => '/login_check'),
                'logout' => array('logout_path' => '/logout'),
                'users' => array(
                    // password is foo
                    'user1' => array('ROLE_USER', '5FZ2Z8QIkA7UTZ4BYkoC+GsReLf569mSKDsfods6LYQ8t+a8EW9oaircfMpmaLbPBh4FOBiiFyLfuZmTSUwzZg=='),
                ),
            ),
        ),
));

$app->mount('/login', include '../src/login.php');

Then I created a login.php file:
$controllers->get('/', function(Silex\Application $app, Request $request) {
    return $app->render('login.html.twig', array(
        'error'         => $app['security.last_error']($request),
        'last_username' => $app['session']->get('_security.last_username'),
    ));
});

When I try to go to my homepage http://localhost I've got a redirect loop message by the browser.
Where am I wrong?
Thanks all!

A: Ok I spotted the issue: it's on the mount behaviour with /login path. I had to change those lines in:

$app->mount('/', include '../src/login.php');

And in the login.php:

$controllers->get('/login', ...


text:
Q: This autoloader loads only the first class I have the following autoloader, that for some reason is loading only the first class.
Here is the Autoloader class
<?php
 class AutoloaderException extends Exception{}

class AutoLoader
{
    private $classDir;
    private $namespace;
    public $dirSeparatorSymbol = '\\';

    public function __construct($namespace, $classDir)
    {
        $this->classDir = $classDir;
        $this->namespace = $namespace;

    }

    private function load($class)
    {

        $include_path = str_replace($this->dirSeparatorSymbol, DIRECTORY_SEPARATOR, $this->classDir);

        $classFilename = strtolower(substr($class, strrpos($class, '\\') + 1) . '.php');

        if(file_exists($include_path.$classFilename)){
            require $include_path.$classFilename;

            return true;
        }

        throw new AutoloaderException('Class '.$classFilename. ' could not be loaded');
    }

    public function register()
    {
        spl_autoload_register([$this, 'load']);
    }
}

While the above works, but only loads one class at a time. So, in the below example.
For every registered path/class only first will only get loaded.
$b = new Autoloader('mercury\venus\earth', __DIR__.'/mercury/venus/earth/');
$b->register();

$a = new Autoloader('bar\tar', __DIR__.'/foo/bar/tar/');
$a->register();

$x = new bar\tar;

$y = new mercury\venus\earth;

What could be the problem for this?

A:
If there must be multiple autoload functions, spl_autoload_register() allows for this. It effectively creates a queue of autoload functions, and runs through each of them in the order they are defined.

http://php.net/manual/en/function.spl-autoload-register.php
It's queue. Second autoload function would run if first autoload function did not define a class.
So, you do not need to throw an exception in your autoload method because it would prevent launching second autoload method in your autoload queue.


text:
Q: Return calling first before await const isLicensesValid = async (
  licenseList: Promise<string>[]
): Promise<string> => {
  let errorText = "";
  await licenseList.forEach(async (licenseFile) => {
    await licenseFile.then(async (licenseData: string) => {
      const licenseType = await Object.keys(
        JSON.parse(licenseData).Features
      )[0];
      if (!isLicenseValid(licenseData, licenseType.toLowerCase())) {
        errorText = "One or more invalid license file in zip";
      }
    });
  });
  return errorText;
};

not sure why errorText always returns empty. Await is not working in then function. Can someone please suggest what is the problem here


text:
Q: Scala-How to apply this class code to a datafile which contains more than one record How to apply this class code to a datafile which contains more than one record
class Iris(val sepal_len:Double,val sepal_width:Double,val petal_len:Double,
           val petal_width:Double,var sepal_area:Double,val species:String){
require(sepal_area == sepal_len*sepal_width, "wrong values")
def this(sepal_len:Double,
     sepal_width:Double,
     petal_len:Double,
     petal_width:Double,
     species:String
) = {
     this(sepal_len,sepal_width,petal_len,petal_width,sepal_len * sepal_width,species)
}
    override def toString:String = "Iris("+sepal_len+","+sepal_width+","+petal_len+","+petal_width+
                                      ","+sepal_area+","+species + ")"
}

val ir = new Iris(1.2,3.4,4.5,5.0,4.08,"setosa")
Iris(1.2,3.4,4.5,5.0,4.08,setosa)

val ir1 = new Iris(1.2,3.4,4.5,5.0,"setosa")
output => ir1: Iris = Iris(1.2,3.4,4.5,5.0,4.08,setosa)

Please give me some idea

A: Use foreach and for every line create a collection of objects. maybe a list

A: I would suggest you to use case classed for such data structures and companion object for class overload.
case class Iris(sepal_len: Double, sepal_width: Double, petal_len: Double, petal_width: Double, sepal_area: Double, species: String) {
    require(sepal_area == sepal_len * sepal_width, "wrong values")
}

object Iris {
    def apply(sepal_len: Double, sepal_width: Double, petal_len: Double, petal_width: Double, species: String) =
        new Iris(sepal_len, sepal_width, petal_len, petal_width, sepal_len * sepal_width, species)
}

val ir = Iris(1.2, 3.4, 4.5, 5.0, 4.08, "setosa")
val ir1 = Iris(1.2, 3.4, 4.5, 5.0, "setosa")

A: I've made the assumption that your sepal_area is not a required field in your class due to your examples and answered accordingly, but if it is required then changing the code will be easy.
In my example answer, I'm storing a collection of Iris. You could alternatively make a case class like:
case class Irises(irises: Seq[Iris])

Example CSV file:
1,5.1,3.5,1.4,5.1,Iris-setosa
2,4.9,3,1.4,9.8,Iris-setosa
3,4.7,3.2,1.3,14.1,Iris-setosa
4,4.6,3.1,1.5,Iris-setosa
5,5,3.6,1.4,25,Iris-setosa
6,5.4,3.9,1.7,32.4,Iris-setosa

Code:
object Demo extends App {

  case class Iris(sepal_len: Double, sepal_width: Double, petal_len: Double,
             petal_width: Double, var sepal_area: Double = 0, species: String) {

    // if undefined on constructing the class
    sepal_area = if(sepal_area == 0) sepal_len * sepal_width else sepal_area

    def format(double: Double): Double = {
      double.round
    }

    // had weird thing where 4.7 * 3 = 14.100000000000001
    require(format(sepal_area) == format(sepal_len * sepal_width), "wrong values")

    // using string concatenation looks much more readable
    override def toString: String = s"Iris($sepal_len,$sepal_width,$petal_len,$petal_width,$sepal_area,$species)"
  }

  // file.csv found in {project-name}/file.csv
  val bufferedSource = io.Source.fromFile("file.csv")
  val seq = bufferedSource.getLines.map {
    line =>

      // for each line in csv file, split by comma and remove all whitespace around each part
      val cols = line.split(",").map(_.trim)

      // define parts
      val sepal_len = cols.head.toDouble
      val sepal_width = cols(1).toDouble
      val petal_len = cols(2).toDouble
      val petal_width = cols(3).toDouble
      val species = if(cols.length == 6) cols(5) else cols(4)

      // if sepal_area is defined
      if (cols.length == 6) Iris(sepal_len, sepal_width, petal_len, petal_width, cols(4).toDouble, species)
      // if sepal_area is not defined
      else Iris(sepal_len, sepal_width, petal_len, petal_width, species = species)
  }.toSeq

  seq.foreach(println)
  // Iris(1.0,5.1,3.5,1.4,5.1,Iris-setosa)
  // Iris(2.0,4.9,3.0,1.4,9.8,Iris-setosa)
  // Iris(3.0,4.7,3.2,1.3,14.1,Iris-setosa)
  // Iris(4.0,4.6,3.1,1.5,18.4,Iris-setosa)
  // Iris(5.0,5.0,3.6,1.4,25.0,Iris-setosa)
  // Iris(6.0,5.4,3.9,1.7,32.4,Iris-setosa)

  val newSeq = seq.toSeq
  newSeq.foreach(println)

  // close the source once you've finished with it
  bufferedSource.close
}


text:
Q: What does this structure of the URL mean? http://www.example.com/?i=0 I have been asked to switch between the existing front/home page of a website which has the URL
http://www.example.com

to a differnt page with the URL
http://www.example.com/?i=0

It's a very old website (twenty twelve theme), and I can't understand what this ?i=0 means, and how they built this specific page.
To add clarity
In the website www.example.com there is a page which has a URL structure that is different from all other pages and this is the URL: www.example.com/?i=0
The client wants that this page (www.example.com/?i=0) will be the home page and not an inner page, so I am trying to understand how to build it. Now it is not in the WordPress pages list, it's not a post or a category. I have also tried to disable all the plugins, but it didn't effect the page URL or its content, so I don't know where this page is coming from.

A: It means that you have some url parameter loading from site, as reaction to some plugins, or file, or some changes, or behavior on site that may be loaded by some php code. In this scenario it can't be exactly seen where is it coming from, but it looks like starting some type of increment.
But most important you can't just change the url site with added paramete ?i=0 that is not the way this functions, and you can't change your adress to something like this.
If you need to transfer your site from domainexample1.com to domainexample2.com/?i=0 you shouldn't worry about this ?i=0 because if you are going to delete all content from domain2 and put there domain1 content it will not happened as this ?i=0 part is result of some functionality on this site.

A: In very general sense this looks like an arbitrary GET query. WP uses these extensively in a raw form or (commonly) hidden under a layer of pretty permalinks.
However i specifically doesn't seem to be any query variable name WordPress recognizes natively. Most likely it is something custom to the site (or maybe some extension installed). You will have to track down in code what exactly accesses this value and for what reason.

A: It's very difficult for someone here to tell you where to look as it could be anywhere.
I suggest you download all your wordpress files on to your computer and then use a text editor to search those files for $_GET['i'] and $_REQUEST['i'] which will probably help you find where to start looking.