text:
Q: Spring 4 Exception Handling : No suitable resolver for argument Problem Statement
Migration to Spring 4 from Spring 3 induces some exceptions in exception handling flow.
  The Exception says No suitable resolver for argument in the org.springframework.web.method.support.InvocableHandlerMethod class.
So whenever and exception occurs Spring tries to find the Exception Handler which it gets
 but when it tries to populate the method arguments or exception Handler it throws the below exception
Failed to invoke @ExceptionHandler method:
  public org.springframework.web.servlet.ModelAndView
       HelloController.handleCustomException(CustomGenericException, javax.servlet.http.HttpServletRequest, org.springframework.web.servlet.ModelAndView)

  java.lang.IllegalStateException:
     No suitable resolver for argument [2]
             [type=org.springframework.web.servlet.ModelAndView]

HandlerMethod details:
Controller [HelloController]
Method [public org.springframework.web.servlet.ModelAndView
        HelloController.handleCustomException(CustomGenericException,
            javax.servlet.http.HttpServletRequest,org.springframework.web.servlet.ModelAndView)]
        at org.springframework.web.method.support.InvocableHandlerMethod.getMethodArgumentValues(
                     InvocableHandlerMethod.java:169)

It basically comes for @CRequestParam("p") String p  variable
Code
Controller
@RequestMapping(method = RequestMethod.GET, value="/exception2")
    public String getException1(ModelMap model, @CRequestParam("p") String p) {

        System.out.println("Exception 2 "+ p);
        throw new CustomGenericException("1","2");
    }

Exception Handler
@ExceptionHandler(CustomGenericException.class)
    public ModelAndView handleCustomException(CustomGenericException ex,
            HttpServletRequest request, @CRequestParam("p") String p) {

            ModelAndView model = new ModelAndView("error/generic_error");
            model.addObject("exception", ex);
            System.out.println("CustomGenericException  ");
            return model;
    }

Annotations
@Target( { ElementType.PARAMETER })
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface CRequestParam {
    String value() default "";
}

Param Resolver
public class CRequestparamResolver implements HandlerMethodArgumentResolver {

    @Override
        public boolean supportsParameter(MethodParameter methodParameter) {
          CRequestParam requestParamAnnotation =
          methodParameter.getParameterAnnotation(CRequestParam.class);
        if(requestParamAnnotation==null){
        return false;
        }
        return true;
        }

    @Override
    public Object resolveArgument(MethodParameter methodParameter,
        ModelAndViewContainer mavContainer, NativeWebRequest webRequest,
        WebDataBinderFactory binderFactory) throws Exception {

    CRequestParam requestParamAnnotation = methodParameter .getParameterAnnotation(CRequestParam.class);

    if (requestParamAnnotation != null) {
        String requestParamName = requestParamAnnotation.value();
        if (StringUtils.hasText(requestParamName)) {
        return webRequest.getParameter(requestParamName);
        }
    }
    return null;
  }

XML Configuration
<bean
        class="com.mkyong.common.resolver.AnnotationMethodHandlerAdapterConfigurer"
        init-method="init">
        <property name="customArgumentResolvers">
            <list>
                <bean class="com.mkyong.common.resolver.CRequestparamResolver" />
            </list>
        </property>
    </bean>

    <bean
 class="org.springframework.web.servlet.mvc.method.annotation.ExceptionHandlerExceptionResolver">
        <property name="customArgumentResolvers">
            <list>
                <bean class="com.mkyong.common.resolver.CRequestparamResolver" />
            </list>
        </property>
    </bean>

Source Code
https://github.com/santoshjoshi/SpringMVC4

A: Solved the problem by passing the custom arguments in request itself.
code is as  below :
Controller
@RequestMapping(method = RequestMethod.GET, value = "/exception2")
public String getException1(ModelMap model, @CRequestParam("p") String p, HttpServletRequest request) {

  System.out.println("Exception 2 " + p);
  request.setAttribute("p", p);
  throw new CustomGenericException("1", "2");
}

Exception Handler
@ExceptionHandler(CustomGenericException.class)
public ModelAndView handleCustomException(CustomGenericException ex, HttpServletRequest request) {

  ModelAndView model2 = new ModelAndView("error/generic_error");
  model2.addObject("exception", ex);
  System.out.println(request.getAttribute("p"));
  System.out.println("CustomGenericException  ");
  return model2;

}

Complete source code is available at git

A: Solved the problem  by providing the implementation of WebApplicationInitializer
public class SpringDispatcherConfig implements WebApplicationInitializer {

@Override
public void onStartup(ServletContext servletContext) throws ServletException {
    AnnotationConfigWebApplicationContext Contianer =   new AnnotationConfigWebApplicationContext();
    Contianer.register(SpringConfig.class);
    Contianer.setServletContext(servletContext);
    DispatcherServlet dispatcherServlet = new DispatcherServlet(Contianer);
    dispatcherServlet.setThrowExceptionIfNoHandlerFound(true);
    Dynamic servlet = servletContext.addServlet("spring",dispatcherServlet);
    servlet.addMapping("/");
    servlet.setLoadOnStartup(1);

}


text:
Q: Method for finding implicit equations $Ax=0$ that describe a subspace with known base. Let $V$ a vector space and $U$ a subspace of $V$. Let $B_U$ a basis of $U$. How can you find a matrix $A$ such that $x\in V \iff Ax=0$? That is, I want to find the implicit description of a subspace with a given basis. I know how to do for concrete exercises, but I'd like to know a simple algorithm that I can use on the PC. I've been searching and I read the following.
Suppose the basis of the subspace is given in the rows of a matrix $B$. If $M=null(B)$ gives a matrix whose columns are the basis of the subspace given by the implicit equations $Bx=0$, then $M'$ gives the coefficients of the implicit equations of the subspace.
Why is that? I've read that it might have to do with orthogonal complement, but I think it must be simpler... just using the definition.
An example:
Let $U$ the subspace $\mathbb{R}^3$ with basis $\{(1,0,0), (0,1,0)\}$. To find the implicit equations, one would do write a generic element of $U$ as a linear combination of the vectors of the basis, so
\begin{equation}\left(
\begin{matrix}
x\\
y\\
z
\end{matrix} \right)
= \lambda \left(\begin{matrix}
1\\
0\\
0
\end{matrix} \right) + \mu \left(\begin{matrix}
0\\
1\\
0
\end{matrix} \right) = \left(\begin{matrix}
\lambda\\
\mu\\
0
\end{matrix} \right)
\end{equation}
So the conclusion is that $z=0$, and this is the implicit equation describing the subspace.
With the other method, one would write
B =\begin{equation}\left(
\begin{matrix}
1&0&0\\
0&1&0
\end{matrix} \right)\end{equation}
and find $null(B)$, which is the column vector $(0,0,1)'$. In $null(B)$ there are the coefficients of the implicit equation, $(0x+0y+) 1z=0$.
Why does this works?
Thanks in advance

A: The "reason why" can be explained without the notion of orthogonal complement.
Let $B$ be your matrix such that the columns of its transpose $B'$ form your basis $B_U=(B_1,\dots,B_r)$ of $U,$ and let "$null(B)=C$" be a matrix whose columns $C_1,\dots,C_s$ form a basis of $\ker B.$ Then these columns belong to $\ker B$, so that
$$BC_j=0\quad\forall j=1,\dots,s.$$
More compactly: $BC=0,$ or $C'B'=0'=0,$ i.e. $C'B_i=0$ for all $i=1,\dots,r,$ i.e. $C'U=0,$ so the lines of $C'$ (or the columns of $C$) are coefficients of implicit equations for $U.$
But I should improve that answer by being more careful about the ranks of these matrices, to establish that $U$ is exactly the kernel of $C'$ (and not a proper subsspace of it).
Or more directly, using orthogonal complements:
$$\ker(C')={\rm im}(C)^\bot=\ker(B)^\bot={\rm im}(B')=U.$$

redpajama_set_name: RedPajamaStackExchange


text:
Q: CakePHP: shortcomings with indirectly associated models I'm having some issues with dealing with indirectly associated models in cakephp.  My current model setup is as follows:
Deliveries hasOne License
License belongsTo Delivery
License hasAndBelongsToMany Product (and vice-versa)
License hasAndBelongsToMany ProductOption (and vice-versa)

I'm trying to save information about ALL of these models inside ONE form.  The shortcomings I'm running into are the following:

*

*The form helper only seems able to see the field type one level deep.

*saveAll() only seems able to save records one level deep (for multiple model forms).
I'm searching everywhere for the solutions to these issues, but since I'm new to CakePHP, I'm not sure what the newest methods or "correct" methods are for dealing with these issues.
Any advice is much appreciated. Thank you all!
EDIT: I've posted code to my failed attempt here: http://bin.cakephp.org/saved/58501

A:
saveAll() only seems able to save records one level deep (for multiple model forms).

I have stumbled across this limitation in the past and chose, at the time, to work around it by breaking up my form into multiple smaller forms.
One thing to bear in mind when using saveAll and InnoDB tables is that you get atomic transactions, as Cake will perform a rollback if it is unable to commit changes to the database.
So, while you can obviously work around the issue with a few lines of your own code (since Cake's saveAll one-liner doesn't live up to expectations), you would have to spend more time if transactions were a requirement.

A: Hi I know this is an old post but thought I'd post this to help others, As of CakePHP 2.1 you can save multiple levels of model association using an option on the call the saveAll(), more details here: http://book.cakephp.org/2.0/en/appendices/new-features-in-cakephp-2-1.html#model-saveall-model-saveassociated-model-validateassociated
Example:
$this->MyModel->saveAll($this->request->data, array('deep'=>true));

As for the FormHelper limitation, I'm as lost as you are, I will probably resort to setting the input types manually as my fields don't need too much validation.


text:
Q: How to get unique values based on dictionary key, which is an element of an array in objective C? How to get unique values based on dictionary key, which is an element of an array in objective C ?
for example:
i am having an array of an Items
aryItem
  aryItem[0] = Dictionary{

               ItemCategory
               ItemName
               ItemPrice

               }

  aryItem[1] = Dictionary{

               ItemCategory
               ItemName
               ItemPrice

               }

