text:
Q: How to set height of content with jQuery – cut off in small window size I'm having trouble getting this to work. Currently, it's resizing section[role="main"] to the height properly, but when you resize the window to a small size, it cuts off.
<script type="text/javascript">
    $(function(){
        $('section[role="main"]') .css({'height': (($(window).height()))+'px'});
        $(window).resize(function(){
            $('section[role="main"]') .css({'height': (($(window).height()))+'px'});
        });
    });
</script>

I'm also wondering how I would compensate for the height of the footer? As of now, it is pushing the footer off-screen.
Thanks for any help!
So it should look something like this, Patrick (Updated)?
    <script type="text/javascript">
        $(function(){
            $(window).resize(function(){
                var winheight = $(window).height();
                var heightMinusFooter = winheight - jQuery("#footer").height();
                $('section[role="main"]') .css({'height': heightMinusFooter+'px'});
            });
        });
    </script>

A: Subtract the footer height from the window height then apply.
$(window).resize(function(){
    var winheight = $(window).height();
    var heightMinusFooter = winheight - jQuery("#footer").height();
    $('section[role="main"]') .css({'height': heightMinusFooter+'px'});
});


text:
Q: ASM block into function and ABI x86-64 I coded a very nice integer lib for large integer but limited to 512 bits (faster than GMP for various reason). I am trying to generalize the lib for large size. So I have to loop over an adcq instruction.
// long addition little indian order due the technique incq-jnz
// I can not use compare because it destroy the Carry Bit
template<int n>
void test_add(boost::uint64_t*, boost::uint64_t* ){
    asm volatile (
        "clc                                     \n"
        "movq %0, %%rcx                          \n"
    "loop:                                       \n"
        "movq 8(%%rsi,%%rcx,8), %%rax            \n"  /* original -8(%%rsi,%%rbx,8) */
        "adcq %%rax           , 8(%%rdi,%%rcx,8) \n"  /* original -8(%%rsi,%%rbx,8) */
        "incq %%rcx                              \n"  /* original decq */
    "jnz loop                                    \n"
        :
        :"g"(n)
        :"rax","rcx","cc","memory"
    );
}