   ...........
   ...........
  aryItem[n] = Dictionary{

               ItemCategory
               ItemName
               ItemPrice

               }

Now i want to get only unique ItemCategory , not duplicates. If i can write [[aryItem objectatIndex:i] valueForKey:ItemCategory] i get all categories, same category also included in this. I need only unique categories. I have an option searching whole array and then get unique Itemcategory objects, but i am looking for any short way to accomplish the same thing.
Thanks.

A: I think NSSet class is most suitable to collect unique values. You can create it using something like:
NSSet* categories = [NSSet setWithArray: [aryItem valueForKey: @"ItemCategory"]];


text: Q: SonarQube plugin to modify evaluation of existing code coverage I'm looking to create a plugin to prevent analysis failing if the the coverage level is within X percent of the current quality gate value. I'm not too sure where to begin or how to approach solving this problem. I've looked at the Web API to attain the current quality gate values although I'm not sure if this is correct. The current setup uses SonarScanner for Jenkins.


text:
Q: Adding key value pair (value from an array) to specific objects in an array I have an array of objects:
chachters = [{name: "Frodo", race: "hobitt", age: 111},
             {name: "Gandalf", race: "human", age: 2019}],
             {name: "Aragorn", race: "elf", age: 40}];

and an array of strings.
swords = ["Sting","Glamdring","Anduril"];

I want to add a key-value pair to the objects in 'characters' so the correct sword is assigned to the correct character. The indexes match in that swords[0] needs to be added to the value in charachrers[0]:
Here's what I'd like characters to look like:
 chachters =[{name:"Frodo", race:"hobitt", age:111,sword:"Sting"},
             {name:"Gandalf",race:"human",age:2019,sword:"Glamdring"}],
             {name:"Aragorn",race:"elf",age:40,sword:"Anduril"}];

Please help. The fait of middle earth depends on it.

A: You can use map and Object.assign:

var chachters = [{name: "Frodo", race: "hobitt", age: 111},
             {name: "Gandalf", race: "human", age: 2019},
             {name: "Aragorn", race: "elf", age: 40}],
    swords = ["Sting","Glamdring","Anduril"];

var result = chachters.map( (obj, i) => Object.assign({ sword: swords[i] }, obj) );
console.log(result);

A: You can use array#map with spread syntax. Add a sword to a character based on the index.

const chachters = [{name: "Frodo", race: "hobitt", age: 111}, {name: "Gandalf", race: "human", age: 2019},       {name: "Aragorn", race: "elf", age: 40}],
      swords = ["Sting","Glamdring","Anduril"],
      result = chachters.map((o,i) => ({...o, sword: swords[i]}));
console.log(result);

A: Use #array.forEach and for each object of array add extra key with the value from swords array.
Working snippet (This way, it will do the changes directly in the original array):

let chachters = [
      {name: "Frodo", race: "hobitt", age: 111},
      {name: "Gandalf", race: "human", age: 2019},
      {name: "Aragorn", race: "elf", age: 40}];

let swords = ["Sting","Glamdring","Anduril"];

chachters.forEach((el,i) => {
     el.sword = swords[i];
})

console.log('chachters = ', chachters);

If chachters is a state array and you are updating the state then use this way:

let chachters = [
      {name: "Frodo", race: "hobitt", age: 111},
      {name: "Gandalf", race: "human", age: 2019},
      {name: "Aragorn", race: "elf", age: 40}];

let swords = ["Sting","Glamdring","Anduril"];

let newchachters = chachters.map((el,i) => ({...el, sword: swords[i]}))

console.log('chachters = ', chachters);
console.log('newchachters = ', newchachters);

A: You can create a function to append the array of strings to the array of objects;
For example:
This function will be used to append the array of strings to the array of object
function appendObjTo(swords, chachters ) {
        return Object.freeze(swords.concat(chachters ));
    }

From what you defined:
  swords = ["Sting","Glamdring","Anduril"];
        const chachters = [{name: "Frodo", race: "hobitt", age: 111},
             {name: "Gandalf", race: "human", age: 2019},
             {name: "Aragorn", race: "elf", age: 40}];

        const newChachters = appendObjTo(swords, chachters);

A: Allow me to try. I'm not so familiar with .map() :P

var characters = [
    {name: "Frodo", race: "hobitt", age: 111},
    {name: "Gandalf", race: "human", age: 2019},
    {name: "Aragorn", race: "elf", age: 40}
];
var swords = ["Sting", "Glamdring", "Anduril"];

var charactersWithSwords = characters.map(function (character, index) {
    character.swords = swords[index];
    return character;
});

console.log(charactersWithSwords);

Result:
> Array [Object { name: "Frodo", race: "hobitt", age: 111, swords: "Sting" }, Object { name: "Gandalf", race: "human", age: 2019, swords: "Glamdring" }, Object { name: "Aragorn", race: "elf", age: 40, swords: "Anduril" }]


text:
Q: =sort filter including minimum value Google Spreadsheet I hope you can help me. At this moment I am busy with creating a presentation with an auto updated graph. In this graph I will show the top 5 latest scores of people that are attending a competition. The values will be added via a google form but the score will be added later in the google spreadsheet.
The problem at this moment is that it also shows input with '0' value. I need to have the values visible once it is higher than '0'.
Does anyone know how this is possible to manage? :)
See example here: https://docs.google.com/spreadsheets/d/1cld9sU51Xf78fR14RH7gGlPNkz1Z7732DD5leQwweb4/edit?usp=sharing
Thanks!
KR Sami


text:
Q: System freezes when swapping I have a raspberry pi which swaps to an external NAS (please don't judge me :) ) over CIFS (link is a direct 100Mbit full duplex Ethernet connection). Swap works fine until a certain threshold which is about 100MB. The system then freezes and network connection with NAS stops. Samba share is mounted with automount. Where do I start if I want to find out why the Pi stops using the swapfile? I dont mind the slowdown because I'm just compiling heavy programs but when it freezes I'm forced to reboot.

A: Just looking at kernel code, this shouldn't even let you swapon a file that's on a CIFS mount, so I'm rather surprised this works at all.  There are two generic issues with swap on a networked filesystem:

*

*Swap on Linux requires a static block mapping.  This is why swap files can't be sparse unless they use unwritten extents, and why you need a loop device to put a swap file on copy-on-write or log structured filesystems.  You can work around this in theory using a loop device, but that should be a last resort.

*Some protocols or authentication setups require userspace components, and if those don't mlock() their entire address space, you may end up in a situation where you can't swap anything because you can't run the userspace code because you have no memory to load it into.

CIFS suffers from the first issue, and also the second if you are using authentication and the system does not maintain a constant connection.
You mentioned you're using a Pi, I'd suggest looking into using ZRAM, and possibly a local swap file (decent SD cards are inexpensive).  You can even use a USB flash drive if need be instead of the SD card.
Alternatively, and more generically, if you have a reasonable NAS system, you could look into swapping via (in general order of preference) NBD, ATA over Ethernet, or iSCSI (which depending on how it's set up on the Pi may also suffer from the second limitation listed above).


text:
Q: I'm using python to remove the repeated character in a string, is there any way to do this except 'not in' and set()? I wrote a function to do this, but unfortunately, it doesn't work. Did I miss anything? I try to avoid using 'not in' and set() and anything that C++ doesn't have. But the output is either the same as the input or just no puput at all
def find(number):
global key
for m in range(len(match)):
    if number == match[m]:
        key = match[m]
        break
    else:
        key = None

def find1(number1):
    if number1 == None:
        return True
    else:
        return False

a = str(input())
match = '0'

for i in range(len(a)):
    b = find(a[i])
    if find1(b):
        match += a[i]

print(match)

A: I have no idea why you'd want to do this in Python in a manner that avoids "anything that C++ doesn't have", however it seemed an interesting exercise so comparable solutions in both Python and C++ below.
The solution(s) below use regular expressions (built-in re library for Python and standard library regex header for C++). Each example matches any single character as the first capture group using (.) and then uses \1+ to identify one or more repetitions of the first character matched, if this pattern matches (i.e. there is a repeated character), this operation is performed left-to-right over the entire string and the string following this operation is returned - i.e. a copy of the original string with repeated characters pruned.
Python Solution
def remove_repeated(s):
    return re.sub(r'(.)\1+', r'\1', s)

s = input("Enter a string: ")

print(remove_repeated(s))

C++ Solution
#include <iostream>
#include <string>
#include <regex>
using namespace std;

string remove_repeated(string s)
{
    regex r ("(.)\\1+");
    return s = regex_replace(s, r, "$1");
}

int main ()
{
    string s;
    cout << "Enter a string: ";
    cin >> s;
    s = remove_repeated(s);
    cout << s;
    return 0;
}

Input:
tteessttiinngg

Output:
testing

Input and output the same over both Python and C++ solutions when testing.


text:
Q: MongoDB lists - get every Nth item I have a Mongodb schema that looks roughly like:
[
  {
    "name" : "name1",
    "instances" : [
      {
        "value" : 1,
        "date" : ISODate("2015-03-04T00:00:00.000Z")
      },
      {
        "value" : 2,
        "date" : ISODate("2015-04-01T00:00:00.000Z")
      },
      {
        "value" : 2.5,
        "date" : ISODate("2015-03-05T00:00:00.000Z")
      },
      ...
    ]
  },
  {
    "name" : "name2",
    "instances" : [
      ...
    ]
  }
]

where the number of instances for each element can be quite big.
I sometimes want to get only a sample of the data, that is, get every 3rd instance, or every 10th instance... you get the picture.
I can achieve this goal by getting all instances and filtering them in my server code, but I was wondering if there's a way to do it by using some aggregation query.
Any ideas?

Updated
Assuming the data structure was flat as @SylvainLeroux suggested below, that is:
[
  {"name": "name1", "value": 1, "date": ISODate("2015-03-04T00:00:00.000Z")},
  {"name": "name2", "value": 5, "date": ISODate("2015-04-04T00:00:00.000Z")},
  {"name": "name1", "value": 2, "date": ISODate("2015-04-01T00:00:00.000Z")},
  {"name": "name1", "value": 2.5, "date": ISODate("2015-03-05T00:00:00.000Z")},
  ...
]

will the task of getting every Nth item (of specific name) be easier?

A: It seems that your question clearly asked "get every nth instance" which does seem like a pretty clear question.
Query operations like .find() can really only return the document "as is" with the exception of general field "selection" in projection and operators such as the positional $ match operator or $elemMatch that allow a singular matched array element.
Of course there is $slice, but that just allows a "range selection" on the array, so again does not apply.
The "only" things that can modify a result on the server are .aggregate() and .mapReduce(). The former does not "play very well" with "slicing" arrays in any way, at least not by "n" elements. However since the "function()" arguments of mapReduce are JavaScript based logic, then you have a little more room to play with.
For analytical processes, and for analytical purposes "only" then just filter the array contents via mapReduce using .filter():
db.collection.mapReduce(
    function() {
        var id = this._id;
        delete this._id;

        // filter the content of "instances" to every 3rd item only
        this.instances = this.instances.filter(function(el,idx) {
            return ((idx+1) % 3) == 0;
        });
        emit(id,this);
    },
    function() {},
    { "out": { "inline": 1 } } // or output to collection as required
)

It's really just a "JavaScript runner" at this point, but if this is just for anaylsis/testing then there is nothing generally wrong with the concept. Of course the output is not "exactly" how your document is structured, but it's as near a facsimile as mapReduce can get.
The other suggestion I see here requires creating a new collection with all the items "denormalized" and inserting the "index" from the array as part of the unqique _id key. That may produce something you can query directly, bu for the "every nth item" you would still have to do:
db.resultCollection.find({
     "_id.index": { "$in": [2,5,8,11,14] } // and so on ....
})

So work out and provide the index value of "every nth item" in order to get "every nth item". So that doesn't really seem to solve the problem that was asked.
If the output form seemed more desirable for your "testing" purposes, then a better subsequent query on those results would be using the aggregation pipeline, with $redact
db.newCollection([
    { "$redact": {
        "$cond": {
            "if": {
                "$eq": [
                    { "$mod": [ { "$add": [ "$_id.index", 1] }, 3 ] },
                0 ]
            },
            "then": "$$KEEP",
            "else": "$$PRUNE"
        }
    }}
])

That at least uses a "logical condition" much the same as what was applied with .filter() before to just select the "nth index" items without listing all possible index values as a query argument.

A: No $unwind is needed here. You can use $push with $arrayElemAt to project the array value at requested index inside $group aggregation.
Something like
db.colname.aggregate(
[
  {"$group":{
    "_id":null,
    "valuesatNthindex":{"$push":{"$arrayElemAt":["$instances",N]}
    }}
  },
  {"$project":{"valuesatNthindex":1}}
])

A: Unfortunately, with the aggregation framework it's not possible as this would require an option with $unwind to emit an array index/position, of which currently aggregation can't handle. There is an open JIRA ticket for this here SERVER-4588.
However, a workaround would be to use MapReduce but this comes at a huge performance cost since the actual calculations of getting the array index are performed using the embedded JavaScript engine (which is slow), and there still is a single global JavaScript lock, which only allows a single JavaScript thread to run at a single time.
With mapReduce, you could try something like this:
Mapping function:
var map = function(){
    for(var i=0; i < this.instances.length; i++){
        emit(
            { "_id": this._id,  "index": i },
            { "index": i, "value": this.instances[i] }
        );
    }
};

Reduce function:
var reduce = function(){}

You can then run the following mapReduce function on your collection:
db.collection.mapReduce( map, reduce, { out : "resultCollection" } );

And then you can query the result collection to geta list/array of every Nth item of the instance array by using the map() cursor method :
var thirdInstances = db.resultCollection.find({"_id.index": N})
                                        .map(function(doc){return doc.value.value})

A: You can use below aggregation:
db.col.aggregate([
    {
        $project: {
            instances: {
                $map: {
                    input: { $range: [ 0, { $size: "$instances" }, N ] },
                    as: "index",
                    in: { $arrayElemAt: [ "$instances", "$$index" ] }
                }
            }
        }
    }
])

$range generates a list of indexes. Third parameter represents non-zero step. For N = 2 it will be [0,2,4,6...], for N = 3 it will return [0,3,6,9...] and so on. Then you can use $map to get correspinding items from instances array.

A: You might like this approach using the $lookup aggregation. And probably the most convenient and fastest way without any aggregation trick.
Create a collection Names with the following schema
[
  { "_id": 1, "name": "name1" },
  { "_id": 2, "name": "name2" }
]

and then Instances collection having the parent id as "nameId"
[
  { "nameId": 1, "value" : 1, "date" : ISODate("2015-03-04T00:00:00.000Z") },
  { "nameId": 1, "value" : 2, "date" : ISODate("2015-04-01T00:00:00.000Z") },
  { "nameId": 1, "value" : 3, "date" : ISODate("2015-03-05T00:00:00.000Z") },
  { "nameId": 2, "value" : 7, "date" : ISODate("2015-03-04T00:00:00.000Z") },
  { "nameId": 2, "value" : 8, "date" : ISODate("2015-04-01T00:00:00.000Z") },
  { "nameId": 2, "value" : 4, "date" : ISODate("2015-03-05T00:00:00.000Z") }
]

Now with $lookup aggregation 3.6 syntax you can use $sample inside the $lookup pipeline to get the every Nth element randomly.
db.Names.aggregate([
  { "$lookup": {
    "from": Instances.collection.name,
    "let": { "nameId": "$_id" },
    "pipeline": [
      { "$match": { "$expr": { "$eq": ["$nameId", "$$nameId"] }}},
      { "$sample": { "size": N }}
    ],
    "as": "instances"
  }}
])

You can test it here

A: Or with just a find block:
db.Collection.find({}).then(function(data) {
  var ret = [];
  for (var i = 0, len = data.length; i < len; i++) {
    if (i % 3 === 0 ) {
      ret.push(data[i]);
    }
  }
  return ret;
});

Returns a promise whose then() you can invoke to fetch the Nth modulo'ed data.


text:
Q: simulate random variable and transform of random variable I have two random variables $X, Y$.
$X \sim  N(0,1) \qquad\text{(normally distributed)}\\
Y = g(X) \qquad\text{(g is a function such as g(x) = 1 + x + 2x^2)}$
I would like to draw a sample of size 1000 of X and Y. Do I need to draw from normal distribution for x and y or just for x and then use it in y? (See code examples for clarification.) In my case version 2 would suit me better, but I am not sure if this is still satisfies my definition of X and Y.
Version 1
m = 1000
x = rnorm(m, 0, 1)
y = g(x)

Version 2
m = 1000
x = rnorm(m, 0, 1)
y = g(rnorm(m, 0, 1))

Which version is correct?

A: (answer largely copied from comments)
You should use version 1. Version 2 will generate $m$ new random variables, not necessarily corresponding to $X$. With version 2 you get the correct marginal distributions, but the joint distribution is wrong. With version 1 both are right.


text:
Q: Why don't IDEs support dynamic formatting? Given all the holy wars surrounding various code formatting styles, and many companies' strict formatting requirements, why don't IDEs allow dynamic reformatting of code?
By that I mean have the IDE format the code the way the user wants it every time, and save the code without any formatting at all. (Well maybe line breaks so that diffs are still easy)
The user wouldn't have to worry about adhering to a coding standard, people wouldn't get bent out of shape over working in code that's not formatted just how they like it, and formatting changes wouldn't show up in repository diffs.
There's have to be some mechanism for turning it off so it doesn't screw up old, pre-formatted code, but otherwise, what's keeping this from becoming a standard feature?
Edit: I'm aware that some IDEs have an reformat feature, but that causes almost as many problems as it solves -- source control diffs become nearly useless as the actual changes are lost in a sea of insignificant formatting changes, and different tab character widths still knock things out of alignment. Also, it doesn't let programmers work with the code in their preferred format.

A: I think Eclipse allows you to format code however you like.
EDIT: Yeah, the Java Code Formatter formats based on rules you set in the project.

A: Because most people like to see the code as it will be committed. Unless all of the tools you use to view your code (diff programs, grep, web based source repository viewers, etc) understand how to dynamically format the code the same way, you're going to be confused by different formattings when you look at it in your IDE vs. the other tools.
I agree it would be nice if we had more structural programming tools, rather than fixed width text tools, but it would require updating everything in your tool chain to really make it workable.

A: I've thought this would be a good idea too, but as a function of the source control software rather than the IDE.
Code could be stored as a list of tokens and then reconstructed when copied to the development machine. This answers aleemb's point as no white space is ever stored. There might need to be more sophisticated formatting rules to cope with all cases though.
It also answers Martin Harris' concerns - the code on your machine wouldn't contain any special characters just white space between tokens.

A: I think that the files that live on your actual machine in most cases should be in a common text format, it is beyond useful to be able to open up any source code file that I'm working on in notepad or any other handy text editor. Because of this I wouldn't want my local copies to contain any special characters that the IDE interprets as "This is an indent, please use a tab or a space here as you feel is appropriate". My opinion is that the best point to do this kind of formatting is the source control system, you check a file in formatted as you like, I check it out formatted as I like.
A while back I asked this question about source control tools not understanding code and ascalonx's answer pointing me towards source control in database. It's a shame that this idea doesn't seem to have more traction since it would solve both our problems and much more. I'm a .NET developer so I'm very much out in the cold with this at the moment, but apparently Eclipse and IntelliJ in the Java world are getting closer to this ideal (I don't know how close, since I've never used either)

A: I think that the biggest hurdle would be reconstructing the source code comments since they have no formal semantics - I'm not talking about JavaDocs or the like but rather the comments that are placed inline with the sources. Without semantic rules for source code comments the whole concept falls apart.
Sure you can version control the AST, but how will you map the comments onto the AST nodes?
A naive approach would be to associate comments with statements in the language, but what if I have a comment that applies to "the next 3 lines" and then someone moves one of the lines somewhere else. Where does the comment go?

A: I am sure there are programs and scripts available that format the code in the way you specify.
While some IDE's support such reformatting of code (Eclipse, Intellij for Java, Wing for Python, VS2007? for .net), even if they dont, it should be a matter of just running those scripts on the source code.

A: If you can handle the following scenario I would think it's a good idea but my hunch is that it's not trivial, which means that it's not intuitive and predictable which is bad for user experience.
If the code is written:
if(value!=null)

and dynamic formatter shows:
if (value != null)

and I modify it to:
if ((value != null) && (value.Length > 0))

and then another developer dynamically formats it to:
if ( (value != null) && (value.Length > 0) )

and changes some other line in the code and saves it. Does the above formatting also get saved? How do you reconcile the different formatting preferences of the two developers because his new additions will in a different format.
You'd have to store in a common format but even so the line lengths would be different and the developers would break the line at different positions for 80 or 100 char wrapping and it gets quite messy.

A: Plagiarism would be hard to detect :)

A: Because most people don't care much about how the code looks as long as it is consistent.

A: I think it's about time that the IDEs start storing their code as XML, and then use a user-defined XSL stylesheet to format the code upon presentation.


text:
Q: Move a window on keypress + mouse (like linux ALT + mouse down) Simple, i want to move a windows pressing ALT+MOUSE, like linux os (ALT+drag).
It's possible to pass a win32 api (move api) to the windows interested clicking on it?
I have a windows services that hook key pressed (ALT button in specific).
When ALT key is pressed and a mouse down event is verified, i want to move window clicking anywhere, not only on the title bar!
Currently i move my form windows in this way:
using System.Runtime.InteropServices;

[DllImport( "user32.dll", CharSet = CharSet.Auto, SetLastError = false )]
static extern IntPtr SendMessage( IntPtr hWnd, uint Msg, int wParam, int lParam );
[DllImportAttribute( "user32.dll", CharSet = CharSet.Auto, SetLastError = false )]
public static extern bool ReleaseCapture();

private void Form1_MouseDown( object sender, MouseEventArgs e )
{
  ReleaseCapture();
  SendMessage( this.Handle, 0xa1, 0x2, 0 );
}

How can I get windows handle of the specific windows by clicking and after call SendMessage() on it?
It's possible?

A: You can do this by trapping the WM_NCHITTEST message that Windows sends to see what area of the window got clicked.  You can fool it by returning HTCAPTION and it will dutifully perform the mouse actions you'd normally get when clicking the caption of a window.  Including moving the window.  Paste this code into your form:
    protected override void WndProc(ref Message m) {
        base.WndProc(ref m);
        // Trap WM_NCHITTEST when the ALT key is down
        if (m.Msg == 0x84 && (Control.ModifierKeys == Keys.Alt)) {
            // Translate HTCLIENT to HTCAPTION
            if (m.Result == (IntPtr)1) m.Result = (IntPtr)2;
        }
    }

A: I worked this out my self, came up with something interesting of my own calculations, worked perfectly for me, for any window (any active foreground window). Kinda long, but really easy to understand if you follow along the comments, hope it helps :)
The way it works, is that you press a certain registered key-combo, like Ctrl+Alt+M
and the mouse will stick in the center of an active window, you move the mouse, the windows follows it, press the SAME combo again, to release, no need for mouse clicks or anything.
public void MoveWindow_AfterMouse()
    {
      // 1- get a handle to the foreground window (or any window that you want to move).
      // 2- set the mouse pos to the window's center.
      // 3- let the window move with the mouse in a loop, such that:
      //    win(x) = mouse(x) - win(width)/2
      //    win(y) = mouse(y) - win(height)/2
      // This is because the origin (point of rendering) of the window, is at its top-left corner and NOT its center!

      // 1-
      IntPtr hWnd = WinAPIs.GetForegroundWindow();

      // 2- Then:
      // first we need to get the x, y to the center of the window.
      // to do this, we have to know the width/height of the window.
      // to do this, we could use GetWindowRect which will give us the coords of the bottom right and upper left corners of the window,
      // with some math, we could deduce the width/height of the window.
      // after we do that, we simply set the x, y coords of the mouse to that center.
      RECT wndRect = new RECT();
      WinAPIs.GetWindowRect(hWnd, out wndRect);
      int wndWidth = wndRect.right - wndRect.left;
      int wndHeight = wndRect.bottom - wndRect.top; // cuz the more you go down, the more y value increases.
      Point wndCenter = new Point(wndWidth / 2, wndHeight / 2); // this is the center of the window relative to itself.
      WinAPIs.ClientToScreen(hWnd, out wndCenter); // this will make its center relative to the screen coords.
      WinAPIs.SetCursorPos(wndCenter.X, wndCenter.Y);

      // 3- Moving :)))
      while (true)
      {
        Point cursorPos = new Point();
        WinAPIs.GetCursorPos(out cursorPos);
        int xOffset = cursorPos.X - wndWidth / 2;
        int yOffset = cursorPos.Y - wndHeight / 2;
        WinAPIs.MoveWindow(hWnd, xOffset, yOffset, wndWidth, wndHeight, true);
        Thread.Sleep(25);
      }
    }