int main(int argc, char* argv[]) {
boost::uint64_t c[4],d[4];

c[0] = -1;
c[1] = -1;
c[2] = -1;
c[3] =  0;

d[0] = 1;
d[1] = 0;
d[2] = 0;
d[3] = 0;

test_add<-4>(&d[3],&c[3]); // <-- BigEndian to LittleEndian

This thing works well in debug mode -O0 but as soon as I use optimization, segfault/
I do not really understand because I respect the ABI for rsi and rdi, clobber register, use the good register, so I compiled with GCC -O0 -S and -O2 -S
For -O0 -S I get
 3 .globl main
 4         .type   main, @function
 5 main:
 6 .LFB1:
 7         .cfi_startproc
 8         .cfi_personality 0x3,__gxx_personality_v0
 9         pushq   %rbp
 10         .cfi_def_cfa_offset 16
 11         .cfi_offset 6, -16
 12         movq    %rsp, %rbp
 13         .cfi_def_cfa_register 6
 14         subq    $80, %rsp
 15         movl    %edi, -68(%rbp)
 16         movq    %rsi, -80(%rbp)
 17         movq    $-1, -32(%rbp)
 18         movq    $-1, -24(%rbp)
 19         movq    $-1, -16(%rbp)
 20         movq    $0, -8(%rbp)
 21         movq    $1, -64(%rbp)
 22         movq    $0, -56(%rbp)
 23         movq    $0, -48(%rbp)
 24         movq    $0, -40(%rbp)
 25         leaq    -32(%rbp), %rax
 26         leaq    24(%rax), %rdx
 27         leaq    -64(%rbp), %rax
 28         addq    $24, %rax
 29         movq    %rdx, %rsi
 30         movq    %rax, %rdi
 31         call    _Z8test_addILin4EEvPyS0_
 32         movl    $0, %eax
 33         leave
 34         .cfi_def_cfa 7, 8
 35         ret
 36         .cfi_endproc
 37 .LFE1:
 38         .size   main, .-main
 39         .section              .   enter code here  `enter code here`text._Z8test_addILin4EEvPyS0_,"axG",@progbits,_Z8test_addILin4EEvPyS0_,comdat
 40         .weak   _Z8test_addILin4EEvPyS0_
 41         .type   _Z8test_addILin4EEvPyS0_, @function
 42 _Z8test_addILin4EEvPyS0_:
 43 .LFB2:
 44         .cfi_startproc
 45         .cfi_personality 0x3,__gxx_personality_v0
 46         pushq   %rbp
 47         .cfi_def_cfa_offset 16
 48         .cfi_offset 6, -16
 49         movq    %rsp, %rbp
 50         .cfi_def_cfa_register 6
 51         movq    %rdi, -8(%rbp)
 52         movq    %rsi, -16(%rbp)
 53 #APP
 54 # 14 "test.cpp" 1
 55         clc
 56 movq $-4, %rcx
 57 loop:
 58 movq 8(%rsi,%rcx,8), %rax
 59 adcq %rax           , 8(%rdi,%rcx,8)
 60 incq %rcx
 61 jnz loop
 62
 63 # 0 "" 2
 64 #NO_APP
 65         leave
 66         .cfi_def_cfa 7, 8
 67         ret
 68         .cfi_endproc
 69 .LFE2:
 70         .size   _Z8test_addILin4EEvPyS0_, .-_Z8test_addILin4EEvPyS0_
 71         .ident  "GCC: (GNU) 4.4.6 20120305 (Red Hat 4.4.6-4)"
 72         .section        .note.GNU-stack,"",@progbits

Line 20-30 we see the compiler reorganizes the stack to pass the arg into rsi and rdi
(line 29 - 30) and the call. Perfect as in the ABI
If now I look the optimize version I get
  1         .file   "test.cpp"
  2         .text
  3         .p2align 4,,15
  4 .globl main
  5         .type   main, @function
  6 main:
  7 .LFB1:
  8         .cfi_startproc
  9         .cfi_personality 0x3,__gxx_personality_v0
  10 #APP
  11 # 14 "test.cpp" 1
  12         clc
  13 movq $-4, %rcx
  14 loop:
  15 movq 8(%rsi,%rcx,8), %rax
  16 adcq %rax           , 8(%rdi,%rcx,8)
  17 incq %rcx
  18 jnz loop
  19
  20 # 0 "" 2
  21 #NO_APP
  22         xorl    %eax, %eax
  23         ret
  24         .cfi_endproc
  25 .LFE1:
  26         .size   main, .-main
  27         .ident  "GCC: (GNU) 4.4.6 20120305 (Red Hat 4.4.6-4)"
  28         .section        .note.GNU-stack,"",@progbits

Well bye bye the ABI, I do not understand. The stack is managed by what ????
An ASM guru has an idea ? I refuse to put the function into an independent file, well metaprogramming spirit.
Cheers.
------- Edit :
I found a bug with your solution, if I put it into a single loop :
#include <boost/cstdint.hpp> //boost type

template<long n>
void test_add(boost::uint64_t* x, boost::uint64_t const* y) {
    boost::uint64_t dummy;
    boost::uint64_t loop_index(n);
    __asm__ __volatile__ (
        "clc\n\t"
        "1:\n\t"
        "movq (%[y],%[counter],8), %[dummy]\n\t"
        "adcq %[dummy], (%[x], %[counter], 8)\n\t"
        "incq %[counter]\n\t"
        "jnz 1b\n\t"
        : [dummy] "=&r" (dummy)
        : [x] "r" (x), [y] "r" (y), [counter] "r" (loop_index)
        : "memory", "cc");
 }

int main(int argc, char* argv[]) {
    boost::uint64_t c[3],d[3];

    c[0] = -1;
    c[1] = -1;
    c[2] = -1;
    c[3] =  0;

    d[0] = 1;
    d[1] = 0;
    d[2] = 0;
    d[3] = 0;

for(int i=0; i < 0xfff; ++i)
    test_add<-4>(&c[4],&d[4]);

 return 0;

}
Will give the following ASM :
      movq    $-4, %rdx <---------------------template parameter
      leaq    -32(%rsp), %rcx
      movq    $-1, -32(%rsp)
      movq    $-1, -24(%rsp)
      movq    $-1, -16(%rsp)
      movq    $0, -8(%rsp)
      movq    $1, -64(%rsp)
      movq    $0, -56(%rsp)
      movq    $0, -48(%rsp)
      movq    $0, -40(%rsp)
      .p2align 4,,10
      .p2align 3
  .L2: <-------- OUPUT loop
#APP
# 16 "main.cpp" 1
       clc
       1: <-------- INPUT loop
       movq (%rcx,%rdx,8), %rsi
       adcq %rsi, (%rsp, %rdx, 8)
       incq %rdx <------------ rdx++ -> (-4)++ (for the @nd iteration of L2 it is not reset to -4)
       jnz 1b

 # 0 "" 2
 #NO_APP
       addl    $1, %eax
       cmpl    $4095, %eax <----- test second loop
       jne     .L2

Well for the second iteration for the output loop, rdx is not reflush to -4, thus the movq instruction gives a bad reading, segfault. I patch it very badly (I reset by hand with -4),I just add  "movq $-4, %[counter]\n\t " after the jnz, but I need something more general. Does it exist a constraint to reset the counter to the template parameter value ?
Presently the correction is :
template<long n>
void test_add(boost::uint64_t* x, boost::uint64_t const* y) {
    boost::uint64_t dummy;
    __asm__ __volatile__ (
        "clc\n\t"
        "movq %[counter_value], %[counter]\n\t" // set the counter to the template value, it's not sure if the function is reused
        "1:\n\t"
        "movq (%[y],%[counter],8), %[dummy]\n\t"
        "adcq %[dummy], (%[x], %[counter], 8)\n\t"
        "incq %[counter]\n\t"
        "jnz 1b\n\t"
        : [dummy] "=&r" (dummy)
        : [x] "r" (x), [y] "r" (y), [counter] "r" (n), [counter_value] "i" (n)
        : "memory", "cc");
}

A: You should use constraints to access the arguments. gcc is not required to follow the ABI for internal functions, and even if it does, it's not required to have the initial state intact when your asm block executes. Of course the point of inline asm is to have the compiler inline it, and then no function call even takes place. (Many peole wrongly think inline means "embedded in the C source file" and use it as convenience feature even when no actual code inlining is required.)
gcc is also quite capable of putting things in the register you want them in (not that you particularly care about the counter being rcx, here). It's also generally a good idea to leave as much to the compiler as possible, so that it can do register allocation, loop unrolling and other optimizations. Unfortunately I couldn't get gcc to generate ADC, so the asm block stays, this time. Using inc is not recommended either due to partial flags update, but I don't see an obvious way around that right now.
Finally, if you pass address of d[3] you will access items d[-1] through d[2] which is not what you want. You should pass d[4].
A fixed version could look like this (with named arguments):
template<long n>
void test_add(boost::uint64_t* x, boost::uint64_t* y) {
    boost::uint64_t dummy, dummy2;
    __asm__ __volatile__ (
        "clc\n\t"
        "1:\n\t"
        "movq (%[y], %[counter], 8), %[dummy]\n\t"
        "adcq %[dummy], (%[x], %[counter], 8)\n\t"
        "incq %[counter]\n\t"
        "jnz 1b\n\t"
        : [dummy] "=&r" (dummy), "=r" (dummy2)
        : [x] "r" (x), [y] "r" (y), [counter] "1" (n)
        : "memory", "cc");
}

Note that the dummy variable will be optimized away while allowing gcc to pick a suitable register instead of forcing it to use a particular one.

Update: Here is a pure C++ version that the compiler can fully unroll and otherwise optimize (including calculating things at compilation time!). While in the generic case the compiler's code isn't as efficient as the hand written one, the mentioned optimizations may make it better under circumstances. Note: since you are using gcc inline asm, that means your code is already gcc and x86-64 specific, so using __uint128_t is not a further restriction (in fact this will work on any architecture where gcc supports 128 bit integers).
template<long n>
void test_add(boost::uint64_t* x, boost::uint64_t* y) {
    __uint128_t work = 0;
    for(long i = n; i < 0; i += 1) {
        work = work + x[i] + y[i];
        x[i] = work; // automatic truncation
        work >>= 64;
    }
}

redpajama_set_name: RedPajamaStackExchange


text:
Q: Mapview элементы управления Доброго времени суток.
Есть приложение, функционал которого нужно частично копировать.
Как добавить элементы управления  на mapview?
Заранее спасибо.

A: Самый простой вариант - это сделать layout, в котором расположить кнопки над картой.
Что-то в роде этого:

<?xml version="1.0" encoding="utf-8"?>
    <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="fill_parent" android:layout_height="fill_parent">
        <com.google.android.maps.MapView
            android:id="@+id/map" android:layout_width="fill_parent"
            android:layout_height="wrap_content" android:apiKey="mykey"
            android:clickable="true" />

        <Button android:id="@+id/button" android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:layout_alignParentBottom="true"/>

    </RelativeLayout>

Более сложный, и, возможно, более правильный - использовать overlay. Но с этим я, к сожалению помочь ни чем не могу...


text:
Q: gridsome where to add router meta data I want to password protect specific routes and would like to add a meta data to every route like this:
{
  path: '/route-path',
  name: 'route-name',
  component: ComponentName,
  meta: {
    requiresAuth: true
  }
}

So I can check this in
router.beforeEach((to, from, next)

I have access to router.beforeEach in main.js but where do I add the auth flag to each route? gridsome.config.js does not seem to work?

A: Although it's not currently documented you can use the create page API and pass it a route property, for example...
src/pages.js
module.exports = [
  {
    path: '/',
    route: {
      name: 'index',
      meta: {
        requiresAuth: false
      }
    },
    component: './src/views/Index.vue'
  }
]

gridsome.server.js
const pages = require('./src/pages')

module.exports = function (api) {
  api.createPages(({ createPage }) => {
    for (const page of pages) {
      createPage(page)
    }
  })
}

I also moved the page components into a src/views directory to avoid route auto generation.


text:
Q: How to make a background image of a modal window appear simultaneously with a modal window, not before? I have a modal window with a background image as a background css property. The problem is that the background image appears much faster than the modal itself. How to make make them appear simultaneously?
Here is my HTML code of the modal window:

Here is a class .modal:
.modal {
    border: none !important;
    overflow: hidden;
    background-position: center;
    position: fixed;
    top: 0;
    right: 0;
    bottom: 0;
    left: 0;
    z-index: 1050;
    outline: 0;
    background: url('/img/carpet_simple.png') no-repeat fixed center;
}

And so background: url('/img/carpet_simple.png') no-repeat fixed center; appears instantaneously, much faster than the inner HTML code of the modal is rendered.
I tried this solution. It works but it is obviously not a good one. I just make a backgroung image appear 300ml later:
.pic {
    background: url('/img/carpet_simple.png') no-repeat fixed center;
}

$('.modal').on('shown.bs.modal', function() {
    var timeOutId = setTimeout(function() {
        $("#regModal").addClass("pic");
        clearTimeout(timeOutId);
        delete(timeOutId);
    }, 280);
});

$('.modal').on('hide.bs.modal', function() {
    $("#regModal").removeClass("pic");
});

How to make a background appear simultaneously with a modal inner html code or at least a little after it? And without my solution.

A: You can use javascript events for the modal. For example loaded.bs.modal;This event is fired when the modal has loaded content using the remote option.
$('#myModal').on('loaded.bs.modal', function (e) {
  // do something...
})

There are other events fired with the modal you can read about here


text:
Q: How to listen to JSON file update using java I create java program that load JSON file from url , I push json object to this url every 20 seconds I want the program to give notification when the JSON file updated here is my java code
package com.company;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.*;
import java.net.URL;
import java.nio.charset.Charset;

public class Main {
    private static String readAll(Reader rd) throws IOException {
    StringBuilder sb = new StringBuilder();
    int cp;
    while ((cp = rd.read()) != -1) {
        sb.append((char) cp);
    }
    return sb.toString();
}

public static JSONArray readJsonFromUrl(String url) throws IOException, JSONException {
    InputStream is = new URL(url).openStream();
    try {
        BufferedReader rd = new BufferedReader(new InputStreamReader(is, Charset.forName("UTF-8")));
        String jsonText = readAll(rd);
        JSONArray jsonArray = new JSONArray(jsonText);
        return jsonArray;
    } finally {
        is.close();
    }
}

public static void main(String[] args) throws IOException, JSONException {
    JSONArray json = readJsonFromUrl("http://frozen-brook-16337.herokuapp.com/history.json");
    for(int i=0;i<json.length();i++){
        JSONObject jo=json.getJSONObject(i);
        System.out.println(jo.get("data"));
     }

 }

}

How to make java program listen to JSON file update ?

A: You need to create a scheduler that executes your bit of code after every 20 seconds. There are multiple ways to achieve this.
A good robust way would be to use something like Quartz Scheduler
Or for a quick solution you can also create a Thread and have its run() method execute the code in a loop.
public class MyPush implements Runnable {

    public void run() {
         long twentySeconds = 20*1000L;
        while(true) {
          //execute your code
           Thread.sleep(twentySeconds);
        }
    }

    public static void main(String args[]) {
        (new Thread(new MyPush())).start();
    }

}


text:
Q: Query to return fields of distinct values per key In the process of building a data warehouse we are creating some aggregation tables for a reporting engine. We would like to build a single aggregation table from the fact table that can exist as list of all possible values of certain fields that are present in the fact table.
Assume that all of the source data is in a single flat Fact table. Imagine something like this:
|Org   |Gender| Age|State|
--------------------------
|     1|     M|   1|   FL|
|     1|     F|   2|   VA|
|     1|     M|   3|   CA|
|     1|     M|   2|   NJ|
|     2|     M|   2|   VA|
|     2|     M|   3|   VA|
|     2|     M|   5|   VA|
(Times 400+ million, but for only about 100 Orgs...)

I would like to create an aggregation table that has the following output structure:
|Org   |Gender| Age|State|
--------------------------
|     1|     M|   1|   FL|
|     1|     F|   2|   VA|
|     1|  NULL|   3|   CA|
|     1|  NULL|NULL|   NJ|
|     2|     M|   2|   VA|
|     2|  NULL|   3| NULL|
|     2|  NULL|   5| NULL|

So that for each Org, the non-NULL DISTINCT list in each column represents the list of distinct values in the Fact table for each column. I can't use a DISTINCT operator because that will look for the list of distinct combinations of fields, not where each field is distinct and the number of rows for each Org is at most the number of distinct values for that Org.
Added comments:
This is for a Data Warehouse, so the source data started off in the transactional relational database that is the companies working database. It's then denormalized into a Fact table and set of Dimension tables that support the possible values of other data. I don't have access to the original relational DB for this project.
Purpose:
But we are now putting an ad-hoc reporting interface on top of the data warehouse and in order to efficiently query the Fact and Dimension tables we have to build some aggregation tables so that the selection fields of the reporting interface don't have to query the hundreds of millions of rows in the fact+dimension tables to find the possible values for each org to present in select dropdowns after the Org is chosen.
I've done a lot of googling and haven't found much, but I don't even know what you would call this kind of structure. "Columnar distinct?"
The database I'm using is SQL Server 2012, if it matters.

A: Without knowing anything about the source data, perhaps this would do what you want?
USE Test;
GO
CREATE TABLE GENDER
(
    ORG INT NOT NULL
    , GENDER VARCHAR(1) NOT NULL
);

CREATE TABLE AGE
(
    ORG INT NOT NULL
    , AGE TINYINT
);

CREATE TABLE STATES
(
    ORG INT NOT NULL
    , STATENAME VARCHAR(255)
);

INSERT INTO Gender (ORG, GENDER) VALUES (1, 'M');
INSERT INTO Gender (ORG, GENDER) VALUES (1, 'F');
INSERT INTO Gender (ORG, GENDER) VALUES (2, 'M');
INSERT INTO Gender (ORG, GENDER) VALUES (2, 'F');
INSERT INTO Gender (ORG, GENDER) VALUES (3, 'M');
INSERT INTO Gender (ORG, GENDER) VALUES (3, 'F');

INSERT INTO AGE (ORG, AGE) VALUES (1,27);
INSERT INTO AGE (ORG, AGE) VALUES (1,28);
INSERT INTO AGE (ORG, AGE) VALUES (1,29);
INSERT INTO AGE (ORG, AGE) VALUES (1,30);
INSERT INTO AGE (ORG, AGE) VALUES (2,37);
INSERT INTO AGE (ORG, AGE) VALUES (2,38);
INSERT INTO AGE (ORG, AGE) VALUES (2,39);
INSERT INTO AGE (ORG, AGE) VALUES (2,40);
INSERT INTO AGE (ORG, AGE) VALUES (3, 2);

INSERT INTO STATES (ORG, STATENAME) VALUES (1,'FL');
INSERT INTO STATES (ORG, STATENAME) VALUES (1,'GA');
INSERT INTO STATES (ORG, STATENAME) VALUES (1,'MN');
INSERT INTO STATES (ORG, STATENAME) VALUES (1,'NM');
INSERT INTO STATES (ORG, STATENAME) VALUES (2,'FL');
INSERT INTO STATES (ORG, STATENAME) VALUES (2,'MN');
INSERT INTO STATES (ORG, STATENAME) VALUES (2,'NM');
INSERT INTO STATES (ORG, STATENAME) VALUES (3,'FL');
INSERT INTO STATES (ORG, STATENAME) VALUES (3,'GA');
INSERT INTO STATES (ORG, STATENAME) VALUES (3,'NM');

CREATE TABLE FACTS
(
    ORG INT NOT NULL
    , GENDER VARCHAR(1) NULL
    , AGE INT NULL
    , STATENAME VARCHAR(255) NULL
);

INSERT INTO FACTS (ORG, GENDER, AGE, STATENAME)
SELECT ORG, GENDER, NULL, NULL
FROM GENDER
GROUP BY ORG, GENDER
UNION ALL
SELECT ORG, NULL, AGE, NULL
FROM AGE
GROUP BY ORG, AGE
UNION ALL
SELECT ORG, NULL, NULL, STATENAME
FROM STATES;

SELECT *
FROM FACTS
ORDER BY ORG;

The results:

This will create a FACTS table that has all the data from several source tables.  As @ypercube and @jon-seigel said, this really doesn't make much sense; perhaps we are missing something compelling about your setup.
If this is not what you were expecting, please provide the source tables, and any other pertinent details.

A: Would a more generic FACT and DIMENSION table meet your needs?  The values in that table seem more like dimensions - is AGE a fact?  I don't understand the context so not sure of the best solution.  I assume that the objective is slicing, dicing, and analytics as opposed to storing data in a more relational structure.
If that assumption is wrong, a normalized relational table structure seems more appropriate.


text:
Q: Transactions not working unless inside DAO I have a problem with transactions in that annotating a service that calls a DAO with @Transactional throws an exception stating that the Session is not open. The only way I can get it working is by annotating the DAO with @Transactional. What on earth can be happening?
This is what I'd like to do but doesn't work:
class CustomerService {
    private CustomerDao dao;

    @Transactional
    public void foo() {
        int customerId = dao.getCustomer("fred");
    }
}

class CustomerDao {
    private HibernateTemplate hibernateTemplate;

    public int getCustomer(String name) {
        String sql = "SELECT {m.*} from Customers {m} where name=:name";
        Query qry = getSession().createSQLQuery(sql).addEntity("m", Customer.class);
        qry.setParameter("name", name);
        qry.setCacheable(false);
        List<Customer> list = qry.list();
        return list.iterator().next().getId();
    }

    private Session getSession() {
        return hibernateTemplate.getSessionFactory().getCurrentSession();
    }
}

This is what I'm doing instead but would rather not have to:
class CustomerService {
    private CustomerDao dao;

    public Customer(CustomerDao dao) {
        this.dao = dao;
    }

    public void foo() {
        int customerId = dao.getCustomer("fred");
    }
}

class CustomerDao {
    private HibernateTemplate hibernateTemplate;

    @Transactional
    public int getCustomer(String name) {
        String sql = "SELECT {m.*} from Customers {m} where name=:name";
        Query qry = getSession().createSQLQuery(sql).addEntity("m", Customer.class);
        qry.setParameter("name", name);
        qry.setCacheable(false);
        List<Customer> list = qry.list();
        return list.iterator().next().getId();
    }

    private Session getSession() {
        return hibernateTemplate.getSessionFactory().getCurrentSession();
    }
}

The problem seems to be caused by the CustomerService being instantiated inside the constructor of a wrapper class, where the wrapper is declared in the Spring xml context file:
class AllServices {
    private final CustomerService customerService;
    private final OrderService orderService;

    @Autowired
    public AllServices(CustomerDao customerDao, OrderDao orderDao) {
        this.customerService = new CustomerService(customerDao);
        this.orderService = new OrderService(orderDao);
    }

    public CustomerService getCustomerService() {
        return this.customerService;
    }

    public OrderService getOrderService() {
        return this.orderService;
    }
}

The spring file looks like this:
<context:annotation-config />
<import resource="classpath:db-spring-conf.xml"/>
<bean id="allServices" class="myPackage.AllServices" />

and the db-spring-conf:
<bean id="editorDatasource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
    <property name="driverClassName" value="com.mysql.jdbc.Driver" />
    <property name="url" value="${versioning.db}" />
    <property name="username" value="${versioning.user}" />
    <property name="password" value="${versioning.pass}" />
</bean>

<tx:annotation-driven transaction-manager="editorTransactionManager"/>

<bean id="editorSessionFactory" class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
    <property name="dataSource" ref="editorDatasource"/>
    <property name="exposeTransactionAwareSessionFactory">
        <value>true</value>
    </property>
    <property name="annotatedClasses">
        <list>
            <value>myPackage.Order</value>
        </list>
    </property>
    <property name="mappingResources">
        <list>
            <value>mappings/customer.hbm.xml</value>
        </list>
    </property>
    <property name="hibernateProperties">
        <props>
            <prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
            <prop key="hibernate.show_sql">true</prop>
            <prop key="hibernate.hbm2ddl.auto">validate</prop>
            <!-- Enable Query Cache -->
            <prop key="hibernate.cache.use_query_cache">false</prop>
            <!-- Enable 2nd Level Cache -->
            <prop key="hibernate.cache.use_second_level_cache">false</prop>
            <prop key="hibernate.connection.autocommit">false</prop>
            <prop key="hibernate.current_session_context_class">org.springframework.orm.hibernate3.SpringSessionContext</prop>
        </props>
    </property>
</bean>

<bean id="editorHibernateTemplate" class="org.springframework.orm.hibernate3.HibernateTemplate">
    <property name="sessionFactory" ref="editorSessionFactory"/>
</bean>

<bean id="editorTransactionManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager">
    <property name="sessionFactory" ref="editorSessionFactory" />
</bean>

<!-- DAOs -->
<bean id="customerDao" class="myPackage.CustomerHibernateDao" />
<bean id="orderDao" class="myPackage.OrderHibernateDao" />

I've now moved the instantiation of CustomerService up to the Spring config file and everything works a treat. Do all classes using @Transactional have to be in the context file? Also in order to make it work I had to create an interface for CustomerService to prevent an exception whilst loading the context file - Could not generate CGLIB subclass of class

A: So, you identified the cause of problem - Spring's @Transactional support is an aspect, and aspects in Spring are applied only to the components managed by the Spring contrainer (though it can be changed, but it's an advanced feature for complex cases).
If you don't like declaring services in XML, you may take a look at other options to delcare Spring-managed components:

*

*Classpath scanning

*Java-based configuration (since Spring 3.x)

Regarding the problem with CGLIB proxies see 7.6 Proxying mechanisms - probably you don't have CGLIB implementation in the classpath.


text:
Q: How to make nonclickable button click able in python using selenium? Hi Before starting Thanks for the help in advance
So I am trying to scrape google flight website : https://www.google.com/travel/flights
When scraping I have done the sending Key to the text field but I am stuck at clicking the search button it always gives the error that the field is not clickable at a point or Other elements would receive the click
the error image is
and the code is
from time import sleep
from selenium import webdriver
chromedriver_path = 'E:/chromedriver.exe'
def search(urrl):
 driver = webdriver.Chrome(executable_path=chromedriver_path)
 driver.get(urrl)
 asd= "//div[@aria-label='Enter your destination']//div//input[@aria-label='Where else?']"
 driver.find_element_by_xpath("/html/body/c-wiz[2]/div/div[2]/c-wiz/div/c-wiz/c-wiz/div[2]/div[1]/div[1]/div[1]/div[2]/div[1]/div[4]/div/div/div[1]/div/div/input").click()
 sleep(2)
 TextBox = driver.find_element_by_xpath(asd)
 sleep(2)
 TextBox.click()
 sleep(2)
 print(str(TextBox))
 TextBox.send_keys('Karachi')
 sleep(2)
 search_button = driver.find_element_by_xpath('//*[@id="yDmH0d"]/c-wiz[2]/div/div[2]/c-wiz/div/c-wiz/c-wiz/div[2]/div[1]/div[1]/div[2]/div/button/div[1]')
 sleep(2)
 search_button.click()
 print(str(search_button))
 sleep(15)
 print("DONE")
 driver.close()
def main():
 url = "https://www.google.com/travel/flights"
 print(" Getitng Data ")
 search(url)
if __name__ == "__main__":
 main()

and i have done it by copying the Xpath using dev tools
Thanks again

A: Instead of this absolute xapth
//*[@id="yDmH0d"]/c-wiz[2]/div/div[2]/c-wiz/div/c-wiz/c-wiz/div[2]/div[1]/div[1]/div[2]/div/button/div[1]

I would recommend you to have a relative path:
//button[contains(.,'Search')]

Also, I would recommend you to have explicit wait when you are trying a click operation.
Code:
search_button = WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//button[contains(.,'Search')]")))
search_button.click()

You'd need below imports as well:
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC

Pro tip:
Launch the browser in full screen mode.
driver.maximize_window()

You should have the above line just before driver.get(urrl) command.

A: The problem you are facing is that after entering the city Karachi in the text box, there is a suggestion dropdown that is displayed over the Search Button. That is the cause of the exception as the dropdown would receive the click instead of the Search button. The intended usage of the website is to select the city from the dropdown and then continue.
A quick fix would be to first look for all of the dropdowns in the source (there are a few) and look for the one that is currently active using is_displayed(). Next you would select the first element in the dropdown suggested:

.....
TextBox.send_keys('Karachi')
sleep(2)

# the attribute(role) in the dropdowns element are named 'listbox'. Warning: This could change in the future
all_dropdowns = driver.find_elements_by_css_selector('ul[role="listbox"]')

# the active dropdown
active_dropdown = [i for i in all_dropdowns if i.is_displayed()][0]

# click the first suggestion in the dropdown (Note: this is very specific to your search. It could not be desirable in other circumstances and the logic can be modified accordingly)
active_dropdown.find_element_by_tag_name('li').click()

# I recommend using the advise @cruisepandey has offered above regarding usage of relative path instead of absolute xpath
search_button = driver.find_element_by_xpath("//button[contains(.,'Search')]")
sleep(2)
search_button.click()
.....

Also suggest to head the advise provided by @cruisepandey including research more about Explicit Waits in selenium to write better performing selenium programs. All the best


text:
Q: Сохранение большого количества переменных в файл У меня есть такие значения:
x = 3452.7807
y.= 67.07
Z = 13.568

Нужно их как-то сохранить, а затем прочитать. Нужно, чтобы получилось что-то типа такого:
Checkpoint_1:

x = 3452.7807
y.= 67.07
Z = 13.568

Checkpoint_2:

x = 345552.7807
y.= 67.0567
Z = 13.568

И так далее...
Как это можно сделать?

A: Существует много различных вариантов сохранения данных, в данном случае можно использовать сериализацию.
Сериализация представляет процесс преобразования какого-либо объекта в поток байтов. После преобразования этот поток байтов можно записать на диск или сохранить его временно в памяти. Так же можно выполнить обратный процесс - десериализацию - получить из потока байтов ранее сохраненный объект.
В C#, по умолчанию, есть 4 класса-сериализатора, которые работают со следующими форматами:

*

*бинарный (BinaryFormatter);

*SOAP (SoapFormatter);

*XML (XmlSerializer);

*JSON (DataContractJsonSerializer).

Продемонстрирую на примере формата JSON. Для начала нужно пометить атрибутами те данные, которые мы хотим сохранить. Класс помечается атрибутом DataContract, а  его свойства - атрибутом DataMember:
[DataContract]
public class CheckPoint
{
    public CheckPoint (double x = 0, double y = 0, double z = 0)
    {
        X = x;
        Y = y;
        Z = z;
    }

    [DataMember]
    public double X { get; set; }
    [DataMember]
    public double Y { get; set; }
    [DataMember]
    public double Z { get; set; }
}

Представим, что в списке List<CheckPoint> checkPoints у нас есть 10 объектов, чтобы их записать в файл необходимо воспользоваться методом WriteObject() класса DataContractJsonSerializer:
DataContractJsonSerializer jsonFormatter = new DataContractJsonSerializer(typeof(List<CheckPoint>));
using (FileStream fs = new FileStream("checkPoints.json", FileMode.OpenOrCreate))
{
    jsonFormatter.WriteObject(fs, checkPoints);
}

Для чтения используется метод ReadObject():
List<CheckPoint> newCheckPoints;
DataContractJsonSerializer jsonFormatter = new DataContractJsonSerializer(typeof(List<CheckPoint>));
using (FileStream fs = new FileStream("checkPoints.json", FileMode.OpenOrCreate))
{
    newCheckPoints = (List<CheckPoint>)jsonFormatter.ReadObject(fs);
}

Файл будет выглядеть следующим образом:


text:
Q: Ошибка вызова ссылки на функцию Почему следующий код не валидный?
var t = Object.prototype.toString.call;
console.log(t); //==> function call()
t();            //==> Uncaught TypeError: t is not a function

Почему если t это функция, то при попытке ее вызвать выдается сообщение, что t это не функция?!
P.S. Я знаю, что правильно брать ссылку на call ф-ции toString надо так: Function.prototype.call.bind(Object.prototype.toString). Мне просто непонятно сама суть проблемы: если t это функция, то почему при попытке ее вызвать выдается сообщение, что t это не функция?
P.S.S. Проверено в Chrome и IE11

A: Может быть так?
var t =function(){
return Object.prototype.toString.call;
}

t();

A: Какую-то ясность внес Microsoft Edge. Если своими словами, то он говорит, мол f я вызываю, но this внутри call не является ф-цией (что при вызове f() в принципе является правдой). Просто Хром выдает вообще какое-то невменяемое сообщение из коотрого можно сделать вывод, что типа f не можно вызвать вообще (что меня собственно и смутило)


text:
Q: Angular style background image url + linear gradient I want to put a picture in a div, while using a gradient. After some tries, my best solution is this one:

But still not working.
Any help?

A: Use plain css and not inline styles!
.form-edit-picture-wrapper{
    background: linear-gradient(-225deg, rgba(0,0,0,0.6) 50%, rgba(0,36,61,0.6) 80%),
    url(/assets/hands.jpeg)
}

You would also need to set height and width as there seems to be no content in the div you provided.

A: If you want to use it in the template you can use the [ngStyle] directive.
[ngStyle]="{background: 'linear-gradient(-225deg, rgba(0,0,0,0.6) 50%, rgba(0,36,61,0.6) 80%), url(/assets/hands.jpeg)'}"

Here's a quick example

A: using @Nikhil Chandu answer, but using pipe.
make class pipe :
import { Pipe, PipeTransform } from "@angular/core";
import { DomSanitizer, SafeStyle } from '@angular/platform-browser';

@Pipe({
    name: 'sanitizeStyle'
})
export class SanitizeStylePipe implements PipeTransform {

    constructor(private _sanitizer:DomSanitizer) {
    }

    transform(v:string):SafeStyle {
        return this._sanitizer.bypassSecurityTrustStyle(v);
    }
}

using sanitizeStyle

A: sanitize and it shall work:
in your .ts file:
import { DomSanitizer } from '@angular/platform-browser';

in your export class add:
bgImage:any;

in your constructor add:
private sanitizer: DomSanitizer

then create an image url and sanitize:
this.bgImage = this.sanitizer.bypassSecurityTrustStyle('linear-gradient(-225deg, rgba(0,0,0,0.6) 50%, rgba(0,36,61,0.6) 80%),url(/assets/hands.jpeg)');

Thats the sanitizing part.
Now in your html:

There is also an other way to do this without sanitizing using ngStyle:

hope that helps!

A: you can do it like this:

 <image src="url" alt="">

.css file:
.image {
  background: linear-gradient(-225deg, rgba(0,0,0,0.6) 50%, rgba(0,36,61,0.6) 80%);
  background: -webkit-linear-gradient(-225deg, rgba(0,0,0,0.6) 50%, rgba(0,36,61,0.6) 80%);
  background: -moz-linear-gradient(-225deg, rgba(0,0,0,0.6) 50%, rgba(0,36,61,0.6) 80%);
}


text:
Q: Facebook Custom Posts currently i'm using Omniauth-facebook and Koala to integrate with facebook, so posting status updates and pictures on users behalf is fairly straightforward.
I was wondering if anybody knows how to create a custom posts(for example like the posts that social cam or coupon sites create) from rails.
Any guide or tutorial will be very much appreciated.
Thanks

A: Do you mean something similar to this post?
https://stackoverflow.com/questions/10037655/are-custom-wall-posts-links-such-as-this-possible-with-the-api
To do this you need to use Open Graph:
https://developers.facebook.com/docs/opengraph/


text:
Q: Is only one $watch created regardless of how many DOM elements are bound to the watched $scope? In the following code, is there only one $watch created even though the <input> element and interpolation of the double curlies {{customer.name}} create two different bindings to $scope.customer.name?
<html ng-app>
   <body>
     <input ng-model="customer.name" />
     {{customer.name}}
     <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.2.12/angular.min.js"></script>
  </body>
</html>

As a follow-up, does the resulting callback to the listener defined in the $watch update the DOM and re-render those changed elements?

A: Every ng-* and angular expression create internally a separate watcher.
If you want to check how many watchers are created you could check for angular private scope property scope.$$watchers
Sometimes there could be a lot of this watchers for a complex app, with some performance issue, that's why library as Bindonce was born (in the demo you could find interesting code to check watchers)

A: Answer to question 1:
There will be two watchers added.
Slightly simplified, a watcher is an object that is added to the scopes $$watchers array. This watcher object has a watchFunction and a listenerFunction.
Even if you used $watch to register the same pair of watch- and listenerFunction twice, there would be two watcher objects added.
Answer to question 2:
It depends on the watcher.
Consider the interpolation in your example: {{ customer.name }}
The listenerFunction (the function that is executed when the watched expression has changed) of the associated watch object will look like this:
function interpolateFnWatchAction(value) {
  node[0].nodeValue = value;
}

Pretty straightforward. The listenerFunction will update the node's nodeValue with the new value. When Angular's digest loop is finished the execution leaves Angular and the JavaScript context, which is followed by the browser re-rendering the DOM to reflect changes. Again a bit simplified.
When it comes to the ng-model directive, it gets more complex, since it has a two-way data binding ($scope --> view and view --> $scope) while the previous case has a one-way data binding ($scope --> view).
The watcher added from ng-model doesn't even register a listenerFunction. Instead it performs work in the watchFunction.
I will not go deeper into the matter, but might as well put the code below (which can be found here):
$scope.$watch(function ngModelWatch() {
  var value = ngModelGet($scope);

  // if scope model value and ngModel value are out of sync
  if (ctrl.$modelValue !== value) {

    var formatters = ctrl.$formatters,
      idx = formatters.length;

    ctrl.$modelValue = value;
    while (idx--) {
      value = formatters[idx](value);
    }

    if (ctrl.$viewValue !== value) {
      ctrl.$viewValue = ctrl.$$lastCommittedViewValue = value;
      ctrl.$render();
    }
  }

  return value;
});


text:
Q: basicNack and basicReject in RabbitMQ 1.what is mean by message in bulk in basicNack

The AMQP 0-9-1 specification defines the basic.reject method that allows clients to reject individual, delivered messages, instructing the broker to either discard them or requeue them. Unfortunately, basic.reject provides no support for negatively acknowledging messages in bulk.

2.is basicNack with multiple false is same as basicReject?
channel.basicNack(deliveryTag,false,true);

channel.basicReject(deliveryTag,true);

A: Yes; it is effectively the same.


text:
Q: use direction="rtl" in pre with html tags I try to figure out why in Pre tag with direction="dir" attributes with quotes in html tags looks wrong and how it can be fixed.
Print inside pre element html tags with attributes and quotes:
<html meta="test">

looks like this:
<"html meta="test>

css attribute unicode-bidi: bidi-override; not fits for me, i need to safe html tags structure.
live example:
https://codepen.io/justillusion/pen/GRGoRNv
best regards.

A: Using the &lrm to your punctuations seems to have fixed the problem.
Your snippet would look something like this;
   <pre>
        <html meta= test">
        Hello, World!
        </html>
    </pre>

For more explanation see: https://stackoverflow.com/a/42551367/11226302
There may be other solutions/workarounds as well, but this is what I found to be most practical and useful in cases such as yours!


text:
Q: How Can I get same div repeatedly as many I want once I click on plus button? I am using php to develop my website. I have a
 which contains multiple input fields. Now My question is how can I repeat the same
 multiple repeatedly once I go on clicking on plus button.

    <form name="myForm" method="post" action="#" onsubmit="return validateForm();" autocomplete="off" enctype="multipart/form-data">
            <input class="btn btn-success col-sm-1" type="submit" name="submit"  id="submit" value="Save"/>

My name

                        my address:

                        <input  class="form-control input-sm" type="text" name="testname" id="testname" required />

                        place

                        user Type

                            Instance/s

                        <md-content style="padding:10px; background-color: white">
                        <md-slider-container>
                              </md-slider>
                              <md-input-container>
                              </md-input-container>
                            </md-slider-container>
                         </md-content>

                                    <legend>Select File to Upload:</legend>

                                        <input type="file" name="file1" />

        </form>

A: You have to clone the entire div using .clone() in jquery. And then on button click you have to append it to the place where you want it.
Check this fiddle.
Or If you have a predefined code that is to be repeated on button click then you can do the following.
In php
function get_repeat_html(){
  ?>

        <input type="text" value="text">

Sample text

  >?php
}

In js
$('.btn').click(function(){
    var html = $('#get_repeat_html').html();
    $('#target').append(html);
});

A: below div will repeat based on your clicks
HTML

        <button class="add_field_button">Add More Fields</button>

<input type="text" name="mytext[]">

Jquery
$(document).ready(function() {
    var max_fields      = 10; //maximum input boxes allowed
    var wrapper         = $(".input_fields_wrap"); //Fields wrapper
    var add_button      = $(".add_field_button"); //Add button ID

    var x = 1; //initlal text box count
    $(add_button).click(function(e){ //on add input button click
        e.preventDefault();
        if(x < max_fields){ //max input box allowed
            x++; //text box increment
            $(wrapper).append('
<input type="text" name="mytext[]"/>Remove
'); //add input box
        }
    });

    $(wrapper).on("click",".remove_field", function(e){ //user click on remove text
        e.preventDefault(); $(this).parent('div').remove(); x--;
    })
});

here jsfiddle


text:
Q: Does a class with has-a relationship with a Collection object have a relationship with the Collection's elements? I am studying for the Java 8 Programmer II certification, and I'm going over the relationships classes can have. I understand composition, but I wondered if there is relationship considered between the elements of a collection that is a class variable of a class and that class. For instance, consider this code:
public class A {
    static ArrayList<String> strings = new ArrayList<String>();

    public A() {
        strings.add("foo");
    }
}

Do we say that the String elements of strings have a relationship with class A?

A: I would say yes.  The collection is almost immaterial here, more just an implementation detail of the "has-a" relationship between the class and the strings than anything else.  As for the fact that this is a class-wide relationship rather than a per-instance relationship, well, that's fine as long as you are aware and that is your intention.

A: First of all we should make clear if classes A and String would be in relationship if class A would have simple String field like so:
public class A {
    static String aString;

    public A() {
       aString = "foo";
    }
}

... I think so! And that would be "has-a" realtionship - A has-a String.
In your example there's a collection of Strings. We can also say that class A has-a (lot of ;) Strings... You can imagine that class A has a lot of relationships with String objects; class A aggregates them in collection. This is analogous to well known composition example "car 'has' wheels".
You can also say that this is unidirectional one-to-many relationship (unidirectional because only one side of this relationship knows about the other).

A: Yes, it is an "aggregation" or a composition depending on the lifetime of related objects. See also https://softwareengineering.stackexchange.com/questions/61376/aggregation-vs-composition

A: Has-a and is-a are intuitive concepts. They are not rules that compiler would check. It is a share vocabulary used to communicate to others effectively and used to make design decisions. So does class A "has" those strings? Yes, but you'll seldom state that rather you'd say Class A has a collection of Strings. A simple analogy is when you are carrying a bag, you wouldn't immediately say that you're carrying books, rather you're most likely to say you're carrying a bag full of books (collection of strings).


text:
Q: How to create a 'hole' in an image in vb.net I am trying to create a hole in my image using code, like this http://i1293.photobucket.com/albums/b595/electrogeekguy/fogofwardemo_zps6a6108c8.png
so that when i draw my image you can see what is underneath through the hole.
Below is my code that creates a gradient transparent at the middle out to solid black at the edges, but it blends my gradient with the underlying black.
vb.net or c# code to help me would be fine.
My plan is to remove a circle such as in my picture above and then apply the gradient.
Private Function FogOfWarUpdate() As Image
    Dim FogOfWarBitmap As Bitmap = New Bitmap(FogOfWarOldImage)
    Dim FogOfWarGraphics As Graphics = Graphics.FromImage(FogOfWarBitmap)
    Dim FogOfWarGraphicsPath As New System.Drawing.Drawing2D.GraphicsPath
    FogOfWarGraphicsPath.AddEllipse(2048, 1024, 500, 500)
    Dim FogOfWarPathGradientBrush As New System.Drawing.Drawing2D.PathGradientBrush(FogOfWarGraphicsPath)
    FogOfWarPathGradientBrush.CenterPoint = New PointF(2048 + 250, 1024 + 250)
    FogOfWarPathGradientBrush.CenterColor = Color.FromArgb(0, Color.Black)
    FogOfWarPathGradientBrush.SurroundColors = New Color() {Color.FromArgb(128, Color.Black)}
    FogOfWarGraphics.FillPath(FogOfWarPathGradientBrush, FogOfWarGraphicsPath)

    'FogOfWarGraphics.DrawEllipse(Pens.BlueViolet, 100, 100, 200, 200)
    FogOfWarPathGradientBrush.Dispose()
    FogOfWarGraphicsPath.Dispose()
    FogOfWarGraphics.Dispose()

    Return FogOfWarBitmap

End Function


text:
Q: Method return data type when using LINQ to Entities I have database table Staff having the columns Name, Email, Address and DateOfBirth. In my web application I have a separate class ClassMyBase having a couple of methods. One of the methods uses LINQ to Entities:
public static List<Staff> ShowAll()
{
     using (ModelPersonnelContainer myContainer = new
            ModelPersonnelContainer())
     {
         return myContainer.Staff.ToList();
     }
}

... and then in ButtonShowAll event handler in WebForm1:
protected void ButtonShowAll_Click(object sender, EventArgs e)
{
      GridViewAll.DataSource = ClassMyBase.ShowAll();
      GridViewAll.DataBind();
}

So far so good, BUT if I add filtering to my public static List<Staff> ShowAll():
public static xyz ShowAll()
{
      using (ModelPersonnelContainer myContainer = new
                ModelPersonnelContainer())
      {
            selectedRrows=from item in myContainer.Staff
                select new
            {
              Name=item.Name,
              Email=item.Email
            }
      }
}

my method won't work because the return data type is no more same as previously. Any easy solutions? What could this return data type xyz be?
If I put everything together (no separate class in my project) and have only ButtonShowAll it will work all right, so like this:
protected void ButtonShowAll_Click(object sender, EventArgs e)
{
            using (ModelPersonnelContainer myContainer = new
            ModelPersonnelContainer())
            {
                var selectedRows = from item in myContainer.Staff
                                  select new
                                  {
                                    Name=item.Name,
                                    Email=item.Email
                                  };
                GridView1.DataSource = selectedRows.ToList();
                GridView1.DataBind();
}

A: This part of your code creates an anonymous class:
new
{
    Name=item.Name,
    Email=item.Email
}

You should name it explicitly, then that class name will be used, and you can type your return type:
new Staff()
{
    Name=item.Name,
    Email=item.Email
}

Additionally, you might want to use ToList(), or change your return type to IEnumerable<Staff>, since the LINQ query will not return a List<Staff>:
var selectedRows = ...
                   .ToList();


text:
Q: Building a module based on ACIS kernel I want to build a module/application that converts .SAT format to a 3D printing file format like .3mf and I want it to be built on ACIS kernel so that I can use pre-defined functions and...
I have access to ACIS kernel source code but I don't know where to start exactly. I know they have this framework called RADF but I'm not sure if it would help me for what I want.
The questions that I have are so basic but I really appreciate it if you answer them.

*

*What does it mean to build an application based on a kernel exactly? Lets say I'm using VS, C# programming language and I have ACIS kernel source code. Do I have to start a new a project in VS and add ACIS libraries to it so that I can use its functions? I really need a good and informative answer for this so thank you in advance!

*What does RADF do in this situation? Do I rally need it? Is it necessary if I want to use C#?(because ACIS is written in C++)

*if the answer to the previous question is yes, I really need some help building the RADF and SPADotnet solutions. I can ask questions if someone has experience with it.

*As I said I want the output of my application to be a .3mf file, does that mean that I have to use .3mf source code that is developed by the consortium? (the one that is on GitHub)
At last I want to say that I'm really trying to learn those things by reading the documentation and other stuff online, but I just don't find my answers

A: Mohammad,
ACIS is a commercial toolkit that you must purchase a license in order to use it legally. I suggest you contact Spatial Corp to acquire a license. They are more than happy to support your workflow and answer the questions you ask.

*

*ACIS is a C++ library. To expose the functionality you're after, you must write a wrapper that is appropriate for the language you want to use.

*RADF is two things- a C# wrapper for the C++ library, as well as a basic application framework for creating a GUI application.

*Contact Spatial for help on this.

*Your best bet is to use the 3mf library from the consortium, yes.

A: As Brad says, Spatial provides support to developers: https://spatial.custhelp.com/app/utils/login_form/.
I worked with ACIS some years ago, and I'd say, it's not a library you should use in a new project, unless your project uses very little of its functions, so you could easily migrate to another kernel later, or your project so heavily depends on compatibility with ACIS that you have no other choice.
I believe open-source libraries are our future, see if you can pick some of them.


text:
Q: C# ActiveDirectory LDAP Group Querying Basically what I'm trying to do is, I have an ASP.Net web application that's using Forms Authentication with some custom code to link it to ActiveDirectory (very similar to how this works).
However, whenever I query the domain controller for the users groups it only returns the groups that they're explicitly in and not subgroups (id est, there's a specific Security Group that the user belongs to, say group A, that is a member of the group I want, say group B, the user is explicitly in group A, but only implicitly in group B because group A is a member of group B).
I've read the tokenGroups querying could help me out here but currently I don't have a way to parse that data.
However what would be most preferable is if I could pass certain groups via an LDAP query and have the Domain controller just give me a boolean (true/false) if that user is within that group or not.
Any suggestions?

A: Yes, the "usual" user.Properties["memberOf"] only returns direct memberships.
If you're using .NET 3.5 however, you can use the more modern "principal-based" methods:
using(PrincipalContext ctx = new PrincipalContext(ContextType.Domain))
{
    using(Principal p = Principal.FindByIdentity(ctx, "yourUserName"))
    {
        var groups = p.GetGroups();

        using (groups)
        {
            foreach (Principal group in groups)
            {
                Console.WriteLine(group.SamAccountName + "-" + group.DisplayName);
            }
        }
    }
}

This method (add a reference to the "System.DirectoryServices.AccountManagement" assembly to your project) should work and deliver the user's primary group and its nested group memberships as well.
If you're on .NET 2.0/3.0 and can't move up, using the approach by reading the "tokenGroups" attribute is the best approach - see the details about how to do all of this in Ryan Dunn's excellent blog post, Enumerating Token Groups (tokenGroups) in .NET.
Marc


text:
Q: Default value in function - Javascript In PHP we can define the argument value for the functions if it's not set(called), so for example:
<?php
    function blah($arg = false){
        var_dump($arg);
    }
?>

In the above example if we call the function like:
<?php
    blah();
    // ==> out put will be: false;
    blah(true);
    // ==> out put will be: true;
?>

So we can define a value for the arguments if they are not settled while we call the function, how this could be achieved in javascript functions?
I have it exactly like PHP:
<script>
    function blah(arg = false){
        //...
    }
</script>

The above code works just fine in Mozilla Firefox, but in Chrome, the function is not working and gets fixed when I remove = false in the parenthesis, Chrome developer tools says:

Uncaught Syntax Error: Unexpected token =

A: This is not possible in Javascript.
Try this Conditional Operator statement instead:
<script>
    function blah(arg){
       arg = typeof arg !== 'undefined' ? arg : 'someValue';
    }
</script>

Where 'someValue' is the default value that the arg variable will get when there are no arguments passed to the blah() function.

A: This is the cleanest pattern for implementing default arguments in javascript IMO.
function (arg) {
  arg = arg || 'defaultVale';
}

However this can fail if you expect the value of arg to be some falsy value, e.g 0, false, NaN, null using it is not really recommended.
This version protects against this case by explicitly comparing with undefined.
function (arg) {
  arg = arg === undefined ? 'defaultVale' : arg;
  // As T.J Crowder pointer out if not in strict mode or if the code will run
  // in an IFrame use typeof arg === "undefined" instead of directly
  // comparing with undefined
}

Another nice pattern is using objects for arguments instead. This has two benefits

*

*Order of arguments is not important

*It's easy to implement default arguments

Code
var defaults = {
  arg1: 10,
  arg2: 20
};

var f = function (args) {
  args = jQuery.extend(true, args, defaults); //jQuery
  args = _.defaults(args, defaults); // Underscore
};

f({
  a: 25 //Use a non default value
});

A: In JavaScript there is no default parameter.
Just write the code like:
function test(arg) {
    if(arg) {
        // do something as arg is defined.
    } else {
        // do something as arg is undefined.
    }
}

test(true); // arg is defined
test();  // arg is undefined

A: In Js you can't have default values for parameters. You can check if the data is of a known type with typeof operator:
function blah(arg)
{
    if (typeof arg === 'undefined')
    {
        arg = false;
    }
}

or setting his value in a short-circuit way
function blah(arg)
{
    arg = arg || false;
}

For example in coffeescript you can set it by using
blah = (arg = "mydefaultvalue") ->
that is translated into
blah = function(arg)
{
    if (arg == null)
    {
        arg = "mydefaultvalue";
    }
}

A: Simple variation
function defaulter(p1) {
    p1 = p1 || "default";
}


text:
Q: Django Exists() / ~Exists() return if there is no matching data? EDIT:
As per schillingt's answer below I have switched to using Case/When:
        context['db_orders'] = Order.objects.filter(
            retailer_code=self.object.retailer_code).annotate(
            in_db=Case(When(Q(Subquery(self.object.suppliers.filter(
                supplier_code=(OuterRef('supplier_code')))
            ), then=Value(True), default=Value(False), output_field=NullBooleanField()))))

However I'm now struggling with an errror:
FieldError at /retailers/A001/

Cannot resolve expression type, unknown output_field

Original question:
I have the DetailView below with a query/subquery that checks whether supplier_code exists within instances of a second model set up to represent purchase orders received into a live stock database.
The intention is for this to function as a checklist/ticksheet that will return whether or not the order has been received for each supplier expected to send one.
Getting it to return that there is a match seems to be working fine, and if there is a value it does not recognize (I have purposefully created an invalid order that won't match against the list) it will return that there is no match.
However I need this to also tell me that there is simply no data, yet I don't seem to be able to achieve this.
For example the below shows the template output; G001 is the 'fake' code I have set up and G002 is a valid one that exists in the suppliers list. However if there is not an order present for G002 it will not return anything.
    Order not received: G001
    Order received: G002

I have tried writing a second query for the context that is a mirror of context['db_orders'] but using the ~Exists() and then nesting the if statements in the template but this will just tell me that the orders both exist and don't exist or vice versa.
 context['not_db_orders'] = Order.objects.filter(
            retailer_code=self.object.retailer_code).annotate(in_db=~Exists(squery))

I've also tried to do this in the template using 'is not' or 'is None' or 'is False' but cannot seem to get the output I need
Ultimately the intended output is a table that lists all the suppliers expected into a particular retailer with some manner of 'Yes' or 'No' next to them based on whether the order exists among the Order instances. (The template HTML doesn't currently reflect this but that is not the issue)
Template:
{% extends 'tick_sheet/base.html' %}

{% block content %}

{{ object.retailer_name }}

    {% for supplier in object.get_supplier_values %}

{{ supplier }}

    {% endfor %}

{% for item in db_orders %}
        {% if item.in_db %}

Order received: {{ item.supplier_code }} - {{ item.supplier_name }}

        {% elif not item.in_db or item.in_db is None %}

Order not received: {{ item.supplier_code }} - {{item.supplier_name}}

        {% endif %}
{% endfor %}

{% endblock content %}

The DetailView:
class RetailerDetailView(DetailView):

    model = Retailer
    slug_field = 'retailer_code'
    slug_url_kwarg = 'retailer_code'

    def get_context_data(self, **kwargs):

        context = super().get_context_data(**kwargs)
        context['now'] = timezone.now()
        context['title'] = 'Order Checklist'

        squery = self.object.suppliers.filter(
            supplier_code=OuterRef('supplier_code'))

        context['db_orders'] = Order.objects.filter(
            retailer_code=self.object.retailer_code).annotate(in_db=Exists(squery))

        return context

Models.py
from django.db import models
from django.utils import timezone

class Order(models.Model):

    ''' To simulate connection to main stock db '''

    retailer_code = models.CharField(max_length=4)
    retailer_name = models.CharField(max_length=100)
    supplier_code = models.CharField(max_length=4)
    supplier_name = models.CharField(max_length=100)
    order_reference = models.CharField(max_length=20)
    despatch_date = models.DateTimeField(default=timezone.now)

    def __str__(self):

        return f"< {self.order_reference}', {self.supplier_name}, {self.retailer_name} >"

# -------------------------------------------------------------------------------------

class Retailer(models.Model):

    retailer_code = models.CharField(max_length=4)
    retailer_name = models.CharField(max_length=100)
    suppliers = models.ManyToManyField('Supplier')
    slug = models.SlugField(unique=True, null=True)

    def get_supplier_values(self):

        return [(suppliers.supplier_code + ' - ' + suppliers.supplier_name) for suppliers in self.suppliers.all()]

    def save(self, *args, **kwargs):

        self.slug = self.slug or slugify(self.retailer_code)
        super().save(*args, **kwargs)

    def __str__(self):

        return f"< {self.retailer_code} - {self.retailer_name} >"

class Supplier(models.Model):

    supplier_code = models.CharField(max_length=4)
    supplier_name = models.CharField(max_length=100)

    def __str__(self):

        return f"< {self.supplier_code}, {self.supplier_name} >"

A: If there's a difference in the case between False and None you can't use Exists. That is a strictly boolean operation. You will need to use a Subquery that returns a NullableBooleanField whose result is calculated with When and Case


text:
Q: BASH Script - Safe limits for string from command output Good day,
I am writing a relatively simple BASH script that performs an SVN UP command, captures the console output, then does some post processing on the text.
For example:
#!/bin/bash
# A script to alter SVN logs a bit

# Update and get output
echo "Waiting for update command to complete..."
TEST_TEXT=$(svn up --set-depth infinity)
echo "Done"

# Count number of lines in output and report it
NUM_LINES=$(echo $TEST_TEXT | grep -c '.*')
echo "Number of lines in output log: $NUM_LINES"

# Print out only lines containing Makefile
echo $TEST_TEXT | grep Makefile

This works as expected (ie: as commented in the code above), but I am concerned about what would happen if I ran this on a very large repository. Is there a limit on the maximum buffer size BASH can use to hold the output of a console command?
I have looked for similar questions, but nothing quite like what I'm searching for. I've read up on how certain scripts need to use the xargs in cases of large intermediate buffers, and I'm wondering if something similar applies here with respect to capturing console output.
eg:
# Might fail if we have a LOT of results
find -iname *.cpp | rm

# Shouldn't fail, regardless of number of results
find -iname *.cpp | xargs rm

Thank you.

A: Using
var=$(hexdump /dev/urandom | tee out)

bash didn't complain; I killed it at a bit over 1G and 23.5M lines. You don't need to worry as long as your output fits in your system's memory.

A: I see no reason not to use a temporary file here.
tmp_file=$(mktemp XXXXX)

svn up --set-depth=infinity > $tmp_file
echo "Done"

# Count number of lines in output and report it
NUM_LINES=$(wc -l $tmp_file)
echo "Number of lines in output log: $NUM_LINES"

# Print out only lines containing Makefile
grep Makefile $tmp_file

rm $tmp_file


text:
Q: Cloning an SQL Server 2008 Database Schema to a new Database - Programatically (PHP?) I've done some Googling and searching on SO, but I have not been able to find much help on the matter. I am designing a web service which utilizes an Microsoft SQL Server 2008 Server. The relevant structure is something like this... There is a main database which houses all Primary Account/Company information (Company name, address, etc..). In addition, there are databases for each Account/Company which houses all of the relevant (meta?)data for that account (users, settings, etc...).
SQL2008 Server
|---MainDatabase
|-------Accounts Table
|-----------Account Record where ID = 1
|-----------Account Record where ID = 2
|-----------Account Record where ID = 3
|---AccountDatabase00001
|-------Users Table for account where ID = 1
|---AccountDatabase00001
|-------Users Table for account where ID = 2

When a new account is created (let's say, ID=3), I am trying to figure out a way to clone the table schema and views (NOT the data) of AccountDatabase0001 into a new database called AccountDatabase00003. I could use virtually any language to perform the duplication as long as it can be called from a PHP page somehow.
Has anyone come across such a PHP script, or a script in any other such language for that matter? Is there a command I can send the the SQL server to do this for me?  I'm sure I could find my way through manually traversing the structure and writing SQL statements to create each object, but I'm hoping for something more simple.

A: You can do this using SMO without too much trouble. Here's one site that gives specific code for it. The code is in C#, but hopefully you can integrate it or translate it into PHP.

A: I found a remotely simply way to accomplish this in PHP with a little help from a custom-written stored procedure which need only exist in the database you wish to clone (for me it's always AccountDatabase_1). You pass the Table name to the Stored Procedure, and it returns the script you need to run in order to create it (which we will do, on the second database). For views, the creation script is actually stored in the Information_Schema.Views table, so you can just pull the view names and creation code from that to create clones very easily.
STORED PROC GenerateScript()
USE [SOURCE_DATABASE_NAME]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER Procedure [dbo].[GenerateScript]
(
    @tableName varchar(100)
)
as
If exists (Select * from Information_Schema.COLUMNS where Table_Name= @tableName)
Begin
    declare @sql varchar(8000)
    declare @table varchar(100)
    declare @cols table (datatype varchar(50))
    insert into @cols values('bit')
    insert into @cols values('binary')
    insert into @cols values('bigint')
    insert into @cols values('int')
    insert into @cols values('float')
    insert into @cols values('datetime')
    insert into @cols values('text')
    insert into @cols values('image')
    insert into @cols values('uniqueidentifier')
    insert into @cols values('smalldatetime')
    insert into @cols values('tinyint')
    insert into @cols values('smallint')
    insert into @cols values('sql_variant')

    set @sql=''

    Select
        @sql=@sql+
        case when charindex('(',@sql,1)<=0 then '(' else '' end +Column_Name + ' ' +Data_Type +
        case when Column_name='id' then ' IDENTITY ' else '' end +
        case when Data_Type in (Select datatype from @cols) then '' else  '(' end+
        case when data_type in ('real','money','decimal','numeric')  then cast(isnull(numeric_precision,'') as varchar)+','+
        case when data_type in ('real','money','decimal','numeric') then cast(isnull(Numeric_Scale,'') as varchar) end
        when data_type in ('char','nvarchar','nchar') then cast(isnull(Character_Maximum_Length,'') as varchar) else '' end+
        case when data_type ='varchar' and Character_Maximum_Length<0 then 'max' else '' end+
        case when data_type ='varchar' and Character_Maximum_Length>=0 then cast(isnull(Character_Maximum_Length,'') as varchar) else '' end+
        case when Data_Type in (Select datatype from @cols)then '' else  ')' end+
        case when Is_Nullable='No ' then ' Not null ' else ' null ' end +
        case when Column_Default is not null then 'DEFAULT ' + Column_Default else '' end + ','
    from
        Information_Schema.COLUMNS where Table_Name=@tableName

    select
        @table=  'Create table ' + table_Name
    from
        Information_Schema.COLUMNS
    where
        table_Name=@tableName

    select @sql=@table + substring(@sql,1,len(@sql)-1) +' )'

    select @sql  as DDL

End

Else
    Select 'The table '+@tableName + ' does not exist'

PHP
function cloneAccountDatabase($new_id){

    $srcDatabaseName = "AccountDatabase_1"; //The Database we are cloning
    $sourceConn = openDB($srcDatabaseName);

    $destDatabaseName = "AccountDatabase_".(int)$new_id;
    $destConn = openDB($destDatabaseName);

    //ENSURE DATABASE EXISTS, OR CREATE IT
    if ($destConn==null){
        odbc_exec($sourceConn, "CREATE database " . $destDatabaseName);
        $destConn = openDB($destDatabaseName);
    }

    //BUILD ARRAY OF TABLE NAMES
    $tables = array();
    $q = odbc_exec($sourceConn, "SELECT name FROM sys.Tables");
    while (odbc_fetch_row($q))
        $tables[]=odbc_result($q,"name");

    //CREATE TABLES
    foreach ($tables as $tableName){
        $q=odbc_exec($sourceConn, "exec GenerateScript '$tableName';");
        odbc_fetch_row($q);
        $sql = odbc_result($q, 'ddl');
        $q=odbc_exec($destConn, $sql);
    }

    //BUILD ARRAY OF VIEW NAMES AND CREATE
    $q = odbc_exec($sourceConn, "SELECT * FROM Information_Schema.Views");
    while (odbc_fetch_row($q)){
        $view=odbc_result($q,"table_name");
        $sql = odbc_result($q, "view_definition");
        odbc_exec($destConn, $sql);
    }

    return(true);
}

UPDATE
The CLONEDATABASE function is available in newer versions of MSSQL.
https://learn.microsoft.com/en-us/sql/t-sql/database-console-commands/dbcc-clonedatabase-transact-sql?view=sql-server-2017
//Clone AccountDatabase_1 to a database called AccountDatabase_2

DBCC CLONEDATABASE (AccountDatabase_1, AccountDatabase_2) WITH VERIFY_CLONEDB, NO_STATISTICS;
ALTER DATABASE AccountDatabase_2 SET READ_WRITE WITH NO_WAIT;


text:
Q: how can i make a .jar executable + I'm on ubuntu Studio 13.10 how do i make my mine craft executable.Ive tried running it in terminal and many forum answers. when I get to mine craft and i go into properties. and i look for allow to execute it doesn't appear i have no option to make it executable. I suppose i must
do it in the terminal yet i do not have the extra time for reading this whole thing Java -h
please help me get a quick easy or hard answer. <----- Original
Ive done what someone in the comments said and i got my computer to recognize it as a .jar
but it still won't  work i tried a very very helpful forum and learned some stuff but still nothing please help me guys i am stuck

A: I always run it via. command line:
java -jar /path/to/minecraft.jar

You could create a short script called start_minecraft.sh with the following contents:
#/bin/bash
/usr/bin/java -jar /path/to/minecraft.jar

and chmod +x the file.

A: Try creating a Launcher using the commands, it's easy and simple!
Right-Click
Click Create launcher and fill in the command and directory, also change "minecraft.jar" to "Minecraft.jar" as that's what it's called for 1.9


text:
Q: How to update all columns of a R data.table by row? I am trying to create a data.table object by taking pieces from other data.tables and combining them. Here's a simple example:
a <- data.frame(x=1:30)
b <- data.frame(x=10:39)
c <- data.frame(x=20:49)

d <- data.frame(x=50:79)
e <- data.frame(x=60:89)
f <- data.frame(x=70:99)

DT <- data.table(matrix(ncol = 3, nrow = 30))
for (i in seq.int(from = 1, to = 30, by = 3)) {
  set(DT,i,.SD,cbind(a[i,],b[i,],c[i,]))
  set(DT,(i+1),.SD,cbind(d[i,],e[i,],f[i,]))
  set(DT,(i+2),.SD,"")
}

However this doesn't work. Where did I go wrong? And can anyone recommend a better approach to achieving this kind of an effect? I always feel a little uneasy looping like this in R.
The desired output should be something like this: (showing first few rows)
     x  x  x
 1:  1 10 20
 2: 50 60 70
 3:
 4:  2 11 21
 5: 51 61 71
 6:
 7:  3 12 22
 8: 52 62 72
 9:
10:  4 13 23

A: First of all you have conflicting classes because you are trying to assign numbers and characters to the same columns. So I will assign NA instead of "".
That said, here is your solution using data.table with some modifications so it works:
DT <- data.table(matrix(0, ncol = 3, nrow = 30))
j = 1
cols = names(DT)
for (i in seq.int(from = 1, to = 30, by = 3)) {
  DT[i  , (cols) := .(a[j,], b[j,], c[j,])]
  DT[i+1, (cols) := .(d[j,], e[j,], f[j,])]
  DT[i+2, (cols) := NA]
  j = j + 1
}
DT
    V1 V2 V3
 1:  1 10 20
 2: 50 60 70
 3: NA NA NA
 4:  2 11 21
 5: 51 61 71
 6: NA NA NA
 7:  3 12 22
 8: 52 62 72
 9: NA NA NA
10:  4 13 23
11: 53 63 73
12: NA NA NA
13:  5 14 24
14: 54 64 74
15: NA NA NA
16:  6 15 25
17: 55 65 75
18: NA NA NA
19:  7 16 26
20: 56 66 76
21: NA NA NA
22:  8 17 27
23: 57 67 77
24: NA NA NA
25:  9 18 28
26: 58 68 78
27: NA NA NA
28: 10 19 29
29: 59 69 79
30: NA NA NA
    V1 V2 V3

Another solution using apply (and not using data.table):
df <- apply(cbind(a,b,c,d,e,f), 1, function(x) rbind(data.frame(x=x[1], y=x[2], z=x[3]),
                                               data.frame(x=x[4], y=x[5], z=x[6]),
                                               data.frame(x=NA, y = NA, z = NA)))
df <- do.call("rbind", df)

A: Building on @TimBiegeleisen's answer, which was deleted for some reason:
library(data.table)
pt1 <- data.table(a,b,c)
pt2 <- data.table(d,e,f)
out <- rbind(pt1,pt2)
out[c(rbind(matrix(seq(1,nrow(out)),byrow=TRUE,nrow=2),NA))]

The row indexing of out above is like: 1 31 NA  2 32 NA  3 33 NA, so it grabs the first row of each set of data and puts them together. NA indexing results in all NAs for a row.
#     x  x  x
# 1:  1 10 20
# 2: 50 60 70
# 3: NA NA NA
# 4:  2 11 21
# 5: 51 61 71
# 6: NA NA NA
# 7:  3 12 22
# 8: 52 62 72
# 9: NA NA NA
#10:  4 13 23
#...

A: May be there is more efficient way of doing this:
    rows2<-seq.int(1,30,3)
rows3<-1:10
n2<-length(rows3)
h1<-list(a[rows3,],b[rows3,],c[rows3,])
h2<-list(d[rows3,],e[rows3,],f[rows3,])
h3<-list(rep("",n2),rep("",n2),rep("",n2))

DT <- data.table(matrix(0,ncol = 3, nrow = 30))
for (j in 1:3) {
  set(DT,i=rows2,j=j,value=h1[[j]])
  set(DT,i=rows2+1,j=j,value=h2[[j]])
  set(DT,i=rows2+2,j=j,value=h3[[j]])
}
    DT
    V1 V2 V3
 1:  1 10 20
 2: 50 60 70
 3: NA NA NA
 4:  2 11 21
 5: 51 61 71
 6: NA NA NA
 7:  3 12 22
 8: 52 62 72
 9: NA NA NA
10:  4 13 23
11: 53 63 73
12: NA NA NA
13:  5 14 24
14: 54 64 74
15: NA NA NA
16:  6 15 25
17: 55 65 75
18: NA NA NA
19:  7 16 26
20: 56 66 76
21: NA NA NA
22:  8 17 27
23: 57 67 77
24: NA NA NA
25:  9 18 28
26: 58 68 78
27: NA NA NA
28: 10 19 29
29: 59 69 79
30: NA NA NA
    V1 V2 V3


text:
Q: sqlquery not working giving error I to write a query for the book database.  The question is to List each author's total earnings in 1995-2000 in descending order.
SELECT DISTINCT b.author,b.earnings as TOTAL_EARNING
FROM BookAuthor as b lEFT JOIN
     BookPublish
     on b.book=BookPublish.book
WHERE (b.earnings=COUNT(b.earnings)) AND (year BETWEEN 1995 AND 2000)
ORDER BY b.earnings desc ;

ERor: Invalid use of group function.
create table BookPublish(
      book varchar(255) ,
      year int,
      publisher varchar(255),
      price int,
      num int,
      PRIMARY KEY (book)
    );

    //INSERT INTO BookPublish VALUES('Math-1',1999,'Mcgraw',120,5000);
    //INSERT INTO BookPublish VALUES('Physics',2001,'Matt Woods',85,2500);
    //INSERT INTO BookPublish VALUES('Chemistry',1996,'McGraw',99,2300);
    //INSERT INTO BookPublish VALUES('Biology',1999,'Krishna',75,2000);
    //INSERT INTO BookPublish VALUES('Economics',2000,'Maze',125,3000);
    //INSERT INTO BookPublish VALUES('Engineering',1994,'ABC',180,8000);
    //INSERT INTO BookPublish VALUES('Medicine',1997,'ABC',180,9000);

    create table BookAuthor(
      book varchar(255) ,
      author varchar(255) ,
      earnings int,
      PRIMARY KEY (book,author)
    );

    //INSERT INTO BookAuthor VALUES('Math-1','Chris,Norman',12000);
    //INSERT INTO BookAuthor VALUES('Physics','Matt Woods',4000);
    //INSERT INTO BookAuthor VALUES('Chemistry','John Bayer',8200);
    //INSERT INTO BookAuthor VALUES('Biology','Craig S',3000);
    //INSERT INTO BookAuthor VALUES('Economics','Manohar',17000);
    //INSERT INTO BookAuthor VALUES('Engineering','Sterling',13050);
    //INSERT INTO BookAuthor VALUES('Medicine','Craig S',10000);

    create table BookReview(
      book varchar(255) ,
      reviewer varchar(255) ,
      score int,
      PRIMARY KEY (book,reviewer)  ,
      FOREIGN KEY (book) REFERENCES BookPublish(book)
    );

    //INSERT INTO BookReview VALUES('Math-1','Paul Gray',7);
    //INSERT INTO BookReview VALUES('Math-1','Daphne Merkin',8);
    //INSERT INTO BookReview VALUES('Physics','Daphne Merkin',6);
    //INSERT INTO BookReview VALUES('Chemistry','John',9);
    //INSERT INTO BookReview VALUES('Biology','Jack',10);
    //INSERT INTO BookReview VALUES('Economics','Paul Gray',7.5);
    //INSERT INTO BookReview VALUES('Engineering','Paul Gray',8);
    //INSERT INTO BookReview VALUES('Engineering','Daphne Merkin',7);

    create table BookReference(
      book varchar(255) ,
      bookreferenced varchar(255) ,
      PRIMARY KEY (book, bookreferenced)  ,
      FOREIGN KEY (book) REFERENCES BookPublish(book)
    );

    //INSERT INTO BookReference VALUES('Math-1','Introduction to Math');
    //INSERT INTO BookReference VALUES('Physics','Foundation of Physics');
    //INSERT INTO BookReference VALUES('Chemistry','Introduction to Chemistry');
    //INSERT INTO BookReference VALUES('Biology','Molecular Biology');
    //INSERT INTO BookReference VALUES('Economics','Micro-Economics');
    //INSERT INTO BookReference VALUES('Engineering','Engineering-1');

A: You have this in the where clause:
 b.earnings = COUNT(b.earnings)

You cannot mix aggregation and non-aggregation values.
What you want is a group by:
SELECT ba.author, sum(ba.earnings) as TOTAL_EARNING
FROM BookAuthor as ba lEFT JOIN
     BookPublish bp
     on ba.book = bp.book
WHERE year BETWEEN 1995 AND 2000
GROUP BY ba.author
ORDER BY sum(ba.earnings) desc ;

A: Since you want the earnings, ba.earnings will remain same for every column multiplied by BookPublish column hence the total will become wrong. Hence it should remain just ba.earnings without any method. If you want to calculate the earnings based on BookPublish something below should work
SELECT b.author, b.book AS book, b.earnings AS TOTAL_EARNING, sum(bp.num) * bp.price AS EARNING
FROM BookAuthor b
LEFT JOIN BookPublish bp ON b.book=bp.book
WHERE year BETWEEN 1995 AND 2000
GROUP BY b.author, b.book
ORDER BY b.earnings desc ;

Here I tried to SUM the number of books sold & multiplied with the price, the GROUP BY remains for author and book as every book sold will have different price.
By this you will get multiple author rows which can later be control in your code using for loop over the resultant object
Added on SQLFiddle - http://sqlfiddle.com/#!2/9755d/6
Edit - Table structure you can consider improving
CREATE TABLE `AUTHORS`(
    `id` INT NOT NULL PRIMARY KEY AUTO_INCREMENT,
    `fname` TEXT NOT NULL,
    `lname` TEXT NOT NULL,
    `email` VARCHAR(255) NOT NULL
);
CREATE TABLE `PUBLISHERS` (
    `id` INT NOT NULL PRIMARY KEY AUTO_INCREMENT,
    `name` TEXT NOT NULL,
    `phone_no` VARCHAR(16) NOT NULL,
    `email` VARCHAR(255) NOT NULL,
    `address` TEXT
);
CREATE TABLE `BOOKS` (
    `id` INT NOT NULL PRIMARY KEY AUTO_INCREMENT,
    `name` TEXT NOT NULL,
    `publish_year` INT NOT NULL,
    `author_id` INT NOT NULL,
    KEY `author_id` (`author_id`),
    CONSTRAINT `books_author_fk1` FOREIGN KEY `author_id` REFERENCES AUTHORS (`id`)
);
CREATE TABLE `BOOKPUBLISH` (
    `id` INT NOT NULL PRIMARY KEY AUTO_INCREMENT,
    `book_id` INT NOT NULL,
    `publisher_id` INT NOT NULL,
    `publish_year` INT NOT NULL,
    `price` INT NOT NULL,
    KEY `book_id` (`book_id`),
    CONSTRAINT `bookpublish_book_fk1` FOREIGN KEY `book_id` REFERENCES BOOKS (`id`),
    KEY `publisher_id` (`publisher_id`),
    CONSTRAINT `bookpublish_publisher_fk1` FOREIGN KEY `publisher_id` REFERENCES PUBLISHER (`id`)
);

This way you can define your other tables took, BOOKREVIEW & BOOKREFERENCE


text:
Q: discord.py-rewrite music - Cannot use check So, I have a Discord BOT with a music cog that looks like this:
def setup(bot):

    class Music:

        __slots__ = ("players", )

        def __init__(self):
            self.players = {}

        def get_player(self, ctx):
            # Retrieve the guild player.

        def check_player(self):

            def predicate(ctx):
                # PREVIOUS CHECK
                player = self.get_player(ctx)
                # CHECK PLAYER STATE

            return commands.check(predicate)

        @commands.command()
        @check_player(self)
        async def a_command(self, ctx):
            pass

    bot.add_cog(Music())

But I cannot use the check_player() check on the a_command() command as self is not defined. Anyone please know how I can fix this?

A: @PatrickHaugh
def get_player(self, ctx):
    """Retrieve the guild player, or generate one."""
    try:
        player = self.players[ctx.guild.id]
    except KeyError:
        player = MusicPlayer(ctx, bot)
        self.players[ctx.guild.id] = player
    except:
        return None

    return player

This is how the get_player() check works.


text:
Q: Tens of thousands of failed/denied SSH login attempts Recently a few friends and I came up with an idea for an app. To facilitate the creation of it, we set up LAMP on an Ubuntu Server 12.04. This box is running from my home. We've set up 3 user accounts. I'm still pretty new to Linux, but I have a bit of experience from using Ubuntu on my own box.
Today I was playing around with SSH and looking at the logs (I need to learn how to read that information to know how the server is performing, right?) and I saw the strangest thing.
In /var/log/auth.log and /var/log/auth.log.1 I saw a bunch of failed login attempts for 'root' and a few usernames I'm not familiar with. I looked over them and for as far as I can see no user has been authenticated except for the actual users on the system. A lot of the IP-addresses listed seem to be from Russia.
As of now this server contains nothing but a vanilla Ubuntu Server with LAMP, but even so, with the following command:
sudo grep -i fail /var/log/auth.log | wc -l

I get 3412 as a result. This seems very excessive for a server that has been up since April 8th. It gets worse, because running the above command on auth.log.1 returns 23075 (!!!!) results.
It seems obvious that people are trying to break into the server. Not that it contains anything of value, but once we start making progress on the app we wouldn't want our intellectual property stolen.
Should I be worried? And what can I do about it?
EDIT:
I found some very useful information here and this allowed me to run a script that splits and sorts all the invalid passwords and invalid users that tried to log in. May come in handy to someone who ended up here through Google!

A: This is happening a lot to me too. There are a lot of script kiddies trying brute force attacks against your SSH server.
My solution till now was to install DenyHosts, but seems that it will be not supported in 14.04; the next best solutions seems to be Fail2Ban. Links and  more information in Package denyhosts in Ubuntu Trusty Tahr is deleted: temporary or forever?
In that answer, bodhi.zazen pointed to this highly recommended page: https://web.archive.org/web/20190828185822/http://bodhizazen.com/Tutorials/SSH_security


text:
Q: Buscar por id Mongo Olá pessoal estou seguindo o livro Getting Mean mas me deparei com um problema na qual não consigo resolver. Tenho um documento que mostro abaixo pegando dados do Mongo, e nele tenho subdocumentos no caso reviews na qual quero pegar pelo id.
Meu problema é que não consigo retornar o subdocumento pelo id. Ele retorna sempre vazio. Preciso de ajuda!
module.exports.reviewsReadOne = function (req, res) {
  Loc
    .findById(req.params.locationid)
    .select('name reviews')
    .exec(
    function(err, location) {
      sendJsonResponse(res, 200,location);
    });
};

Aqui irá me mostrar todo resultado da consulta que é este:
{
"_id": "59c0115558d09042f1bd203e",
"name": "Starcups",
"reviews": [
    {
        "author": "Simon Holmes",
        "id": "59c0135658d09042f1bd203f",
        "rating": 5,
        "timestamp": "2013-07-16T03:00:00.000Z",
        "reviewText": "What a great place. I can't say enough good things about this",
        "createdOn": "2017-09-22T13:44:22.380Z"
    }
]

}
Eu quero acessar o subdocumento reviews pelo id. Então fiz:
module.exports.reviewsReadOne = function (req, res) {
  Loc
    .findById(req.params.locationid)
    .select('name reviews')
    .exec(
    function(err, location) {
      var review;
      review = location.reviews.id('59c0135658d09042f1bd203f');
      sendJsonResponse(res, 200,review);
    });
};

E recebi a resposta
null

Eu esperava receber o reviews por completo e não nulo. Não sei qual o problema aqui. Alguém tem alguma ideia aí pra resolver isso ?

A: O que procuras é:
var review = location.reviews.find(rev => rev.id == '59c0135658d09042f1bd203f');
// ou
var review = location.reviews.find(rev => rev.id == req.params.locationid);

Assim procuras nessa array reviews o objeto cuja propriedade id é igual à string que lhe passas. O find retorna o primeiro objeto que verificar a condição.


text:
Q: PIC18F String to Bluetooth to Tera Term I am trying to output a string from the PIC's USART and have it display on Tera Term. I am using the:

*

*PIC18F4331

*Sparkfun Bluesmirf RN-42

*MPLAB v8.85

*Tera Term

I've been working at this code for a couple of days and I am not seeing a single response. A couple of things that I think may be causing the issue is the baud rate and/or not having an interrupt routine. But is there a need for an interrupt if I am only attempting to transmit? Please, can someone guide me? Also, when using printf, I am seeing a response through the bluetooth but in strange symbolic form. For example, þþþ.
The code is a modification of one found online.
// Libraries
#include <p18f4331.h>
#include <stdio.h>

// Configuations
#pragma config OSC      = XT
#pragma config WDTEN    = OFF
#pragma config PWRTEN   = OFF
#pragma config FCMEN    = OFF
#pragma config IESO     = OFF
#pragma config BOREN    = ON
#pragma config BORV     = 27
#pragma config WDPS     = 128
#pragma config T1OSCMX  = ON
#pragma config PWMPIN   = ON
#pragma config MCLRE    = ON
#pragma config LVP      = OFF
#pragma config STVREN   = OFF
#pragma config PWM4MX   = RD5

// Definitions
#define _XTAL_FREQ 4000000
#define BAUDRATE 9600

void EUSART(void)
{
    TRISC = 0b10000000;
    SPBRG = 25;
    TXSTAbits.CSRC = 0; // Baud Rate Generated Externally
    TXSTAbits.TX9 = 0; // 8-Bit Transmission
    TXSTAbits.TXEN = 1; // Transmit Enabled
    TXSTAbits.SYNC = 0; // Asynchronous Mode
    TXSTAbits.BRGH = 1; // High Baud Rate
    TXSTAbits.TRMT = 0; // Transmit Shift Register When TSR Is Full
    RCSTAbits.SPEN = 1; // Serial Port Enabled
    RCSTAbits.RX9 = 0; // 8-Bit Reception
    RCSTAbits.CREN = 1; // Enables Receive
}

void SendByteSerially(unsigned char Byte) // Writes a character to the serial port
{
    while(!PIR1bits.TXIF) ; // wait for previous transmission to finish
    TXREG = Byte;
}

unsigned char ReceiveByteSerially(void) // Reads a character from the serial port
{
    while(!PIR1bits.RCIF) continue;   // Wait for transmission to receive
    return RCREG;
}

void SendStringSerially(const rom unsigned char* st)
{
    while(*st) SendByteSerially(*st++);
}

void delayMS(unsigned int x)
{
    unsigned char y;
        for(;x > 0; x--) for(y=0; y< 82;y++);
}

void main(void)
{
    unsigned char SerialData;
    EUSART();
    SendStringSerially("Hello World");

    while(1)
    {
        SerialData = ReceiveByteSerially();
        SendByteSerially(SerialData);
        delayMS(1000);
    }
}

A: You are using a PIC18, be sure that BRG16 equals 0 since you're using BRGH
BAUDCTL.BRG16 = 0;

because SPBRGH16 is the higher byte of SPBRG, and that may change the baudrate value of your USART.
Plus, be sure you're in the PIR1 bank. In MPLAB, that would be
banksel PIR1; //Not sure if there's an ending coma

My two functions to transmit via UART when properly initialized ( In MikroC ) :
void vTx232 (UC ucSend)
 {
    STATUS.RP0 = PIR1;     //Sure we're in PIR1
    while (PIR1.TXIF == 0);//While last TX not done
    TXREG = ucSend;        //Input param into TXREG
 }

void vTxString(UC *ucpString)
 {
   while (*ucpString!= 0x00)    //While string not at its end
    {
      vTx232(*ucpString);       //Send string character
      ucpString++;              //Increm string pointer
    }
 }


text:
Q: How to get alternating chapter and section titles in headers using fancyhdr without "Chapter 1" or section number This might look like a duplicate, but I don't think it is. What I want is the chapter and section titles in the headers on alternating pages in italics without them being preceded by "Chapter 1" or the section number. I've managed to get most the way there, but I can't manage to get the section title (without the section number) on the odd pages without the chapter title disappearing altogether from the headers on the even pages.
The commands I'm using to try and get rid of the "Chapter 1" and "1.1", respectively, are:
\renewcommand{\chaptermark}[1]{\markboth{#1}{}}
\renewcommand{\sectionmark}[1]{\markboth{#1}{}}
And here's a MWE:
\documentclass[12pt, twoside]{report}

\usepackage{lipsum}

\usepackage{fancyhdr}
\pagestyle{fancy}
\fancyhead{} %clears header
\fancyhead[CE]{\nouppercase{\textit{\leftmark}}} %puts chapter title on even page in lower-case italics
\fancyhead[CO]{\nouppercase{\textit{\rightmark}}} %puts section title on odd page in lower-case italics
\renewcommand{\headrulewidth}{0pt} %gets rid of line
\renewcommand{\chaptermark}[1]{\markboth{#1}{}} %gets rid of chapter number
\renewcommand{\sectionmark}[1]{\markboth{#1}{}} %gets rid of section number

\begin{document}

\chapter{Off we go}

\section{Introduction}

\lipsum[1-7]

\section{Key Point}

\lipsum[7-10]

\end{document}

I suspect it's something to do with the \markboth bit, but I can't figure it out! Thanks!

A: You have to use
\renewcommand{\sectionmark}[1]{\markright{#1}}

Example:
\documentclass[12pt, twoside]{report}
\usepackage{lipsum}

\usepackage{fancyhdr}
\pagestyle{fancy}
\fancyhead{} %clears header
\fancyhead[CE]{\nouppercase{\textit{\leftmark}}} %puts chapter title on even page in lower-case italics
\fancyhead[CO]{\nouppercase{\textit{\rightmark}}} %puts section title on odd page in lower-case italics
\renewcommand{\headrulewidth}{0pt} %gets rid of line
\renewcommand{\chaptermark}[1]{\markboth{#1}{}} %gets rid of chapter number
\renewcommand{\sectionmark}[1]{\markright{#1}} %gets rid of section number

\begin{document}
\chapter{Off we go}
\section{Introduction}
\lipsum[1-7]
\section{Key Point}
\lipsum[7-10]
\end{document}


text:
Q: How to send Parse object field from one class to another? I want to make such thing:
On one ViewControleer I'm making a query to Parse.com, where I'm sending objects fields to Label.Text. By clicking one button objects randomly changes, by clicking another one- next ViewController is opening. Just imagine Tinder - on the first VC I swiping girls, on the new one chat is opening, with the girl's name in the head of the NavigatorItem
So I want to send Object Field "Name" that I'm using in that view to another without other query.
I don't know, whether I can do it via segue, or protocol. Can U somehow help me with implementation?
here is the code of my random function
func retriveJobData() {
    var query: PFQuery = PFQuery(className: "Jobs")
    query.getObjectInBackgroundWithId("AUeuvj0zk2") {
        (newJobObject: PFObject?, error: NSError?) -> Void in

        if error == nil && newJobObject != nil {
            println(newJobObject)

            if let newJobObject = newJobObject {

            self.PrcieTextField.text = newJobObject["jobPrice"] as? String

            self.DateTextField.text = newJobObject["jobDate"] as? String

            self.DescriptionTextField.text = newJobObject["jobDescription"] as? String

            }
        } else {
            println(error)
        }
    }
}

I want to send newJobObject["jobName"] to NavigatorItemName of another ViewController

A: you can override prepareForSegue for this purpose:
override func prepareForSegue(segue: UIStoryboardSegue!, sender: AnyObject!) {
    if (segue.identifier == "yourSegueIdentifier") {
        // pass data to next view
    }
}

A: Assuming you have some method that triggers a push to the new viewController and that you're using the storyboard, call performSegue using the identifier you set up in the storyboard
@IBAction func buttonPressed(sender: UIButton!) {
    performSegueWithIdentifier("identifier", sender: nil)
}

Then override prepareForSegue and pass in the string
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
    if segue.identifier == "identifier" {
        let controller = segue.destinationViewController as! ViewController
        controller.jobName = someWayThatYouRetrieveNewJobObjectName
}

Then in ViewController ensure you have a property for jobName
var jobName:String! //declare this as an optional instead if needed

And set the navigation title
navigationItem.title = jobName


text:
Q: Obfuscator's "Prevent Microsoft IL Disassembler from opening my assembly" option I've been trying to apply code protection using the SmartAssembly obfuscator to a WPF Prism application, but it the application refuses to work properly when being obfuscated.
The only option that works for it is: Prevent Microsoft IL Disassembler from opening my assembly.
The Red-Gates help describes it as: SmartAssembly can add an attribute to your assembly that prevents Microsoft's Common Intermediate Language (IL) Disassembler (ildasm.exe) from opening your assembly.
I wonder how serious is this protection, is it worth to be applied if the code isn't really obfuscated.
Or, in other words, what is it this Microsoft's Common Intermediate Language (IL) Disassembler (ildasm.exe)? Is it the main part of every known .NET reverse engineering tool or is it just one of the many such tools?

A: ildasm.exe is the IL disassembler that comes with the .Net Framework. It's the one tool that everyone has if they have .Net. It's not a component, so other disassemblers are not based on it or anything.
The attribute in question is the SuppressIldasmAttribute. I do not know if other disassemblers such as Reflector or ILSpy respect this attribute, but I doubt it. A cursory Google search suggests that is not the case, and that the SuppressIldasmAttribute only affects ildasm.exe itself.
As such, it doesn't really protect your assembly and isn't much use as an obfuscation tool. But if you are obfuscating anyway, I don't see any reason why you wouldn't apply this attribute, as it at least blocks the easiest (most commonly available) method of disassembly and I don't think it does any harm.