And now:
int moveCommandToggle = 0;
protected override void WndProc(ref Message m)
{
   if (m.Msg == 0x0312)
   {
     int keyID = m.WParam.ToInt32();
     if(keyID == some_key_combo_you_registered_for_the_moving)
     {
         if (moveCommandToggle++ % 2 == 0)
         {
            mover = new Thread(() => MoveWindow_AfterMouse());
            mover.Start();
         }
         else mover.Abort();
      }
    }
 }

If you're wondering about RECT:
  public struct RECT
  {
    public int left;    // xCoor of upper left corner.
    public int top;     // yCoor of upper left corner.
    public int right;   // xCoor of lower right corner.
    public int bottom;  // yCoor of lower right corner.
  };

WinAPIs was just a static class that I did my DllImports in.


text:
Q: Firefox unable to download files Firefox unable to download any file when I use "Choose destination" option. With "Save to folder" option it's works well.
System: Ubuntu 20.04, KDE Plasma 5.18.5.
Firefox 84.02.
I found many related questions but no one answer help me.
I tried to disable addons, create new profile,
I'm unable to download file even with firefox-dev binary downloaded from mozzila page.
But with chromium I have no problems.
My permissions to download folder:
drwxrwxrwt  3 biblbrox biblbrox  12K янв 27 20:28  Downloads

A: I resolve this by installing patched firefox from ubuntu 18.04 repository(this question: https://askubuntu.com/questions/1304442/how-to-use-firefox-from-18-04-repositories-in-ubuntu-20-04/1304485#1304485)


text:
Q: PHP IF[FALSE/NULL/EMPTY] function Since a year or so I had a function in all my projects called: ifNot().
This function is somehow a derivated from the ternary operator:
public function ifNot( $item, $ifNot )
{
    if ( !$item ) {
        return $ifNot
    } else {
        return $item;
    }
}
// The var $foo twice
$var = ( $foo ) ? $foo : 'is empty or false =(';
// The var $foo once
$var = ifNot($foo, 'is empty or false =(');

In fact, Twig Template Engine use something like it:
{{ foo ? 'yes' : 'no' }}

{# as of Twig 1.12.0 #}
{{ foo ?: 'no' }} == {{ foo ? foo : 'no' }}
{{ foo ? 'yes' }} == {{ foo ? 'yes' : '' }}

The question is: There is a better/known approach for this function?
PS: SQL also has an IFNULL() =)

A: Your function is essentially equivalent to a variant of the conditional operator that was added in PHP 5.3:

Since PHP 5.3, it is possible to leave out the middle part of the ternary operator. Expression expr1 ?: expr3 returns expr1 if expr1 evaluates to TRUE, and expr3 otherwise.

It may be a tiny bit faster to use the built-in approach if all your target environments are PHP 5.3 or greater, but I wouldn't really worry about it.

A: Yes, if your PHP is new enough (5.3.0 or newer). See the PHP documentation on the ternary operator

Since PHP 5.3, it is possible to leave out the middle part of the ternary operator. Expression expr1 ?: expr3 returns expr1 if expr1 evaluates to TRUE, and expr3 otherwise.

So while your code above is pretty awkward, there might be instances where you want a function version of this ternary operator (for example, to use as a callable - in those cases, you could just roll with a closure:
function($foo, $default) { return $foo ?: $default; }

A: $var = ifNot($foo, 'is empty or false =(');

is the same as:
$var = $foo?:'is empty or false =(';

In normal PHP (>= version 5.3) too. Your ifNot function is completely superfluous.


text:
Q: Verilog style: one large always block vs multiple small always blocks? Say I have multiple registers set up to update on the same clock, based on different conditions.
I could set this up as a series of multiple always blocks:
reg [7:0] counter;
reg output_even;
reg output_multiple_of_5;

always_ff @ (posedge clk)
   if(reset)
       counter <= 0;
   else
       counter <= counter + 1;

always_ff @ (posedge clk)
   if(reset)
       output_even <= 0;
   else begin
       if(counter % 2 == 0)
           output_even <= 1;
       else
           output_even <= 0;
   end

always_ff @ (posedge clk)
   if(reset)
       output_multiple_of_5 = 0;
   else begin
       if(counter % 5 == 0)
           output_multiple_of_5 <= 1;
       else
           output_multiple_of_5 <= 0;
   end

Alternatively, I could set this up as a single always block with multiple conditions:
reg [7:0] counter;
reg output_even;
reg output_multiple_of_5;

always_ff @ (posedge clk)
   if(reset) begin
       counter = 0;
       output_even = 0;
       output_multiple_of_5 <= 0;
   end
   else begin
       counter = counter + 1;

       if(counter % 2 == 0)
           output_even <= 1;
       else
           output_even <= 0;

       if(counter % 5 == 0)
           output_multiple_of_5 <= 1;
       else
           output_multiple_of_5 <= 0;

   end

I suppose one way of looking at this is whether I should use separate always blocks for separate clocks, or for separate registers.

*

*Is there any difference between how these two code blocks will be synthesized? Extra clock cycle, implied latch, etc, or are they functionally equivalent?

*Is there any stylistic or code-maintenance  reason to prefer one style vs the other?

A: Without the use of non-blocking assignments, the multiple always block style has race conditions. There no way of knowing in a clock cycle whether counter has the previous or updated value. In the single always, you must write your code in a specific flow order. You should be using non-blocking assignments to any valuables that are read by other block to prevent race conditions.
Using multiple blocks is likely to make your code more readable, but the only advantage I can think of for combining then into a single block is when you have common expressions and conditional statements. Your reset example is simple, but you don't want to repeat large case statements as that makes maintenance more difficult.


text:
Q: customized collapsable qtool button in pyqt5 I am using a customized collapsable qtool button class in pyqt5 in order to make a drop down tool bar which will expand and collapse.The qtool button will have qpushbutton as its items.When a user will click the qtoolbutton the qpushbutton will be displayed.
The problem i am having is that when a collapsable tool button has qtool button as it items, the child qtool button items overlaps with the buttons of the parent qtool button as a result they cannot be properly displayed in the layout.
from PyQt5 import QtCore, QtGui, QtWidgets

class CollapsibleBox(QtWidgets.QWidget):
    def __init__(self, title="", parent=None):
        super(CollapsibleBox, self).__init__(parent)

        self.toggle_button = QtWidgets.QToolButton(text=title, checkable=True, checked=False)
        self.toggle_button.setStyleSheet("QToolButton {background-color:#dadada;}")
        self.toggle_button.setToolButtonStyle(QtCore.Qt.ToolButtonTextBesideIcon)
        self.toggle_button.setArrowType(QtCore.Qt.ArrowType.RightArrow)
        self.toggle_button.pressed.connect(self.on_pressed)

        self.toggle_animation = QtCore.QParallelAnimationGroup(self)

        self.content_area = QtWidgets.QScrollArea(maximumHeight=0, minimumHeight=0)
        self.content_area.setSizePolicy(QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Fixed)
        self.content_area.setFrameShape(QtWidgets.QFrame.NoFrame)

        lay = QtWidgets.QVBoxLayout(self)
        lay.setSpacing(0)
        lay.setContentsMargins(0, 0, 0, 0)
        lay.addWidget(self.toggle_button)
        lay.addWidget(self.content_area)

        self.toggle_animation.addAnimation(QtCore.QPropertyAnimation(self, b"minimumHeight"))
        self.toggle_animation.addAnimation(QtCore.QPropertyAnimation(self, b"maximumHeight"))
        self.toggle_animation.addAnimation(QtCore.QPropertyAnimation(self.content_area, b"maximumHeight"))

    @QtCore.pyqtSlot()
    def on_pressed(self):
        checked = self.toggle_button.isChecked()
        self.toggle_button.setArrowType(QtCore.Qt.ArrowType.DownArrow if not checked else QtCore.Qt.ArrowType.RightArrow)
        self.toggle_animation.setDirection(QtCore.QAbstractAnimation.Forward if not checked else QtCore.QAbstractAnimation.Backward)
        self.toggle_animation.start()

    def setContentLayout(self, layout):
        lay = self.content_area.layout()
        del lay
        self.content_area.setLayout(layout)
        collapsed_height = self.sizeHint().height() - self.content_area.maximumHeight()
        content_height = layout.sizeHint().height()
        for i in range(self.toggle_animation.animationCount()):
            animation = self.toggle_animation.animationAt(i)
            animation.setDuration(500)
            animation.setStartValue(collapsed_height)
            animation.setEndValue(collapsed_height + content_height)

        content_animation = self.toggle_animation.animationAt(self.toggle_animation.animationCount() - 1)
        content_animation.setDuration(500)
        content_animation.setStartValue(0)
        content_animation.setEndValue(content_height)

if __name__ == '__main__':
    import sys
    import random

    app = QtWidgets.QApplication(sys.argv)

    w = QtWidgets.QMainWindow()
    w.setCentralWidget(QtWidgets.QWidget())
    dock = QtWidgets.QDockWidget("Collapsible Demo")
    w.addDockWidget(QtCore.Qt.LeftDockWidgetArea, dock)
    scroll = QtWidgets.QScrollArea()
    dock.setWidget(scroll)
    content = QtWidgets.QWidget()
    content.setStyleSheet("background-color:white")
    scroll.setWidget(content)
    scroll.setWidgetResizable(True)
    vlay = QtWidgets.QVBoxLayout(content)

    towerGeometry = CollapsibleBox("Tower Geometry")

    vlay.addWidget(towerGeometry)
    layoutForTowerGeometry = QtWidgets.QVBoxLayout()
    section = QtWidgets.QPushButton("Sections")

    section.setStyleSheet("background-color: #dadada ;")
    layoutForTowerGeometry.addWidget(section)
    towerGeometry.setContentLayout(layoutForTowerGeometry)

    #Header for Input

    flanges = CollapsibleBox("Flanges")
    layoutForGeometryParameters = QtWidgets.QVBoxLayout()
    geometryParameters = QtWidgets.QPushButton("Geometry Parameters")

    geometryParameters.setStyleSheet("background-color: #dadada ;")
    layoutForGeometryParameters.addWidget(geometryParameters)
    flanges.setContentLayout(layoutForGeometryParameters)

    guidanceInfo = QtWidgets.QPushButton("Guidance Info")

    guidanceInfo.setStyleSheet("background-color: #dadada ;")
    layoutForGeometryParameters.addWidget(guidanceInfo)
    flanges.setContentLayout(layoutForGeometryParameters)
    layoutForTowerGeometry.addWidget(flanges)
    towerGeometry.setContentLayout(layoutForTowerGeometry)

    cans = QtWidgets.QPushButton("Cans")

    cans.setStyleSheet("background-color: #dadada ;")
    layoutForTowerGeometry.addWidget(cans)
    towerGeometry.setContentLayout(layoutForTowerGeometry)

    vlay.addStretch()
    w.resize(640, 480)
    w.show()
    sys.exit(app.exec_())

A: When you set the layout, you set also the maximum height of the widget based on the size of its content. But, it will not grow or shrink if its content is resized. Especially when you expand the second box.
Don't modify the size of your widget directly. Create a new class which will manages the content and let you change its size:
A simple example:
class Container(QWidget):
    def __init__(self, parent=None):
        super().__init__(parent)
        self.expanded = False
        self.setFixedHeight(0)

    def setExpand(self, expanded):
        self.expanded = expanded
        if expanded:
            self.setMinimumHeight(0)
            self.setMaximumHeight(0)
        else:
            self.setMinimumHeight(self.sizeHint().height())
            self.setMaximumHeight(QWIDGETSIZE_MAX)

class CollapsibleBox(QtWidgets.QWidget):
    def __init__(self, title="", parent=None):
        super(CollapsibleBox, self).__init__(parent)
        self.toggle_button = QtWidgets.QToolButton(text=title, checkable=True, checked=False)
        self.toggle_button.setStyleSheet("QToolButton {background-color:#dadada;}")
        self.toggle_button.setToolButtonStyle(QtCore.Qt.ToolButtonTextBesideIcon)
        self.toggle_button.pressed.connect(self.on_pressed)

        self.toggle_animation = QtCore.QParallelAnimationGroup(self)

        self.content_area = Container()

        self.lay = QtWidgets.QVBoxLayout(self)
        self.lay.setSpacing(0)
        self.lay.setContentsMargins(0, 0, 0, 0)
        self.lay.addWidget(self.toggle_button)
        self.lay.addWidget(self.content_area)
        self.lay.setAlignment(Qt.AlignTop)

    @QtCore.pyqtSlot()
    def on_pressed(self):
        self.adjustSize()
        self.content_area.setExpand(self.toggle_button.isChecked())

    def setContentLayout(self, layout):
        l = self.content_area.layout()
        del l
        self.content_area.setLayout(layout)


text:
Q: Issue with FTX US API I have looked through the FTX API documentation found here: https://docs.ftx.us/#overview
And I've looked at the example code found in this repo: https://github.com/ftexchange/ftx/tree/master/rest
I can't get or post anything that requires Authentication. I am using the API key on my account that has 'full trade permissions', and when I look at print(request.headers) the headers look like they are in the right format.
Let me know if you need any more information, my code returns
Error Code: 400 Invalid API Key
            import time
            import hmac
            from requests import Request

            ts = int(time.time() * 1000)
            request = Request('GET', 'https://ftx/api/wallet/balances')
            prepared = request.prepare()
            signature_payload = f'{ts}{prepared.method}{prepared.path_url}'.encode()
            signature = hmac.new('API SECRET'.encode(), signature_payload, 'sha256').hexdigest()

            request.headers[f'FTXUS-KEY'] = API KEY'
            request.headers[f'FTXUS-SIGN'] = signature
            request.headers[f'FTXUS-TS'] = str(ts)

            res = requests.get('https://ftx/api/wallet/balances', headers=prepared.headers)
            r = res.json()

A: I also got this error and It was a silly mistake.
I think you have FTX.US API Key and you are hitting on 'https://ftx/api/wallet/balances'.  U should hit on 'https://ftx.us/api/wallet/balances'  to get this working


text:
Q: Are two java files in a directory considered a "package?" I have a directory that contains the following :
1) A.java
2) B.java
Is this all that is required in order to call my directory a java 'package'? What if I compile both of them resulting in a directory with two additional .class files? Can it be considered a package then or are there other requirements/actions to take?

A: The files must begin with a package declaration that matches the directory in which they are located.
For example :
package com.something;
if the files are located under com/something.
com/
    something/
        A.java
        B.java

A: To be in the same package, the files must both contain the line:
package com.example.samepackage;

(for example)

A: Package is like directory structure but don't confuse it with window's or other OS' folder.
Just consider package as a package of files.
Just write:
package anything;
as the top most line in your program. All the files have same package name will be placed in the same "anything" package and hence can be used for further implementation like "import amything;" if you want to use those files in any other program and then use those files' structure.


text:
Q: How pass this values in PHP I think this is a very basic question, but I am searching for two hours and can't find anything what works :-(
I have a Drupal Webform to collect personal information about my users and send it to another page with Drupal module "Webform Remote Post" (It removes "submitted").
The name attributes of the input tags look like this:
<input name="submitted[address]">

I can use this data in PHP like this:
$address = $_POST['address'];

But the problem are the Date fields. Here the name attributes look like this:
EDIT: It is an select element!
<select name="submitted[date][day]">

EDIT: I already tried this:
$day = $_POST['date']['day'];

How can I get the day value with $_Post?
Thank you!


text:
Q: Does Uber Eats have an API and if so where can I found out more information Does Uber Eats have an API and if so where can I found out more information.
I know I can integrate with Uber just wondering on the logistics with uber eats and would like to be able to integrate with current platform.

A: This post might be helpful. It looks like "the external API does not support UberEATS" as of March 30th and that there is no way to tell if a certain Uber ride ID is UberEATS or not. Seems it might be in the works, though.


text:
Q: Getting error while trying to run application in play framework I am new to play framework.I am trying to run an application like this
$ play eclipse
Error during sbt execution: Could not find configuration file 'd:/play/framework
/sbt/sbt.boot.properties'.  Searched:
        file:/c:/Users/Alok/test-app/
        file:/C:/Users/Alok/
        file:/D:/play/framework/sbt/

I searched a lot and got some solution but it is not working.I am using play version 2.2.1
Thanks

A: @Chris Beach linked to the answer, but it is better to have the explanation directly here:
Play cannot be run from the Git shell so in case you're using it (I was) you've got to switch to the standard Windows command line.

A: Check out this discussion on the play-framework Google Group:
https://groups.google.com/d/topic/play-framework/CN0L5AaBxwg/discussion


text:
Q: Target of URI doesn't exist:'package:flutter_screenutil/flutter_screenutil.dart' on adding flutter_screenutil package version 1.0.2 ,the "target of URI doesn't exist" error is being showed i have tried the latest  flutter_screenutil: ^4.0.2+1 package also but both give the same error . How to solve this error

A: I assume youre using Visual Studio Code.
Restarting Visual Studio Code after
flutter pub get

This will do it.
You can also check the library of flutter on using packages
https://flutter.dev/docs/development/packages-and-plugins/using-packages


text:
Q: There is a 5 by 5 matrix of points on a plane. How many triangles can be formed using points on this matrix? There is a 5 by 5 matrix of points on a plane. How many triangles can be formed using points on this matrix?

A: This is the obvious approach (to me, at least), and is mostly a matter of bookkeeping.  To begin with, there are ${{5^2} \choose 3}$ sets of three points.  However, some of these are colinear, which we don't want to count.
There are $2 \times 5 \times {5 \choose 3}$ horizontal or vertical sets of three colinear points.  E.g.
 .xxx.   .....
 .....   ...x.
 .....   ...x.
 .....   .....
 .....   ...x.

There are $3+3+3+3$ sets of three colinear points with rise/run $\in {\pm 2, \pm 1/2}$.
 x....   ..x..
 ..x..   .....
 ....x   ...x.
 .....   .....
 .....   ....x

 ...x.   .....
 .....   ....x
 ..x..   ..x..
 .....   x....
 .x...   .....

There are $2 \times {5 \choose 3}$ sets of three colinear points with rise/run $\in {\pm 1}$ along the main diagonal or main anti-diagonal.
 x....   .....
 .x...   ...x.
 ..x..   ..x..
 .....   .....
 .....   x....

There are $4 \times {4 \choose 3}$ sets of three colinear points along the "shunted" main diagonal and main anti-diagonal (is there a better name for these diagonals?).
 .x...   ...x.   .....   .....
 .....   ..x..   x....   .....
 ...x.   .....   .x...   ...x.
 ....x   x....   ..x..   ..x..
 .....   .....   .....   .x...

Finally, there are these $4$ remaining:
 ..x..   ..x..   .....   .....
 .x...   ...x.   .....   .....
 x....   ....x   x....   ....x
 .....   .....   .x...   ...x.
 .....   .....   ..x..   ..x..

So there are \[{{5^2} \choose 3}-2 \times 5 \times {5 \choose 3}-(3+3+3+3)-2{5 \choose 3}-4{4 \choose 3}-4=2148\] triangles that can be formed.  I also checked this answer with some code in GAP.
[Here, I have assumed that you want to count congruent triangles separately.]


text:
Q: my jaxb hello world can run in eclipse but cannot in firefox Sorry my bad english, I has a simple japplet that read XML file by JAXB, it can work when testing in Eclipse.
But it show the exception when running in Firefox. what is it?

A: The error clearly states that it is not able to find out the class definition. You are missing the jaxb-impl-X.X.X.jar in your classpath. Where X.X.X means the version of your jar. Hope this helps


text:
Q: mariadb cannot start with error i'd rebooted server.
and mariadb did not started automatically.
so i'd type service mysqld start. but shows me cannot start with error.
mariadb cannot start with collation error
i wanna start without error
i'm using centos 6.5
**# mysql --version**
mysql  Ver 15.1 Distrib 10.1.19-MariaDB, for Linux (x86_64) using readline 5.1

**# ./mysqld_safe &**
mysqld_safe Logging to '/var/lib/mysql/localhost.localdomain.err'

**localhost.localdomain.err shows me**
mysqld_safe mysqld from pid file /var/lib/mysql/localhost.localdomain.pid ended
mysqld_safe Starting mysqld daemon with databases from /var/lib/mysql
[Warning] '--skip-locking' is deprecated and will be removed in a future release. Please use '--skip-external-locking' instead.
[ERROR] Unknown collation: 'utf8mb4_unicode_ci'
[ERROR] Aborting
[Note] /usr/libexec/mysqld: Shutdown complete

**my.cnf**
[client]
default-character-set=utf8mb4

[mysql]
default-character-set=utf8mb4

[mysqld]
collation-server = utf8mb4_unicode_ci
character-set-server = utf8mb4

A: Add
skip-character-set-client-handshake

under mysqld in my.cnf to resolve any conflicts if collation is set via startup-options.
https://dev.mysql.com/doc/refman/5.7/en/charset-server.html

A: Whatever server you have on that machine, it is not MariaDB 10.1. mysql --version only shows the client version, and it is indeed MariaDB 10.1, but the server is not.
MariaDB 10.1 wouldn't have thrown a warning upon skip-locking, it would have been an error, because this option had been removed long before 10.1. It doesn't even exist in 5.5.
What you most likely have is MySQL 5.1, which is still provided on CentOS 6. Maybe you tried to install MariaDB over it and it didn't go well, or something similar happened.
MySQL 5.1 does not have utf8mb4, so the error makes sense, although I would expect it to fail on character-set-server. It is possible that you have another config somewhere else which overrides character-set-server (and adds skip-locking which is not present in your paste, but it must come from somewhere).


text:
Q: javafx ListChangeListener.Change abstract methods implementation The methods next , getFrom, getTo, getRemoved ... in the Change class from javafx.collections.ListChangeListener interface are declared abstract. The following excerpt is from the interface.
public interface ListChangeListener<E> {

    public abstract static class Change<E>{
        public abstract boolean next();
        public abstract void reset();

        public void Change(ObservableList<E> list){
            this.list = list;
        }

        public abstract int getFrom();
        //... some more methods
    }
    public void onChanged(Change<? extends E> c);
}

If I have a class to observe changes to an observable list
import javafx.beans.Observable;
import javafx.beans.property.IntegerProperty;
import javafx.beans.property.SimpleIntegerProperty;
import javafx.collections.FXCollections;
import javafx.collections.ListChangeListener;
import javafx.collections.ObservableList;
import javafx.util.Callback;

// A class to detect changes in an observable list
public class ChangeQuery {
    static IntegerProperty E1;
    static IntegerProperty E2;
    public static void main(String[] args) {
        Callback<IntegerProperty, Observable[]> extractor = (IntegerProperty p) -> {
        System.out.println("Extracted :" + p);
        return new Observable[] {p};
    };

    ObservableList<IntegerProperty> list = FXCollections.observableArrayList(extractor);

    list.addListener(ChangeQuery::onChanged);
    E1 = new SimpleIntegerProperty(11);
    E2 = new SimpleIntegerProperty(22);

    list.add(E1);
    list.add(E2);
    E1.set(111);
}

public static void onChanged(ListChangeListener.Change<? extends IntegerProperty> change) {
    System.out.println("GetList: " + change.getList());

    while (change.next()) {
        System.out.println(
                "index [" + change.getFrom() + "] to " + "[" + change.getTo() + "]" ); // change.getFrom() implementation
        if (change.wasPermutated()) {
            System.out.println("Permutated is true");
        } else if (change.wasUpdated()) {
            System.out.println("Update == true");
        } else if (change.wasReplaced()) {
            System.out.println("removed and added == true");
        } else if (change.wasRemoved()){
            System.out.println("removed");
        } else if (change.wasAdded()) {
            System.out.println("Added");
        }
    }
}
}

How is, for example the change.getFrom() method implemented. I have checked the javafx.collection package but found no such implementation or perharps I missed something. Thanks in advance for the help.


text:
Q: Changing style of file browse button (MyFaces inputFileUpload) my task is to implement a CSS style to a submit button of a file upload widget. I decided to make an original widget invisible and to add text field and button which are visible and have the styles I need and can use a functionality of the original widget.
<t:inputFileUpload id="fileupload" style="display:none" value="#{Handler.upFile}" accept="application/pdf,image   /tiff"    onchange="Handlechange();"/>

<input type="text" id="filename" class="input400px"  readonly = "readonly"/>
<input type="button" id="fakeBrowse" class="browseButton" value="Browse..." onclick="HandleBrowseClick();"/>

function HandleBrowseClick()
{
    var fileinput = document.getElementById("uploadForm:fileupload");
    fileinput.click();
}

function Handlechange()
{

var fileinput = document.getElementById("uploadForm:fileupload");
var textinput = document.getElementById("filename");
textinput.value = fileinput.value;

}

It works in Firefox, but not in IE. I suppose that click() doesn't work properly in IE. Has anyone ideas how I can solve a problem for IE and why it doesn't work there? Thank you.


text:
Q: How do you process xml columns and check every xml entries with MSSQL? <Standard>
  <Equip Cat="Hardware">10 TB Disk</Equip>
  <Equip Cat="Hardware">USB 2.0</Equip>
</Standard>

I have a column called XML in a table called Product. The type is XML(.), and I am wondering how I can process the xml column.
The big issue is that I have no idea how to do a foreach in a XML column.
I want to add a row if my stored procedure detects the substring "10 TB" inside of the category "Hardware"inside the table called ProductFeature with the id from table Product in the column id and true inside of the column HighDiskSpace.

A: Here is a conceptual example for you.
It is using XQuery .exist() method. Its XPath predicate expression satisfies your question requirements. Both variables, @cat and @searchString, could be your stored procedure parameters.
SQL
-- DDL and sample data population, start
DECLARE @Product TABLE (ID INT IDENTITY PRIMARY KEY, xmldata XML);
INSERT INTO @Product (xmldata) VALUES
(N'<Standard>
  <Equip Cat="Hardware">10 TB Disk</Equip>
  <Equip Cat="Hardware">USB 2.0</Equip>
</Standard>');
-- DDL and sample data population, end

DECLARE @cat VARCHAR(30) = 'Hardware'
    , @searchString VARCHAR(30) = '10 TB';

SELECT *
FROM @Product
WHERE xmldata.exist('(/Standard/Equip[@Cat=sql:variable("@cat")
    and contains(./text()[1], sql:variable("@searchString"))])[1]') = 1;


text:
Q: website inserting pics Hello i am getting this error message :

Object reference not set to an instance of an object.
  Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
  Exception Details: System.NullReferenceException: Object reference not set to an instance of an object.

Source Error:
Line 7:
Line 8:      Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Line 9:          UserIdValue.Text = Membership.GetUser().ProviderUserKey.ToString()
Line 10:         cannotUploadImageMessage.Visible = False
Line 11:     End Sub

can someone help me with this?

A: That's a pretty straightforward error to debug. The error message should tell you exactly which line it's on (either 9 or 10). It's just a matter of setting a breakpoint on that line and running the page, then working out which object hasn't been set by hovering your mouse over each object.


text:
Q: ICD loader reports not usable format after installing OpenCL I installed OpenCL on my Ubuntu 14.04 using this link: http://yuleiming.com/install-intel-opencl-on-ubuntu-14-04/ However when I followed last step:
sudo clinfo | grep Intel

I got the following error:
ICD loader reports not usable format

What might have gone wrong? I've also installed clinfo.

A: I read the guide you followed and it installs the old OpenCL Driver for Inetl CPUS. I have list down steps for the latest OpenCL Driver:

*

*install rpm

sudo apt-get install -y rpm alien libnuma1

*install clinfo utility

sudo apt-get install clinfo

*download and install the OpenCL™ Runtime for Intel® Core™ and Intel® Xeon® Processors

wget -c http://registrationcenter-download.intel.com/akdlm/irc_nas/9019/opencl_runtime_16.1.1_x64_ubuntu_6.4.0.25.tgz
tar xvzf opencl_runtime_16.1.1_x64_ubuntu_6.4.0.25.tgz
cd opencl_runtime_16.1.1_x64_ubuntu_6.4.0.25
sudo rpm --import PUBLIC_KEY.PUB
cd rpm
fakeroot alien --to-deb opencl-1.2-base-6.4.0.25-1.x86_64.rpm
fakeroot alien --to-deb opencl-1.2-intel-cpu-6.4.0.25-1.x86_64.rpm
sudo dpkg -i opencl-1.2-base_6.4.0.25-2_amd64.deb
sudo dpkg -i opencl-1.2-intel-cpu_6.4.0.25-2_amd64.deb

>
sudo nano /etc/ld.so.conf.d/intelOpenCL.conf
and add the following line -> /opt/intel/intel-opencl-1.2-6.0.0.1049/lib64

*

*create a symbolic link for Intel ICD

sudo ln /opt/intel/opencl-1.2-6.4.0.25/etc/intel64.icd /etc/OpenCL/vendors/intel64.icd
sudo ldconfig

*Now you can check Intel OpenCL with clinfo

sudo clinfo | grep Intel

Now, you can proceed with OpenCL SDK installation.


text:
Q: Ehcache not evicting cached entries Main question is does ehcahce 2.6.2 do ANY eviction of expired elements based on ehcache configuration; or do I have to evict programatcially?
After reading various parts of the documentation (data life and cache sizing) we set the current configuration to use TTI/TTL and a CacheManager level maxBytesLocalHeap=1024m. After setting this I would expect ehcache to only use up to 1Gb of heap space for caching, but from testing (and prodcution) we consistently see the JVM heap get full (2GB in our case)
Ehcache doesn't seem to honor the maxBytesLcoalHeap setting we set. Unless of course I (which is likely) dont' understand what this setting is actually doing.
Some notes from our admins:

During this test, the maxBytesLocalHeap value was 1024m which should have limited cache entries and references to 1GB total for the entire cache management pool.  The 8 individual caches were configured to use a portion of the 1024m.  The heap utilization climbed up in a steady fashion to the max heap size of 2GB.  Once there, garbage collection took longer and response times degraded.  The max heap size did not decrease after the test was over.  In fact, it is roughly 30 hours after the end of the test, I cleared all cache entries via the CacheManagement page and allowed the JVM to settle over night, and the heap is still committed to 2GB.  The use of the Old Generation space is flat with no room to spare.  The use of the Young Generation space came down some after I cleared cache entries, but that was only about 240MB and the committed space did not reduce.

Thanks for your help and guidance!
Updated
ehcahce configuration
<?xml version="1.0" encoding="UTF-8"?>
<ehcache>

 <cache name="storeCache"
   maxElementsInMemory="2500"
   memoryStoreEvictionPolicy="LFU"
   eternal="false"
   timeToLiveSeconds="86400"
   statistics="true">
   <persistence strategy="none" />
</cache>

<cache name="courseCache"
   maxElementsInMemory="100000"
   memoryStoreEvictionPolicy="LFU"
   eternal="false"
   timeToLiveSeconds="43200"
   statistics="true">
   <persistence strategy="none" />
</cache>

<cache name="mtcIdCache"
   maxElementsInMemory="500000"
   memoryStoreEvictionPolicy="LFU"
   eternal="false"
   timeToLiveSeconds="3600"
   statistics="true">
   <persistence strategy="none" />
</cache>

<cache name="catentryCache"
   maxElementsInMemory="500000"
   memoryStoreEvictionPolicy="LFU"
   eternal="false"
   timeToLiveSeconds="3600"
   statistics="true">
   <persistence strategy="none" />
</cache>

<cache name="priceCache"
   maxElementsInMemory="500000"
   memoryStoreEvictionPolicy="LFU"
   eternal="false"
   timeToLiveSeconds="300"
   statistics="true">
   <persistence strategy="none" />
</cache>

<cache name="inventoryCache"
   maxElementsInMemory="500000"
   memoryStoreEvictionPolicy="LFU"
   eternal="false"
   timeToLiveSeconds="300"
   statistics="true">
   <persistence strategy="none" />
</cache>

<cache name="attributeCache"
   maxElementsInMemory="500000"
   memoryStoreEvictionPolicy="LFU"
   eternal="false"
   timeToLiveSeconds="300"
   statistics="true">
   <persistence strategy="none" />
</cache>

<cache name="partnerCache"
   maxElementsInMemory="10000"
   memoryStoreEvictionPolicy="LFU"
   eternal="false"
   timeToLiveSeconds="86400"
   statistics="true">
   <persistence strategy="none" />
</cache>
</ehcache>

** 2nd update **
This is what our admin says about the heap utilization

I have taken two memory snapshots for websvc01 JVM in relation to this endurance test.  They are available in dynaTrace for Monday 09/09 @ 10:10:59 and Tuesday 09/10 @ 10:46:48.  Both snapshots are Deep Memory Leak Analysis snapshots with capturing valued of string objects.
During this test, the maxBytesLocalHeap value was 1024m which should have limited cache entries and references to 1GB total for the entire cache management pool.  The 8 individual caches were configured to use a portion of the 1024m.  The heap utilization climbed up in a steady fashion to the max heap size of 2GB.  Once there, garbage collection took longer and response times degraded.  The max heap size did not decrease after the test was over.  In fact, it is roughly 30 hours after the end of the test, I cleared all cache entries via the CacheManagement page and allowed the JVM to settle over night, and the heap is still committed to 2GB.  The use of the Old Generation space is flat with no room to spare.  The use of the Young Generation space came down some after I cleared cache entries, but that was only about 240MB and the committed space did not reduce.

Update:
Thanks for the responses I really appreciate it. I apologize for not updating this question for a while.
Using DynaTrace we were able to determine it is a problem with Spring Integration. Specifically, the SimpleMessageStore seems to be holding onto objects and filling up!

Reading the documentation it seems I should be using a MessageReaper, but even after including this in the configuration I see the same issues. Should I be looking at the Capacity setting for the SimpleMessageStore instead?

A: In your ehcache configuration i do not see any memory limitation if you want specify memory limitation, you have to set the "maxBytesLocalHeap" attribute on the ehcache tag.
Ehcache documentation for more information :
http://ehcache.org/documentation/configuration/cache-size#mixed-sizing-configurations.

A: Instead of 'maxElementsInMemory', use 'maxBytesLocalHeap' in your ehcache cache configuration to limit the heap usage.


text:
Q: Hello World in LLVM-Assembly Language on Windows As an experienced programmer I feel quite dumb asking such a question: Is there a step-by-step tutorial explaining how to write a "Hello World"-Program in LLVM-Assembly Language resulting in a simple "hello.exe" which can be executed on a Standard Windows PC?
I followed dozens of such tutorial explaining how to checkout, make, compile llvm, etc. But either they require some other Software (which results in another tutorial-Marathon), or they ended up with some "Path/File/Dll not found"-Error (which results in another tutorial-Marathon). I achieved to let llvm.exe execute ... once. Now Windows reports the application to be crashing?!
Now I feel completely lost in a maze of outdated tutorials, errors, incompatibilities, emulators/VMs, IDE, Crosslinks, 32 vs. 64-Bit, with/out WinGW, with/out Cygwin, with/out Visual Studio, with/out clang, experimental, not supported, missing Environment-variables etc.
I expected to find an installer or archive containing a bunch of precompiled dll- and exe-files which can be used via command line out of the box. I just want to USE a bare llvm-toolset - no clang, no Visual Studio (if possible) - just like javac.exe, masm.exe, fasm.exe, link.exe, ...
If I have to compile llvm on my own, the possibility to achieve this via Eclipse-CDT would be great - I was unable to import the Project without any FileNotFound-Errors; which was related to some make-specific incompatibilities regarding the directory structure ... cmake should have solved that problem, but the only tutorial I found so far was about cmake-gui - which failed to install for some other reasons ...
Can someone please point me to an up-to-date tutorial on how to get a working llvm-as.exe or write a step-by-step-instruction how he/she achieved the above?
Thanks in advance - I lost three days on this so far :/

A: LLVM historically had second-rate support on Windows, but quite recently things have changed so you have good timing. Check out this LLVM blog post from just a month ago. It points to this page with binary builds of the LLVM toolchain for Windows. Once you have the tools, then the flow to a "hello world" is similar to other platforms. It would be a good idea to start with the LLVM tutorial.
FWIW there's also a getting started on Windows guide, though I'm not sure how up to date it is w.r.t the blog post mentioned above. It does create a "hello world" LLVM IR file in the process, though.


text:
Q: Is it okay to take \$\beta=I_c/I_b=98/2\$ in this problem?
In an npn power transistor the collector current is 20mA. If 98 percent of
  the electrons injected into base region reach collector then the base
  current in mA is nearly ?

Here, in this problem is it okay to take \$\beta=I_c/I_b=98/2=49\$ ?

A: It sounds like they mean 98% of the emitter current, not the base current. That means you're given \$\alpha = 0.98\$. You can use that to calculate \$\beta\$ and find the base current.

A: You don't need to know \$\beta\$ to answer the question. Just Kirchoff's Current Law.


text:
Q: Is it safe to connect (select, update, insert) to Oracle database 10G with a 11G client? I have to work in an Oracle 10G database. The normally used client is Oracle SQLDeveloper. But it has some limitations not related to the database use (Java versions on my PC, but that is another story). So I have to use another client.
DBeaver looks like a good candidate, but when configuring a database connection, the current version (3.5.8, zip without added Java) only has options for 11G or 12G.
There is a lot of info on the net about the differences, but not to such detail as to make it clear of backwards compatibility of 11G to 10G.
Is it safe to just choose the 11G and try it out on a 10G database? Seems too risky to me for update and insert, so probably here is someone already tried that. Or probably there is a possibility to get a 10G connection available in current DBeaver?

A: It depends on the exact versions:

*

*Using 11g Client with 10g Database says

"Metalink 207303.1 is the client/server interoperability matrix. If by 11g you mean 11.2 and by 10g you mean 10.1, the 11.2 client will not work with a 10.1 database. If the client is 11.2 and the database is 10.2, it should be at least 10.2.0.2. If the client is 11.1, the database should be 10.1.0.5 or 10.2.0.2 or higher."

*Is it ok to use oracle 11g client with a 10g server? agrees with that (with less detail)


text:
Q: Change uitextfield background color to grey iphone sdk I use [txtfld setBackgroundColor:[UIColor greyColor]] but the compiler sais may not respond and crashes not working!
How can i make the background color grey?

A: there is a thread that indicates there is a problem if the field has rounded corners
http://icodeblog.com/2010/01/04/uitextfield-a-complete-api-overview/


text:
Q: Angularjs fallback, hide for none javascript users I know about the script-tag for adding content that none javascript users can read.
What is the best way to hide html blocks that is created for angularjs?
Example:

{{this_code_is_converted_to_angular_js_code_when_javascript_is_active}}

The line above is not that beautiful for a none javascript user. What is the best way to remove it if the user is not using javascript?

A: Use the  tag to display content when JavaScript is not enabled.
Also the main.html file should not have any {{content}} tags, instead you should have sub views which are loaded into the

This way if JavaScript is not enabled, only content in the noscript tag will be displayed because the ng-view div is empty, as AngularJS is JavaScript and will never insert anything into the ng-view div.
Example HTML
<!DOCTYPE html>

  <meta charset="utf-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <title>My AngularJS App</title>
  <meta name="description" content="">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" href="bower_components/html5-boilerplate/css/normalize.css">
  <link rel="stylesheet" href="bower_components/html5-boilerplate/css/main.css">
  <link rel="stylesheet" href="css/app.css"/>

  Enable JavaScript to view this web page.

A: If you just want to hide elements you can use ng-cloak
https://docs.angularjs.org/api/ng/directive/ngCloak

A: You have a few options...
Since you specifically don't want to display HTML block for NON-Angular (non-javascript), then you should ONLY place that HTML code within either:

*

*use ngBindTemplate (preferred):

 Salutation: <input type="text" ng-model="salutation">

 Name: <input type="text" ng-model="name">

*or... ngBind:

  Enter name: <input type="text" ng-model="name">

  Hello !

The main difference being that "...unlike ngBind, the ngBindTemplate can contain multiple {{ }} expressions. This directive is needed since some HTML elements (such as TITLE and OPTION) cannot contain SPAN elements.": https://docs.angularjs.org/api/ng/directive/ngBindTemplate
In your specific example/question:

   {{this_code_is_converted_to_angular_js_code_when_javascript_is_active}}

A: I don't know if this is what you are looking for but if you don't want to display {{ }} marks in your page when javascript is not enabled you should try using ng-bind and/or ng-bind-template instead.


text:
Q: How to create a hidden  in JavaScript? How can you make a simple tag like  hidden programmatically using JavaScript?

A: I'm not sure I understand your question.  But there are two approaches to making the image invisible...
Pure HTML

Or...
HTML + Javascript

A: You can hide an image using javascript like this:
document.images['imageName'].style.visibility = hidden;

If that isn't what you are after, you need to explain yourself more clearly.

A: How about

That will disable the display completely, and not leave a placeholder

A: This question is vague, but if you want to make the image with Javascript.
It is simple.
function loadImages(src) {
  if (document.images) {
    img1 = new Image();
    img1.src = src;
}
loadImages("image.jpg");

The image will be requested but until you show it it will never be displayed.
great for pre loading images you expect to be requests but delaying it until the document is loaded.
Example

A: Try setting the style to display=none:


text:
Q: In KendoUI Grid - make grid using C# viewModel My scenario is , I've controller which is passing ViewModel Object to view .
For one model we can return json array from controller . but what for multiple objects case like ViewModel  And the thing is that for each list (In my viewmodel object) i need to make a seperate Grid . Any help will be appreciated .

A: I have done it like this before - in your javascript, you can generate a kendo datasource from the object in your viewmodel:
var yourDataSource = new kendo.data.DataSource({ data: @Html.Raw(Json.Encode(Model.SomeObject)) });
yourDataSource.read();

More often than not though, I wire the up to a service so the loading of the data can by asynchronous, etc...

A: I got the answer of my own question . we can make grid using viewmodel object which further includes multiple objects simply by doing the following code:
@(Html.Kendo().Grid(Model.accountHistory).Name("Account_History").Columns())


text:
Q: Turn a for loop on an object into a .map I have been told my function:
 for (const key of Object.keys(temp)) {
 this.sessionData.push(temp[key]);
 }

Must now use a .map instead,
I have tried this below:
Object.keys(temp).map(function(key) {
  this.sessionData[key];
})

But 1 I don't know if it's actually accurate, and also, it cant access the data outside of the scope of the function it is in, here is the whole function below:
public sessionData;

sessionDates(sessionsData) {
  const temp = {};
  this.sessionData = [];
  sessionsData.forEach(session => {
    const date = moment(session.startDatetime).format('DDMMYYYY');
    if (temp[date]) {
      temp[date].push(session);
    } else {
      temp[date] = [session];
    }
  });

Object.keys(temp).map(function(key) {
  this.sessionData[key];
})

TRYING TO USE THIS BELOW... session data is undefined, it can't access out of the scope?
    Object.keys(temp).map(function(key) {
  this.sessionData[key];
})

But this works..
 for (const key of Object.keys(temp)) {
 this.sessionData.push(temp[key]);
 }

So this new .map method can't access anything out of its scope.. sigh!
If anybody can help that would be amazing! Thanks!

A: In Javascript all functions can access variables from outside (called "higher scope") - it's one of the strengths of the language and is called "capture".
The reason your code is failing is because it's using this.sessionData inside a function declaration, which cases problems because this in javascript is... somewhat complex. But you don't need it!
You also need to make sure you return the value you want to output. Here's how I would write it:
 this.sessionData = Object.keys(temp).map(key => temp[key]);


text:
Q: Check path equivalence using glib I need do check the equivalence of two filepaths using glib. I did it with Qt long time ago, via reduction paths. But I can't find similar instruments in glib.
Can someone suggest the common way to do this?
Thanks

A: For just "simple" canonicalization that resolves use of . and .., just create two GFile objects using the GIO API's g_file_new_for_path() function. Then compare the two files using g_file_equal().
Note that this relies on GIO doing simple canonicalization of the paths when you create the GFile objects; it won't resolve symbolic links. The documentation states:

Using GFile as an identifier has the same weaknesses as using a path in that there may be multiple aliases for the same file. For instance, hard or soft links may cause two different GFiles to refer to the same file. Other possible causes for aliases are: case insensitive filesystems, short and long names on FAT/NTFS, or bind mounts in Linux. If you want to check if two GFiles point to the same file you can query for the G_FILE_ATTRIBUTE_ID_FILE attribute. Note that GFile does some trivial canonicalization of pathnames passed in, so that trivial differences in the path string used at creation (duplicated slashes, slash at end of path, "." or ".." path segments, etc) does not create different GFiles.

So, you can do a two-step approach:

*

*Check with g_file_equal(). If it says true, you're done.

*Else query the G_FILE_ATTRIBUTE_ID_FILE attribute and compare those.


text:
Q: Logical OR in combination with lodash get() gives weird results OK, so I can't wrap my head around this...
I need to find a bankScheme and there is some code before this snippet that might find it so I have set it to ABC to illustrate that the value was found.
If it still wasn't found I wanted to try to find it from some other data, object j in the snippet below but as object j might not contain PaymentMeans I used the lodash _.get() to fetch the value (in the real object the path is much "deeper").
const _ = require('lodash');

let j = { PaymentMeans: '12' };
let bankScheme = 'ABC';
// Let's try the OR operand with a lodash function:
bankScheme = bankScheme || _.get(j, 'PaymentMeans') === '58' ? '58Found' : '58NotFound';

console.log(_.get(j, 'PaymentMeans'), bankScheme);
// It now logs '12 58Found' which is very weird as it should log 'ABC' in any case, and even if it didn't find 'ABC' it should log '58NotFound'...
// If however bankScheme = null then the _.get() works as expected

The weird thing here is, firstly, that the logical OR (||) is not doing what I would expect it to, and that is to leave the value as ABC as it is not "falsy" to begin with.
Secondly, if we accept that the OR is not working, the return should be 58NotFound but now it is 58Found...
What am I missing?
Writing it as this works as expceted though:
bankScheme = bankScheme ? bankScheme : _.get(j, 'PaymentMeans') === '58' ? '58Found' : '58NotFound';

Code: https://repl.it/join/hjqoaatb-anderswa

A: Don't forget about the operator priority.
This
bankScheme = bankScheme || _.get(j, 'PaymentMeans') === '58' ? '58Found' : '58NotFound';

is equivalent to this:
bankScheme = (bankScheme || _.get(j, 'PaymentMeans') === '58') ? '58Found' : '58NotFound';

A: You need to group correctly.
bankScheme = bankScheme || (_.get(j, 'PaymentMeans') === '58' ? '58Found' : '58NotFound');

You can find a good read about operator priorities here.


text:
Q: MS Access - Query - Replace value One of the fields contains ID of partner organisations. Wherever the field is populated it's one of the partner organisations. If the field is blank, it means it's the parent company. In my query, how can I populate the blank records with the ID of the parent company?
The only thing I found was to create an expression in a new field:
 SELECT Valid_Learner.LearnRefNumber, Valid_Learner.FamilyName, Valid_Learner.GivenNames, Valid_Learner.DateOfBirth, Valid_Learner.Ethnicity, Valid_LearningDelivery.FundModel, Valid_LearningDelivery.PartnerUKPRN,
Replace([PartnerUKPRN],"","parentComanyID") AS UKPRN,
Valid_LearningDelivery.DelLocPostCode, Valid_LearningDelivery.LearnAimRef
FROM Valid_Learner RIGHT JOIN Valid_LearningDelivery ON Valid_Learner.LearnRefNumber = Valid_LearningDelivery.LearnRefNumber;

The new field ("UKPRN") should (for the purpose of this question) have the string "parentCompanyID" whenever it's blank in the PartnerUKPRN field.
The result is the UKPRN field displays IDs where the ID is present in the PartnerUKPRN field, but shows "#Error" where it's blank in PartnerUKPRN.

A: If "blank" means NULL, then you can use NZ() in MS Access:
NZ([PartnerUKPRN], "parentComanyID") AS UKPRN

This would be the "normal" way to write this logic.  I don't know why REPLACE() would return an error.


text:
Q: Swift GCDAsyncSocket acceptOnPort:Error: not opening a port? I'm using Xcode beta 3 on 10.9 to write a server using GCDAsyncSocket.  The following code returns true and doesn't produce an error, but Network Utility says that port 5050 is not open.
var tcpSocket = GCDAsyncSocket(delegate: self, delegateQueue: dispatch_get_main_queue())

let lPort: UInt16 = 5050;
var listenError : NSError?
let listening = tcpSocket.acceptOnPort(lPort, error: &listenError)
if listenError {
    println("Error opening listen socket \(listenError!.localizedDescription)")
} else {
    println("Opened listen port")
}

On the same machine, in the same version of Xcode, the ObjC equivalent runs fine and opens a port on 5050.  Is there a problem with my code, GCDAsyncSocket, Swift or Xcode?
TIA.

A: I was seeing this same problem. As a workaround, specifying the listening port as 0 which lets the OS pick the port to use seems to work for me.


text:
Q: Search through an Access Table Column with VBA and return the ID of the searched entry I have an Access Database (not made by me) that contains all the projects of my company. Right now I am trying to automate the way we make new entries into that Database by using VBA. The data we input are taken from excel files and VBA is an easy way to connect those two.
However, I am encountering a problem into pasting the values from excel to an access form because some of the comboboxes in that form are linked to table queries and for some reason using combobox.value = "excel value" doesn/t work. I realised that that in order to make it work I have to find the ID of the value I want to transfer from excel.
Long story short:
Is there a way to look for a specific value in an Access Table Column with VBA and return the ID Number (Primary Key column) of that value ? FYI I have limited knowledge of Access

A: The DLookup() function does this.
strProjectName = "excel value"
myID = DLookup("ID", "myTable", "ProjectName = '" & strProjectName & "'")

But this will only work if the criteria values are unique (no duplicates).
Usually you wrap DLookup with Nz() to handle NULL results, if the value is not found.