Q: SQL query for counting combinations and including entries that don't exist This is a simplified version of the table I am dealing with which is Orders
+-------------------+------------------+---------------+
| Order_Base_Number | Order_Lot_Number | Other Cols... |
+-------------------+------------------+---------------+
|                 1 |                3 |               |
|                 1 |                3 |               |
|                 1 |                4 |               |
|                 1 |                4 |               |
|                 1 |                4 |               |
|                 1 |                5 |               |
|                 2 |                3 |               |
|                 2 |                5 |               |
|                 2 |                9 |               |
|                 2 |               10 |               |
+-------------------+------------------+---------------+

What I want to do is to get a count for the unique entries base on Base and Lot numbers. I have two set of numbers, one is a set of Base numbers and the other is a set of Lot numbers.
for example, lets say the two sets are Base In (1,2,3) and Lot is in (3,4,20).
I am looking for an SQL query that can return all the possible combination of (Base,Lot) from the two sets with a count that shows how many times the combination was found in the table. My problem is that I want to include all the possible combinations and if a combination is not in the Orders table, I want the count to show zero. So, the output I am looking for is something like this.
+------+-----+-----------+
| Base | Lot | Frequency |
+------+-----+-----------+
|    1 |   3 |    2      |
|    1 |   4 |    3      |
|    1 |  20 |    0      |
|    2 |   3 |    1      |
|    2 |   4 |    0      |
|    2 |  20 |    0      |
|    3 |   3 |    0      |
|    3 |   4 |    0      |
|    3 |  20 |    0      |
+------+-----+-----------+

I tried a lot of queries but never got close to this and not even sure if it can be done. Right now I am figuring out the combinations on the client side and hence I am performing too many queries to get the frequencies.

A: Perhaps the clearest way is to start with the lists as CTEs:
with bases as (
    select 1 as base from dual union all
    select 2 as base from dual union all
    select 3 as base from dual
   ),
     lots as (
    select 3 as lot from dual union all
    select 4 as lot from dual union all
    select 20 as lot from dual
   )
select b.base, l.lot, count(Order_Base_Number) as Frequency
from bases b cross join lots l left outer join
     Orders o
     on o.base = b.base and o.lot = l.lot
group by b.base, l.lot

Note that this makes the cross join explicit, purposely not using the , for a Cartesian product.
The first part of this query could also be written as something like the following (assuming that each base and lot has at least one record in the table):
with bases as (
     select distinct base
     from Orders  -- or some other table, perhaps Orders ?
     where base in (1, 2, 3)
    ),
     select distinct lot
     from Orders  -- or some other table, perhaps Lots ?
     where lot in (3, 4, 20)
    )
. . .

This is more succinct, but might result in a less efficient query.

A: What you need in the innermost subquery is called CROSS JOIN, which gets cartesian products (all possible combinations) of records. That's what you get when you have neither JOIN..ON condition nor WHERE:
SELECT Base.Id as baseid, Lot.Id as lotid FROM Bases, Lots

Now put it into subquery and LEFT JOIN to the rest of your stuff:
SELECT ... FROM
   (SELECT Base.Id as baseid, Lot.Id as lotid
           FROM Bases, Lots) baseslots
   LEFT JOIN Orders ON Order_Base_Number = baseid,
             Order_Lot_Number = lotid ....

With this LEFT JOIN, you'll get NULL for nonexistent combinations. Use COALESCE (or something like this) to turn them into 0.

A: I don't have Oracle to test it but this is what I would do:
CREATE TABLE pairs AS
(
SELECT DISTINCT Base.Order_Base_Number, Lot.Order_Lot_Number
FROM ORDERS Base
CROSS JOIN ORDERS Lot
);

CREATE TABLE counts AS
(
SELECT Order_Base_Number, Order_Lot_Number, Count(*) AS C
FROM ORDERS
GROUP BY Order_Base_Number, Order_Lot_Number
);

SELECT P.Order_Base_Number, P.Order_Lot_Number, COALESCE(C.C,0) AS [Count]
FROM Pairs P
LEFT JOIN counts C ON P.Order_Base_Number = C.Order_Base_Number
             AND P.Order_Lot_Number = C.Order_Lot_Number


Q: Java wait for Serial Input I linked a caliper to my computer with a RS232C-USB cable and I managed to get the data and print them in console. The caliper sends data everytime I press a pedal.
The problem is I can only acquire data once at the beginning, I'm searching for a function that would freeze the program, waiting for an input from the caliper before printing. The only one I have in mind is read(), but it doesn't seem to make the program wait for input.
Thanks in advance


Q: Lxml not finding all tables on page? I'm trying to get some data and when I'm using lxml it's find 2 tables and not the 3rd which I want.  I suspect this has to do with the xpath or the way that specific table is being generated.
I'm trying to get the price history from: http://web.tmxmoney.com/pricehistory.php?qm_symbol=WDO.DB.A
Here are the different attempts I've made and the results.
import requests
from lxml import html

def financialPriceData():
        priceData = requests.get('http://web.tmxmoney.com/pricehistory.php?qm_symbol=WDO.DB.A')
        PriceScraperTree = html.fromstring(priceData.content)
        #PriceTreeTickers = PriceScraperTree.xpath('//*[@id="innerContent"]/div[4]/div[1]/div[1]/div[1]/table/tbody/tr[1]/td/table/tbody/tr[5]/td/table/tbody/tr/td/table/tbody/tr[2]/td[1]/text()') # no luck. From Chrome.
        # PriceTreeTickers = PriceScraperTree.xpath('//table[@id="qm_history_historyContent"]') # no luck, can't find the table
        PriceTreeTickers = PriceScraperTree.xpath('//table')  # no luck, finds only 2 tables top of the page and bottom of the page data. When I look at text result the daily price is missing.
        print(PriceTreeTickers)

financialPriceData()


Q: validate and match the zip code with bill/ship country in magento checkout I want to validate the zip code as per bill/ship country in magento checkout process.
entered bill/ship country should matches the entered zipcode.
If the entered zipcode and country did not match - customer should not be able to save the address and appropriate error message should be displayed.
Example:- customer entered zip code 12345 and selected country as US.
          Then it should display the message "Zip code do not match with selected country."
can anyone suggest me , how can i validate the zip as per country ?
Can i use the google API to validate the zip code ?
What portion of magento file i need to customize ?

A: If you want to achieve this functionality, first you need to map the zipcodes with countries or use any plugin for it. Then, define a model or table for it. Then, during checkout make an ajax call from zipcode field to your controller, call your model there and then check the pincode. Based on your comparison, return the result and display what you want to.


Q: Python Produce empty list if condition not satisafied I am creating a if condition-based list. I want to create an empty list if the condition is not satisfied.
My code:
ip_list = []
op_list= [ip_list[0] if len(ip_list)>0 else '']

Present output:
op_list = ['']

Expected output:
op_list = []

A: This can be accomplished more succinctly via slicing:
op_list = ip_list[:1]

If ip_list has at least one element, op_list will be a singleton list with the first element of ip_list. Otherwise, op_list will be an empty list.
>>> a = [1, 2, 3]
>>> b = []
>>> a[:1]
[1]
>>> b[:1]
[]

A: op_list = [] if ip_list else [ip_list[0]]

A: You only need the first element if ip_list has any.
Here is one of the easiest solution for that:
[ip_list[0]] if ip_list else []


Q: Ng2-smart-table: is possible to pass data rows without keys? I want to pass to my data table some values as rows, like the following:
["ab", "b", "c"]. So, my json is just an array that doesn't have any keys, just a value. I know that we need to have a keys for each element that is the same of the column, but is there any solution? thanks

A: According to the documentation, the type of table row data can only be object. You can convert raw data, for example, like this:
// We should know the columns order
var columns = ['id', 'name', 'username', 'email'];

var data = rawData.map(function(item) {
  return item.reduce(
    function(result, item, columnIndex) {
      result[columns[columnIndex]] = item;
      return result;
    },
    {}
  );
});

https://jsfiddle.net/jLwmhbwv/


Q: Saving file properties results in Value does not fall in range exception I have the following code that is supposed to retrieve a canvas, save an image, and then write File properties to it. Sadly, it crashes when trying to save the properties. They are in string form, and the Property requires a string too, so I don't see what might be wrong:
try
{
    using (Windows.Storage.Streams.IRandomAccessStream stream =
            await file.OpenAsync(Windows.Storage.FileAccessMode.ReadWrite))
    {
        stream.Size = 0;
        await MyInkCanvas.InkPresenter.StrokeContainer.SaveAsync(stream);
    }

    ImageProperties imageProperties = await file.Properties.GetImagePropertiesAsync();
    string title = CanvasGrid.Width + " x " + CanvasGrid.Height;
    imageProperties.Title = title;
    await imageProperties.SavePropertiesAsync();

    //MainPage.NotifyUser("File has been saved!", NotifyType.StatusMessage);
}
catch (Exception ex)
{
    //MainPage.NotifyUser(ex.Message, NotifyType.ErrorMessage);
}

Value does not fall within the expected range.


Q: Renaming coat colors in R goes wrong with str_detect I have a dataset with horses and want to group them based on coat colors. In my dataset more than 140 colors are used, I would like to go back to only a few coat colors and assign the rest to Other. But for some horses the coat color has not been registered, i.e. those are unknown. Below is what the new colors should be. (To illustrate the problem I have an old coat color and a new one. But I want to simply change the coat colors, not create a new column with colors)

Horse ID
Coatcolor(old)
Coatcolor

1
black
Black

2
bayspotted
Spotted

3
chestnut
Chestnut

4
grey
Grey

5
cream dun
Other

6

Unknown

7
blue roan
Other

8
chestnutgrey
Grey

9
blackspotted
Spotted

10

Unknown

Instead, I get the data below(second table), where unknown and other are switched.

Horse ID
Coatcolor

1
Black

2
Spotted

3
Chestnut

4
Grey

5
Unknown

6
Other

7
Unknown

8
Grey

9
Spotted

10
Other

I used the following code
mydata <- data %>%
  mutate(Coatcolor = case_when(
     str_detect(Coatcolor, "spotted") ~ "Spotted",
     str_detect(Coatcolor, "grey") ~ "Grey",
     str_detect(Coatcolor, "chestnut") ~ "Chestnut",
     str_detect(Coatcolor, "black") ~ "Black",
     str_detect(Coatcolor, "") ~ "Unknown",
     TRUE ~ Coatcolor
  ))
mydata$Coatcolor[!mydata$Coatcolor %in% c("Spotted", "Grey", "Chestnut", "Black", "Unknown")] <- "Other"

So what am I doing wrong/missing? Thanks in advance.

A: You can use the recode function of thedplyr package. Assuming the missing spots are NA' s, you can then subsequently set all NA's to "Other" with replace_na of the tidyr package. It depends on the format of your missing data spots.
mydata <- tibble(
  id = 1:10,
  coatcol = letters[1:10]
)

mydata$coatcol[5] <- NA
mydata$coatcol[4] <- ""

mydata <- mydata %>%
  mutate_all(list(~na_if(.,""))) %>% # convert empty string to NA
  mutate(Coatcolor_old = replace_na(coatcol, "Unknown")) %>% #set all NA to Unknown
  mutate(Coatcolor_new = recode(
    Coatcolor_old,
    'spotted'= 'Spotted',
    'bayspotted' = 'Spotted',
    'old_name' = 'new_name',
    'a' = 'A', #etc.
  ))
mydata


Q: multiplying an dividing irrational numbers and quantifiers I'm doing a homework assignment, and I am pretty sure that I know which answer they expected, but the problem made me start thinking more deeply about numbers.
So if you have an an arbitrary irrational number, is there a number which is equal to that number / 2?  Is there a number which is equal to that number times two?
For the latter, I would say yes.  For the first question, I've come to think no.  The reason being that I do not think that an irrational number can be divided evenly.  If irrational numbers cannot be divided evenly, then 2 times any number, no matter how close, will always be different than a rational number by some amount.  But then, if this is the case, then also that means that there was no such number that could have been multiplied by 2 to make the irrational number.  And to my knowledge, there is no irrational number which when multiplied by a rational number is not irrational. So 2 times an irrational number, is an irrational number, but that would then not be evenly divisible by 2.  This is a contradiction, so it would seem to follow that all irrational numbers must be evenly divisible.
Can anyone make sense of this for me.

A: For any real number $x$, rational or irrational, $\frac{x}2=\frac12x$ is a real number, and $2\cdot\frac{x}2=x$. If $x$ is rational, $\frac{x}2$ is also rational; if $x$ is irrational, $\frac{x}2$ is also irrational; but in both cases it exists.
Your difficulty seems to arise from trying to apply the notion evenly divisible to real numbers in general, when in fact it applies only to integers. It is perfectly true that if $n$ is an integer, then there is an integer $m$ such that $n=2m$ if and only if $n$ is even, so that some integers — the odd ones — are not two times some integer; and it’s often useful to distinguish the even integers from the odd integers. The odd integers are, however, still two times some rational number, albeit not an integer. E.g., $5=2\cdot\frac52$.
When we move from the integers to the rational numbers, matters change: if $p$ is rational, so is $\frac{p}2$, so every rational number is twice some rational numbers. And when we move on to the real numbers, we retain this property: if $x$ is a real number, so is $\frac{x}2$, so every real number is twice a real number.


Q: I want to hide Edit(Salesforce Classic) action from Report I want to hide the Edit(Salesforce Classic) action from the report record, I checked in Profile and permission set, I not getting any permission related to hiding these button, This is a standard button. Any advice, please.

A: The easiest way to accomplish this is to set a VF page on that button that will override that action. On the VF inform the user that this action is not available anymore.
Got to, Report object, Buttons, Links and Actions,
edit Edit(Salesforce Classic)

Set Salesforce Classic Override to VF page and select the VF page that needs to but built to inform users of this functionality not being available any longer...  that should do it.
The Report object don't allow you to modify the standard page layout for this object, so it is not as other objects in which you can just remove the button, as far as I know.

A: You can remove the button in the Report and Dashboard User Interface Settings in Setup.  Just check the option for "Hide the embedded Salesforce Classic report builder in Lightning Experience".  This removes the button for everyone.


Q: PostgreSQL - "Include Error Detail" connection string parameter - how sensitive is the information returned? https://www.npgsql.org/doc/connection-string-parameters.html

Include Error Detail -
When enabled, PostgreSQL error and notice details are included on PostgresException.Detail and PostgresNotice.Detail. These can contain sensitive data.

If I provide the "Include Error Detail=True" in the connection stringg to PostgreSQL, what sensitive data do I need to be concerned about? If the query itself is returned in an exception or error message, that is fine by me, but if say the connection password were returned in plaintext obviously that would be bad. What sensitive data is conditionally included in errors based on this parameter?

A: These messages include no sensitive data that the database user should not see. So I wouldn't worry, unless perhaps you show the information to the application user rather than logging them. Your database user may have access to information that the application user shouldn't see.


Q: Reading from a pre-populated database file for android I followed this tutorial at this page. I followed it thoroughly but I still can't get the prepopulated database file to work. I keep getting an error saying .getReadableDatabase or .getWritableDatabase is called recursively. Also tried the solution of the answer for this page and also it doesn't work. Is there a simpler way to copy a prepopulated database to a local database which enables me to update and create data?

A: Try this :
public class DatabaseManager {
private DatabaseHelper dataHelper;
private SQLiteDatabase mDb;
private Context ctx;
private String DATABASE_PATH = "/data/data/Your_Package_Name/databases/";
private static String DATABASE_NAME = "Your_Database";
private static String TABLE_NAME = "Your_Table";
private static final int DATABASE_VERSION = 1;
String Class_Tag = "DatabaseManager";

public DatabaseManager(Context ctx) {
    this.ctx = ctx;
    dataHelper = new DatabaseHelper(ctx);
}

private static class DatabaseHelper extends SQLiteOpenHelper {
    @SuppressWarnings("unused")
    Context myContext = null;

    public DatabaseHelper(Context context) {
        super(context, DATABASE_NAME, null, DATABASE_VERSION);
        this.myContext = context;
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        Log.w("DBHelper", "Upgrading database from version " + oldVersion
                + " to " + newVersion + ", which will destroy all old data");
        onCreate(db);
    }
}

public boolean checkDataBase() {

    File f = null;
    try {
        String myPath = DATABASE_PATH + DATABASE_NAME;
        f = new File(myPath);
    } catch (Exception e) {
        Log.e(Class_Tag, "checkDataBase()", e);
    }
    return f.exists();
}

public void createDataBase() {

    try {
        openDB();
        InputStream myInput = ctx.getAssets().open(DATABASE_NAME + ".db");
        OutputStream myOutput = new FileOutputStream(DATABASE_PATH
                + DATABASE_NAME);

        byte[] buffer = new byte[1024];
        int length;
        while ((length = myInput.read(buffer)) > 0) {
            myOutput.write(buffer, 0, length);
        }

        if (mDb.isOpen())
            mDb.close();
        myOutput.flush();
        myOutput.close();
        myInput.close();

    } catch (Exception e) {
        Log.e(Class_Tag, "createDataBase()", e);
    }
}

public DatabaseManager openDB() throws SQLException {

    mDb = dataHelper.getWritableDatabase();
    return this;
}
public void closeDB() {
    try {
        if (mDb != null) {
            mDb.close();
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}
}

and in MainActivity
DatabaseManager dbMgr=new DatabaseManager(this);
try {
    if (!dbMgr.checkDataBase()) {
                dbMgr.createDataBase();
            }
        } catch (Exception e) {
            Log.e(Class_Tag, "onCreate()", e);
        } finally {
            dbMgr.closeDB();
        }

Hope it helps...


Q: Localized dates inconsistency I am localizing my date strings, but having issues.
I expect UK locales to have dayOfTheMonth then Month while US ones to have Month then DayOfTheMonth.
It seems to be the case for getMediumDateFormat but not for getDateFormat.
If I use:
android.text.format.DateFormat.getMediumDateFormat

then I get:
UK: 25 Nov 2015
US: Nov 25, 2015
Which is what I expect (day and month are in reverse order)
However, if I use:
android.text.format.DateFormat.getDateFormat

Then I get:
UK and US: 25/11/2015
In both cases the format is: dd/MM/yyyy
Did I miss something here?
Is there a better way to get a localized short date format?


Q: Yeoman/Grunt clean:dist task property undefined I'm new to grunt and having trouble with the clean:dist task for grunt-contrib-clean. This is my code for the task.
clean: {
    dist: {
        files: [{
            dot: true,
            src: [
                '.tmp',
                '<%= yeoman.dist %>/*',
                '!<%= yeoman.dist %>/.git*',
                '!<%= yeoman.dist %>/Procfile',
                '!<%= yeoman.dist %>/package.json',
                '!<%= yeoman.dist %>/web.js',
                '!<%= yeoman.dist %>/node_modules'
           ]
        }]
    },
    server: '.tmp'
},

When I run grunt build I get the following warning "An error occurred while processing a template (Cannot read property 'dist' of undefined). Use --force to continue." I'm thinking it must be a syntax error or something wrong with a plugin, but I don't know enough to keep figure it out.

A: For some reason, changing from <%= yeoman.dist %> to <%= config.dist %> solves the problem from me. Not sure when using yeoman.dist syntax is appropriate, but in any case I solved my own problem. So the solutions is...
clean: {
  dist: {
    files: [{
      dot: true,
      src: [
        '.tmp',
        '<%= config.dist %>/*',
        '!<%= config.dist %>/.git*',
        '!<%= config.dist %>/Procfile',
        '!<%= config.dist %>/package.json',
        '!<%= config.dist %>/web.js',
        '!<%= config.dist %>/node_modules'
      ]
    }]
  },
  server: '.tmp'
},


Q: Windows Phone Emulator error, Hyper-V components not running, Windows 8.1 hosted in Windows Azure Environment:
Windows 8.1 Enterprise 64-bit hosted in Windows Azure
Visual Studio Ultimate 2013 (Update 2)

I get the following error when trying to run a very simple phone app. I know MS says a VM-within-a-VM environment isn't supported, but I know it can work. Has anyone had success with this? Any help is greatly appreciated.
Windows Phone Emulator

The Windows Phone Emulator wasn't able to ensure the virtual machine was running:

Something happened while starting a virtual machine: 'Emulator WVGA 512 MB.' failed to start.
(Virtual machine ID CADD6546-129A-4683-9A2D-52EAE777E888)

The Virtual Machine Management Service failed to start the virtual machine 'Emulator WVGA 512 MB.'
because one of the Hyper-V components is not running
(Virtual machine ID CADD6546-129A-4683-9A2D-52EAE777E888).

Prior to seeing the error, the emulator emits the on-screen messages:
Loading ...

The Windows Phone OS is starting ...

And then the error. Of all the Hyper-V services available, the Hyper-V Virtual Machine Management service is the only one which is running.
Thanks,
Chris

A: I had the same issue with Visual Studio running on windows 8.1 in vmware player
What I had to do to solve the problem was this :
Tick the box "Virtualize Intel VT-x/EPT or AMD-V/RVI" in the processor settings of your VM
Add the line "hypervisor.cpuid.v0 = FALSE" in the file "Windows 8 x64.vmx" (add it between line 5 and 6. Not sure this matters, but at this line I'm sure it works)
Should be working fine

A: "You cannot host it in Azure.  It needs to be a physical machine." -- Jeff Sanders (MSFT)

A: Florian.C's answer got me on the right track to get the emulator working correctly in VMware Fusion on my MacBook Pro.  In Fusion, the settings are under the "Processors & Memory" section.  You have to open the "Advanced" section at the bottom and check the "Enable hypervisor applications for this virtual machine".  Once that was done, I had to also open the .vmx file and add the "hypervisor.cpuid.v0 = "FALSE"" line.  Originally I copied and pasted from SO and the VM threw an error when I booted it.  It turns out the " I added around FALSE were not normal quotes.  Once I fixed that, the VM booted and the emulator ran just fine under Fusion.  Thanks for the great info!


Q: Jump discontinuity of a function and its analytic phase Let $f:\mathbb{R}\to \mathbb{R}$ and $f \in BV(0,1)$ with a jump discontinuity at $x = a\in(0,1)$. Let $f_h$ be its Hilbert transform and let $$f_A(x) = f(x) + i f_h(x)$$ Is it true that the function $$\phi(x) = \angle{f_A(x)}$$ also has a jump discontinuity at $x = a$?

A: I think the easiest way to tackle this problem is to write $f = g+h$, where $h$ is a piecewise linear function such that $h(0) = h(1) = 0$, chosen so that $g = f-h$ doesn't have a jump discontinuity at $x = a$.  Now presumably you have some results that ensure that $g_A$ doesn't have a jump discontinuity at $x = a$.  You should be able to compute $h_A$ explicitly, and at this point the answer should be easy to determine.
(If memory serves me correctly, $h_h(x)$ will probably converge to $\pm\infty$ at $x = a$, with the $\pm$ being different on either side.  If this is the case, then the jump discontinuity of $\text{arg}(f_A)$ will be $\pm \pi$.)
Added later: looking at the comments below, it seems like memory did not serve me correctly, and the blow up at $x=a$ occurs with the same sign around both sides.  In that case $\text{arg}(f_A)$ will be either $\pi/2$ or $-\pi/2$, with no jump at all, at $x=a$.


Q: Class with multiple interfaces i have 2 interfaces inter1 and inter2 and class that implements both of them:
public interface Interface1 {
    method1();
}
public interface Interface2 {
    method2();
}
public class Implementer implements Interface1, Interface2 {
    method1() {
         // something
    }
    method2() {
         // something
    }
}
public class Test {
    public static void main(String[] args) {
        Interface1 obj = quest();
        obj.method1();
        if(obj instanceof Interface2) {
            obj.method2(); //exception
        }
    }

    public static Interface1 quest() {
        return new cl();
    }
}

How to cast obj to Interface2 and call method2() or it is possible to call method2() without casting ?

A: If you write inter1 obj = ... then you will not be able to write obj.method2) unless you cast to inter2 or to a type that implements inter2.
For example
inter1 obj = quest();
if (obj instanceof class1)
    ((class1) obj).method2();

or
inter1 obj = quest();
if (obj instanceof inter2)
    ((inter2) obj).method2();

As an aside, when you write in Java you normally give classes and interfaces names that begin the a capital letter, otherwise you confuse people reading your code.

A: Using genecics it is possible to declare generic reference implementing more than one type. You can invoke method from each interface it implements without casting. Example below:
public class TestTwoTypes{

    public static void main(String[] args) {
        testTwoTypes();
    }

    static <T extends Type1 & Type2> void testTwoTypes(){
        T twoTypes = createTwoTypesImplementation();
        twoTypes.method1();
        twoTypes.method2();
    }

    static <T extends Type1 & Type2> T createTwoTypesImplementation(){
        return (T) new Type1AndType2Implementation();
    }
}

interface Type1{

    void method1();
}

interface Type2{
    void method2();
}

class Type1AndType2Implementation implements Type1, Type2{

    @Override
    public void method1() {
        System.out.println("method1");
    }

    @Override
    public void method2() {
        System.out.println("method2");
    }
}

The output is:
method1
method2

A: If you want to do this in spring, the general idea would be:
// Test.java
public class Test {
    private final Interface1 i1;
    private final Interface2 i2;
    public Test(Interface1 i1, Interface2 i2) {
        this.i1 = i1;
        this.i2 = i2;
    }
}

<!-- application-context.xml -->
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
    <bean id="implementer" class="org.mypackage.Implementer" />
    <bean id="test" class="org.mypackage.Test">
        <constructor-arg ref="implementer"/>
        <constructor-arg ref="implementer"/>
    </bean>
</beans>

// Main.java
public static void main(String[] args) {
    ApplicationContext context = new ClassPathXmlApplicationContext("application-context.xml");
    Test t = (Test) context.getBean("test");
}


Q: How to set Image as pdf page background I'm having problems to use an image as background in table column. I need the image to be the background of each page in pdf.
The image is being displayed but it seems to be zoomed in. It sizes are width : 2487px, heigth : 3516px (width : 21.06cm, height : 29.77cm).
This is my code:
<xsl:template name="template-body">
        <fo:block backgorund-color="yellow">
            <fo:table>
                <fo:table-column background-image="image.jpg"/>
                <fo:table-body>
                    <fo:table-row height="29.7cm">
                        <fo:table-cell>
                            <fo:block color="white">
                                SOME TEXT INSIDE THE IMAGE
                            </fo:block>
                        </fo:table-cell>
                    </fo:table-row>
                </fo:table-body>
            </fo:table>
        </fo:block>

    </xsl:template>

This code generates this:

But i need this:

I also tried  to put the image as background of <fo:region-body> but i had the same problem. I think i need some way to specify the image width and height.
Any help? Thanks in advance.

A: Since you are using FOP, I believe there is no provision to scale a background-image to fit. This would be an extension to the XSL FO Specification.
RenderX XEP supports this (http://www.renderx.com/reference.html#Background_Image).
It is unclear if you actually want the image behind the table (and you have other content) or you actually want the image behind the whole page.
You could put the image in an absolute positioned block-container and use content-width and content-height to scale, but this is not going to repeat for only the table. This would work for the page. If it is only the table, you are likely going to have to resize the actual image to fit correctly.


Q: Magento manipulate weight on checkout I have simple products in Magento 1.9 that I can combine ship and would like to change the total shipping weight at checkout (and in shopping cart view for shipping estimate calculation etc) based on sku. For example, if one or two widgets with the correct sku are purchased, their weight is 1 lbs combined. If three to five widgets with the correct sku are purchased, their weight is 2 lbs combined etc. Tablerates could handle this if all items were included. However, I must limit it to certain items determined by sku.
So currently in Magento, each item has a weight of 1 lbs and total weight is number of items * 1 lbs. I have found answers to display total weight, or update the item's weight in the database, but nothing that fulfills these requirements. I'm very new to Magento and am struggling to achieve this. If you reply back with suggested code changes, could you please be specific as to the file's location that should be edited?
Edit
Following Mladen Ilić's suggestions, I have come up with the follow code that calculates the total weight on the event sales_quote_collect_totals_after event. How do I send the new adjusted weight to Magneto to use it through checkout?
/app/etc/modules/Weight_Extension.xml
<?xml version="1.0"?>
<config>
    <modules>
        <Weight_Extension>
            <codePool>local</codePool>
            <active>true</active>
        </Weight_Extension>
    </modules>
</config>

/app/code/locale/Weight/Extension/etc/config.xml
<?xml version="1.0"?>
<config>
    <modules>
        <Weight_Extension>
            <version>0.0.1</version>
        </Weight_Extension>
    </modules>
    <global>
        <models>
            <weight_extension>
                <class>Weight_Extension_Model</class>
            </weight_extension>
        </models>
        <events>
            <sales_quote_collect_totals_after>
                <observers>
                    <weight_extension>
                        <class>weight_extension/observer</class>
                        <method>adjustTotalWeight</method>
                    </weight_extension>
                </observers>
            </sales_quote_collect_totals_after>
        </events>
    </global>
</config>

/app/code/locale/Weight/Extension/Model
<?php
class Weight_Extension_Model_Observer
{
    public function adjustTotalWeight($observer)
    {
        $items = Mage::getSingleton('checkout/session')->getQuote()->getAllItems();

        $combinedItems = 0;
        foreach($items as $item)
        {
            if($item->getSku() == 1 || $item->getSku() == 2)
            {
                 $combinedItems++;
            }
        }

        if($combinedItems > 0 && $combinedItems < 3)
            $weight = 1;
        if($combinedItems >= 3 && $combinedItems < 6)
            $weight = 2;

        //send new $weight to Magento and persist through checkout?
    }
}

How do I send the new adjusted weight to Magneto to use it through checkout?

A: Magento calculates weight used for getting shipping rates in Mage_Sales_Model_Quote_Address_Total_Shipping::collect.
When collecting shipping address totals, items are looped and their weight accumulated and then set to address object.
That being said, you have to be careful how are you going to change this behavior. On a first look, it seems that using sales_quote_collect_totals_after event could be the right way.
When event is triggered get all shipping address items, loop through them and use custom logic for calculating weight.
Best of luck.

A: You writted event in adminhtml context, you have to change it to frontend.


Q: sound for notification I want to play an mp3 sound when my Notification is triggered. For this, I have put an mp3 file in my "res/raw" folder and used the following instruction:
notification.sound=Uri.parse("android.resource://"+getPackageName()+"/" + R.raw.mySound);.
But I am getting no sound when the Notifications appears!
Any idea?

A: I found an example here -

*

*How to play an android notification sound
This is the code that is used
try {
        Uri notification = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
        Ringtone ring = RingtoneManager.getRingtone(getApplicationContext(), notification);
        ring.play();
    } catch (Exception e) {}

On the other hand, if you want to customize the sound (as I ausume you do), you should use this code taken from here
notification.sound = Uri.parse("android.resource://" + getPackageName() + "/" + R.raw.notifysnd);
notification.defaults = Notification.DEFAULT_LIGHTS | Notification.DEFAULT_VIBRATE

;

A: Simply put this below code inside the block which will be triggered when notification occurs..
mMediaPlayer = new MediaPlayer();
mMediaPlayer = MediaPlayer.create(this, R.raw.mySound);
mMediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
mMediaPlayer.setLooping(true);  // Set false if you don't want it to loop
mMediaPlayer.start();


Q: XAML GridView to GridView Drag and Drop Mouse vs Touch Here's XAML code where you can drag and drop GridView elements between different GridViews, however, this approach only works with mouse input and just partially with touch input.
With touch input the elements "unlock" from the GridView only on vertical drag. On horizontal drag the UI tries to scroll the screen instead of just moving the GridView element.
So mouse works perfectly and touch works only on inital vertical drag, after the inital vertical drag you can move the element around just as you could with mouse. This is a Windows 8 app.
<Page.Resources>
        <DataTemplate x:Key="ItemTemplate1">
            <Border Background="#25BDC0">
                <Grid Width="230" Height="230" Margin="10">
                    <TextBlock Text="{Binding Title}" Style="{StaticResource HeaderTextStyle}"
                               HorizontalAlignment="Center" VerticalAlignment="Center"/>
                </Grid>
            </Border>
        </DataTemplate>
    </Page.Resources>

    <Grid Background="{StaticResource ApplicationPageBackgroundThemeBrush}" Width="Auto" Height="Auto">
        <Grid.ColumnDefinitions>
            <ColumnDefinition />
            <ColumnDefinition />
        </Grid.ColumnDefinitions>
        <GridView Grid.Column="0" ItemTemplate="{StaticResource ItemTemplate1}"
            ItemsSource="{Binding FirstCollection}"
            AllowDrop="True" CanDragItems="True"
            DragItemsStarting="GridViewDragItemsStarting"
            Drop="GridViewDrop" Margin="10">
        </GridView>
        <GridView Grid.Column="1" ItemTemplate="{StaticResource ItemTemplate1}"
            ItemsSource="{Binding SecondCollection}"
            AllowDrop="True" CanDragItems="True"
            DragItemsStarting="GridViewDragItemsStarting"
            Drop="GridViewDrop" Margin="10">
        </GridView>
    </Grid>

A: I've stumbled upon the same issue and found the answer here :
http://social.msdn.microsoft.com/Forums/windowsapps/en-US/7fcf8bb8-16e5-4be8-afd3-a21e565657d8/drag-and-drop-gridview-items-and-disabled-scrollbar
It appears that with a GridView you can't initiate the drag horizontally, you have to do it vertically and it's the exact opposite with the ListView.
So if you want to drag 'n drop items horizontally you have to use a ListView. (as recommended in the MS guidelines http://msdn.microsoft.com/en-us/library/windows/apps/hh465299.aspx )
Regards


Q: How to get the connected SSID in Xamarin.Forms? I need to get the SSID of the current network that I am connected to.
Here is the code I used to find the SSID in Xamarin.Android:
WifiManager wifiManager = (WifiManager)(Application.Context.GetSystemService(WifiService));

if (wifiManager != null)
{
    var ssid =  wifiManager.ConnectionInfo.SSID;
}
else
{
    var str =  "WiFiManager is NULL";
}

But I need to implement this in Xamarin.Forms.
How can I do this ?

A: You can use DependencyService.

The DependencyService class is a service locator that enables Xamarin.Forms applications to invoke native platform functionality from shared code.

1º
Create a public interface (for organization sake, maybe under Mobile > Services > IGetSSID)
public interface IGetSSID
{
    string GetSSID();
}

2º Create the Android Implementation
[assembly: Dependency(typeof(GetSSIDAndroid))]
namespace yournamespace
{
    public class GetSSIDAndroid : IGetSSID
    {
        public string GetSSID()
        {
            WifiManager wifiManager = (WifiManager)(Android.App.Application.Context.GetSystemService(Context.WifiService));

            if (wifiManager != null && !string.IsNullOrEmpty(wifiManager.ConnectionInfo.SSID))
            {
                return wifiManager.ConnectionInfo.SSID;
            }
            else
            {
                return "WiFiManager is NULL";
            }
        }
    }
}

3º
Then in your forms you get the SSID like this:
var ssid = DependencyService.Get<IGetSSID>().GetSSID();

Note: Don't forget to add this permission on your Android Manifest
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />

A: Get SSID and BSSID API31 Xamarin C# Example
Required permissions: CHANGE_NETWORK_STATE, ACCESS_FINE_LOCATION
If API<31 TransportInfo will return Null
using Android.Content;
using Android.Net;
using Android.Net.Wifi;

protected override void OnStart()
    {
        base.OnStart();

        NetworkRequest request = new NetworkRequest.Builder().AddTransportType(transportType: TransportType.Wifi).Build();
        ConnectivityManager connectivityManager = Android.App.Application.Context.GetSystemService(Context.ConnectivityService) as ConnectivityManager;

        NetworkCallbackFlags flagIncludeLocationInfo = NetworkCallbackFlags.IncludeLocationInfo;
        NetworkCallback networkCallback = new NetworkCallback((int)flagIncludeLocationInfo);
        connectivityManager.RequestNetwork(request, networkCallback);
    }

    private class NetworkCallback : ConnectivityManager.NetworkCallback
    {
        public NetworkCallback(int flags) : base(flags)
        {
        }

        public override void OnCapabilitiesChanged(Network network, NetworkCapabilities networkCapabilities)
        {
            base.OnCapabilitiesChanged(network, networkCapabilities);
            WifiInfo wifiInfo = (WifiInfo)networkCapabilities.TransportInfo;

            if (wifiInfo != null)
            {
                string ssid = wifiInfo.SSID.Trim(new char[] {'"', '\"' });
                string bssid = wifiInfo.BSSID;
            }
        }
    }

Click Android API reference.ConnectivityManager.NetworkCallback(int)!


Q: Formula to reference data from a PivotTable I am having some difficulty writing a specific Excel formula. I have a summary sheet that pulls data from various other sheets extracted from a database. One of these is a PivotTable whereby using the Item Number in the first column and the dates along the top row as a reference I can pinpoint the data I need. eg:

To address the highlighted cell I would normally manually write:
=GETPIVOTDATA(HighPiv,"SPN010977-204 11333")

HighPiv is the name I gave to the pivot table as I am referring to it from my summary sheet.
This works, however the Week numbers along the top will continuously be changing in the pivot every month and therefore this formula will not pick up the values accurately once the pivot is updated. I have been looking into a way to make the referencing more dynamic. This is the summary where the data is required:

Rather than within the quotation marks of the formula (adding the specific Item number and Week number word for word), I was hoping to refer to the cell references of the summary sheet. (So if I wanted Item number, say A55, and Week number, say H50). The dates in the summary sheet change according to the pivot so referring to the dates on the summaries to get the data would be a better way for it to be kept up-to-date.
The problem here is I don't know how to go about it. I have tired to refer to the cells in question but it doesn't seem to work giving me #REF! or #VALUE! errors.

A: I think what you would like is:

=GETPIVOTDATA("Qty",HighPiv,"Item",A55,"Week",H50)

I find the easiest way to write such a formula is to start by ensuring that Pivot Table Tools > Options > PivotTable – Options, Generate GetPivotData is checked then in the desired cell enter = and select the required entry from the PT (here63). That would show (for example) “SPN010977-204” and 11333 or ”11333” but these can be changed to A55 and H50.


Q: How Would I replace a string if its input in a certain order? var xboxConverter = {
  "1" : "Up",
  "2" : "Down",
  "3" : "Down Foward",
  "4" : "Backward",
  "5" : "Standing",
  "6" : "Forward",
  "7" : "Up Backward",
  "8" : "Up",
  "9" : "Up Foward",
  "236S": "Quarter Circle Special",
  ",": "  ",
  "H" : "B",
  "M": "Y",
  "L": "X",
  "S": "A",
  "2" : "Down",
  "RB" : "RB",
  "236" : "Quarter Circle Forward",
  "214" : "Quarter Circle Backwards",
  "214S" : "Quarter Circle Backwards Special",

};

document.querySelector("textarea").addEventListener("keyup", (e) => {
  const input = e.target.value.toUpperCase();
  const inputValidated = input.replace(/[^a-zA-Z0-9 ,]/g, "");
  const arrOfIns = inputValidated.split(" ");
  const arrOfOuts = arrOfIns.map((e) =>
    xboxConverter[e] ? xboxConverter[e] : ""
  );
if (parseInt.innerText == 236 & 214)
return
  const out = arrOfOuts.join(" , ");
  document.getElementById("output").innerText = out;

});

To better describe what I mean if someone inputs 236 together it should say "Quarter Circle Forward" or if they input 236RT it should say "Quarter Circle Forward Right Trigger".

A: From your comments, I can understand that you are looking for a value matching the key that the user inputs. You can simply check for it without any splits and for loops like:

var xboxConverter = {
  "1": "Up",
  "2": "Down",
  "3": "Down Foward",
  "4": "Backward",
  "5": "Standing",
  "6": "Forward",
  "7": "Up Backward",
  "8": "Up",
  "9": "Up Foward",
  "236S": "Quarter Circle Special",
  ",": "  ",
  "H": "B",
  "M": "Y",
  "L": "X",
  "S": "A",
  "2": "Down",
  "RB": "RB",
  "236": "Quarter Circle Forward",
  "214": "Quarter Circle Backwards",
  "214S": "Quarter Circle Backwards Special",

};

document.querySelector("textarea").addEventListener("keyup", (e) => {
  const input = e.target.value.toUpperCase();
  const inputValidated = input.replace(/[^a-zA-Z0-9 ,]/g, "");
  document.getElementById("output").innerText = xboxConverter[inputValidated] ? xboxConverter[inputValidated] : "No data";
});
<textarea></textarea>

Is this what you're looking for?


Q: How to bring BigDecimal to fractional power? BigDecimal was the choice to store numbers that have up to 5 digits after decimal point. I need to raise the BigDecimal to fractional power (up to 2 digits after decimal point).
For example I have to bring 9.09671 to power of 1.51. Do I need some conversions from/to BigDecimal? How to do it?
EDIT:
I cannot use 3rd party libraries as described in Java's BigDecimal.power(BigDecimal exponent): Is there a Java library that does it?
Is there more elegant, succint way for this case than described in How to do a fractional power on BigDecimal in Java?


Q: multi-part identifier could not be bound on insert from another database on another server I am trying to insert information from one database on one server into a table on another with out inserting a duplicate and i get the title error. here is the code
INSERT INTO [Datamaxx].[dbo].[data_job_t] (JobCode, Description)
SELECT job_no, description
FROM OPENDATASOURCE('SQLNCLI',
'Data Source=server\server;Integrated Security=SSPI')
.cas_tekworks.dbo.jobs WHERE Job_Status ='A' and data_job_t.JobCode  not in (select Jobcode from [Datamaxx].[dbo].[data_job_t])

A: Did you tried this....
job_no not in instead of data_job_t.JobCode
INSERT INTO [Datamaxx].[dbo].[data_job_t] (JobCode, Description)
SELECT job_no, description
FROM OPENDATASOURCE('SQLNCLI',
'Data Source=server\server;Integrated Security=SSPI')
.cas_tekworks.dbo.jobs WHERE Job_Status ='A' and job_no not in (select Jobcode from [Datamaxx].[dbo].[data_job_t])


Q: image auto rotate counterclockwise when width is less than height My all images auto rotate counterclockwise when width is less than height.
Example: this example
Help me please! Thanks!


Q: Javascript, find object in list of objects by id I have a list of objects in where I need to find one specifically by an ID. So very simply like so:
{
 {
   "id": "1"
 },{
   "id": "2"
 }
}

I have a function where I want to find the object by it's id, that does not work like so
 function findOb (id) {

   return _.find(myList, function(obj) { return obj.id === id } );

 }

it is not returning the correct object (this is using lodash) uncertain what I am doing incorrect and could use some help. Thanks!
edit - I don't know if this helps but I am building and trying to search an object in this format - https://github.com/pqx/react-ui-tree/blob/gh-pages/example/tree.js . So there are just objects with module and leaf sometimes, and I want to be able to search and find by the 'module' key. Thanks for the feedback everyone!

A: Your code should have worked, but it can be simplified.
If you provide a property name for the predicate argument to _.find, it will search that property for the thisArg value.
function findOb(id) {
    return _.find(myList, 'id', id);
}

The only problem I can see with your code is that you use === in your comparisons. If you pass 1 as the ID argument instead of "1", it won't match because === performs strict type checking.


Q: Does Azure TableQuery handle continuation tokens internally? I'm trying to find a definitive answer to the question of continuation tokens and the Azure Storage Library 2.0, as there seems to be significant differences between pre-2.0 versions (StorageClient) and the current version (Storage).
Aside from the MSDN documentation, which doesn't clarify the above question for me, its very hard to find information on continuation tokens which specifically relates to version 2.0 and above of the library, because earlier versions are named so similarly (CloudTableQuery vs TableQuery) search results get polluted with information about the earlier versions.
So, are continuation tokens handled internally on the Microsoft.WindowsAzure.Storage client (version 2.0 of the storage library)?  Can I trust that the result sets I get back are the full result sets?
Thanks!

A: There're two methods in question when it comes to executing queries against a table: CloudTable.ExecuteQuery and CloudTable.ExecuteQuerySegmented. The first one (ExecuteQuery) will handle the continuation token internally while the second one (ExecuteQuerySegmented) will return you the continuation token as a part of result set which you can use to fetch next set of data.


Q: pulling out list from wordpress post I want to pull out the list (ul) element from my wordpress post(s) so I can put it in a different location.
My current css pulls out the images and blockqute and puts just the text
html
<?php
  $content = preg_replace('/
(.*?)<\/blockquote>/', '', get_the_content());
  $content = preg_replace('/(]*>)/', '', $content);
  $content = wpautop($content); // Add paragraph-tags
  $content = str_replace('

', '', $content); // remove empty paragraphs
    echo $content;
?>

A: Just a friendly reminder is that it is generally not recommended to parse html with regex.
If you would like to do that anyway you could try like this:
$pattern = '~
(.*?)
~s';

So in your code it would look like this:
preg_match_all('/(~
(.*?)
~s)/', $content, $ulElements);

And then for removing it from the original string:
preg_replace('/(~
(.*?)
~s)/', '', $content);


Q: Android java.lang.OutOfMemoryError: GC overhead limit exceeded I got an error as of title. I know there are many answers but it didn't works.
What I did already,
First.
add code on build.gradle(Module:app)
"multiDexEnabled true" at defaultConfig  &
"compile 'com.android.support:multidex:1.0.1'" at dependencies
add code on AndroidMenifest
android:name="android.support.multidex.MultiDexApplication" at application
Second.
add code on build.gradle(Project:~~)(I also tried on build.gradle(Module:app)
"dexOptions{
             javaMaxHeapSize "2g" (I also tried for "4g"
}"
First one was not works which means show same error.(Out of memory)
Second one was show another error(could not find method~~) which means I use higher targetSDKVersion to use it.(My app is 23 for targetSDKVersion.)
So there were no answer until I tried google it....
How could I solve it....?
is there anybody who can help me?
I'm waiting for you such a kind person.... Thank you in advance.....


Q: Ist possible to convert my own HTML to PDF, without breaking the pages, preserving the formatting and supporting the hyperlinks? I have already searched for many questions at Stackoverflow, but I really didn't consider the questions and the answers for my needs. DocRaptor is really not a good app because it breaks the pages and it doesn't recognise the extended Latin letters, as à, é, ã,, etc.
I used many HTML to PDF converter web-based apps, it didn't work for me, because they didn't preserve the formatting and the hyperlinks.
I used capture apps for Mac, as W3Capture and Layouts.1) Layouts capture one whole HTML and CSS page as a PDF without breaking the pages and also preserving the formatting. But, it didn't support the hyperlinks, because it captures the page as PDF, behaving as PNG-like.
2) W3captures supports the hyperlinks, converting the HTML/CSS pages, but it breaks the pages and really doesn't preserve the formatting.
I also tested TextEdit, which can exports as PDF, but when it exports as PDF, it breaks the pages. Pages from iWork and Word also do it.
I'm really frustrated.
Is it possible to convert the own HTML page to PDF, without breaking the pages, preserving the formatting and supporting the hyperlinks?

A: I think you can open you html file in Chrome. Then print it to pdf format. Then it will works.
That is when you print it, you choose "save as pdf" rather than your printer.


Q: is there a way to allow a phone "-" in phone format using numeric in vuelidate? I'm using vuelidate to validate a form in VUE build. I have a phone number input that needs to be formatted as 222-222-2222 which I have setup using a phone mask. My issue is now the input will not validate when the phone is filled in. My error message is still displayed. Is there a way to allow for numbers only along with a dash "-"???

          Phone Number

        <input type="text" class="form-input text-input" name="phone" id="phone" @input="phoneNumberMask()"
               v-model.trim="$v.formData.phone.$model">

          Please enter a valid phone number.

    validations: {
      formData: {
        phone: {
          required,
          numeric,
          minLength: minLength(12),
          maxLength: maxLength(12)
         }
        }
       }

methods: {
  phoneNumberMask(){
        const x = this.formData.phone.replace(/\D/g, '').match(/(\d{0,3})(\d{0,3})(\d{0,4})/);
        this.formData.phone = !x[2] ? x[1] : x[1] + '-' + x[2] + (x[3] ? '-' + x[3] : '');
    },
   }

A: As pointed out in the comments, you can create a regular expression that validates you phone number format, in this case /^[0-9]{3}-[0-9]{3}-[0-9]{4}$/ could be a starting point.
Here a complete example.
<template>

      <input
        class=""
        v-model="number"
        @change="$v.number.$touch()"
        placeholder="Phone number"
      />

NOT VALID

    <button
      class="
        "
      :disabled="$v.$invalid"
      @click="saveClick()"
    >
      Save
    </button>

</template>

Script part
import { required, helpers } from "vuelidate/lib/validators"

const number = helpers.regex(
  "serial",
  /^[0-9]{3}-[0-9]{3}-[0-9]{4}$/
)

export default {
  data() {
    return {
      number: null
    }
  },

  computed: {
    serial: {
      get() {
        return this.number
      },
      set(value) {
        this.number = value
      }
    }
  },
  methods: {
    saveClick() {
      //TODO
    }
  },
  validations: {
    number: {
      required,
      number
    }
  }
}

Note
This is for Vue 2.x and vuelidate ^0.7.6


Q: iPad 2 HDMI out connecter Can the iPad 2's HDMI out adapter, work on the iPhone 4 with ios4.3, as a complete mirror, rather than just video out.
Also on the iPad 2 when using the HDMI out mirror will the onscreen keyboard be displayed on the external screen?

A: The iPad 2's HDMI adapter works as mirror for the iPad but only as video out for the iPhone 4. Also it's only in 720p for the iPhone.
the onscreen keyboard being displayed but my best guess is yes unless your using a bluetooth keyboard.
Hope that helps.

EDIT : it does indeed display the keyboard. When using as a mirror it will only fill the aspect ratio of the iPad but when watching a movie it will fill the screen.

A: Jonathan, yes to both your questions.
A similar and more complete answer is at How to show iOS screen on a projector like Steve Jobs did on his keynotes?


Q: How to implement a Master Detail Form as part of a MultiPageEditor in Eclipse? I have created a sample multi page editor via the Eclipse wizard. Now, I want to extend this editor with a Master Detail Form, so basically, there should be two pages, one standard text editor and the beforesaid Master Detail Form.
Please note: I am using this a demo code for my MasterDetailsPage.java.
Here is my code so far:
MultiPageEditor:
package multipageeditortest.editors;

import java.io.StringWriter;
import java.text.Collator;
import java.util.ArrayList;
import java.util.Collections;
import java.util.StringTokenizer;

import org.eclipse.core.resources.IMarker;
import org.eclipse.core.resources.IResourceChangeEvent;
import org.eclipse.core.resources.IResourceChangeListener;
import org.eclipse.core.resources.ResourcesPlugin;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.jface.dialogs.ErrorDialog;
import org.eclipse.swt.SWT;
import org.eclipse.swt.custom.StyledText;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.graphics.Font;
import org.eclipse.swt.graphics.FontData;
import org.eclipse.swt.layout.FillLayout;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.FontDialog;
import org.eclipse.ui.*;
import org.eclipse.ui.editors.text.TextEditor;
import org.eclipse.ui.part.FileEditorInput;
import org.eclipse.ui.part.MultiPageEditorPart;
import org.eclipse.ui.ide.IDE;

/**
 * An example showing how to create a multi-page editor.
 * This example has 3 pages:
 *

 *
page 0 contains a nested text editor.
 *
page 1 allows you to change the font used in page 2
 *
page 2 shows the words in page 0 in sorted order
 *

 */
public class MultiPageEditor extends MultiPageEditorPart implements IResourceChangeListener{

    /** The text editor used in page 0. */
    private TextEditor editor;

    /** The font chosen in page 1. */
    private Font font;

    /** The text widget used in page 2. */
    private StyledText text;
    /**
     * Creates a multi-page editor example.
     */
    public MultiPageEditor() {
        super();
        ResourcesPlugin.getWorkspace().addResourceChangeListener(this);
    }
    /**
     * Creates page 0 of the multi-page editor,
     * which contains a text editor.
     */
    void createPage0() {
        try {
            editor = new TextEditor();
            int index = addPage(editor, getEditorInput());
            setPageText(index, editor.getTitle());
        } catch (PartInitException e) {
            ErrorDialog.openError(
                getSite().getShell(),
                "Error creating nested text editor",
                null,
                e.getStatus());
        }
    }
    /**
     * Creates page 1 of the multi-page editor,
     * which allows you to change the font used in page 2.
     */
    void createPage1() {

        Composite composite = new Composite(getContainer(), SWT.NONE);
        GridLayout layout = new GridLayout();
        composite.setLayout(layout);
        layout.numColumns = 2;

        Button fontButton = new Button(composite, SWT.NONE);
        GridData gd = new GridData(GridData.BEGINNING);
        gd.horizontalSpan = 2;
        fontButton.setLayoutData(gd);
        fontButton.setText("Change Font...");

        fontButton.addSelectionListener(new SelectionAdapter() {
            public void widgetSelected(SelectionEvent event) {
                setFont();
            }
        });

        int index = addPage(composite);
        setPageText(index, "Properties");
    }
    /**
     * Creates page 2 of the multi-page editor,
     * which shows the sorted text.
     */
    void createPage2() {
        Composite composite = new Composite(getContainer(), SWT.NONE);
        FillLayout layout = new FillLayout();
        composite.setLayout(layout);
        text = new StyledText(composite, SWT.H_SCROLL | SWT.V_SCROLL);
        text.setEditable(false);

        int index = addPage(composite);
        setPageText(index, "Preview");
    }

    void createMasterDetailPage() {
        int index = addPage(new MasterDetailsPage(this)); // ERROR
        setPageText(index, "Master Detail Page");
    }

    /**
     * Creates the pages of the multi-page editor.
     */
    protected void createPages() {
        createPage0();
        createPage1();
        createPage2();
        createMasterDetailPage();
    }
    /**
     * The MultiPageEditorPart implementation of this
     * IWorkbenchPart method disposes all nested editors.
     * Subclasses may extend.
     */
    public void dispose() {
        ResourcesPlugin.getWorkspace().removeResourceChangeListener(this);
        super.dispose();
    }
    /**
     * Saves the multi-page editor's document.
     */
    public void doSave(IProgressMonitor monitor) {
        getEditor(0).doSave(monitor);
    }
    /**
     * Saves the multi-page editor's document as another file.
     * Also updates the text for page 0's tab, and updates this multi-page editor's input
     * to correspond to the nested editor's.
     */
    public void doSaveAs() {
        IEditorPart editor = getEditor(0);
        editor.doSaveAs();
        setPageText(0, editor.getTitle());
        setInput(editor.getEditorInput());
    }
    /* (non-Javadoc)
     * Method declared on IEditorPart
     */
    public void gotoMarker(IMarker marker) {
        setActivePage(0);
        IDE.gotoMarker(getEditor(0), marker);
    }
    /**
     * The MultiPageEditorExample implementation of this method
     * checks that the input is an instance of IFileEditorInput.
     */
    public void init(IEditorSite site, IEditorInput editorInput)
        throws PartInitException {
        if (!(editorInput instanceof IFileEditorInput))
            throw new PartInitException("Invalid Input: Must be IFileEditorInput");
        super.init(site, editorInput);
    }
    /* (non-Javadoc)
     * Method declared on IEditorPart.
     */
    public boolean isSaveAsAllowed() {
        return true;
    }
    /**
     * Calculates the contents of page 2 when the it is activated.
     */
    protected void pageChange(int newPageIndex) {
        super.pageChange(newPageIndex);
        if (newPageIndex == 2) {
            sortWords();
        }
    }
    /**
     * Closes all project files on project close.
     */
    public void resourceChanged(final IResourceChangeEvent event){
        if(event.getType() == IResourceChangeEvent.PRE_CLOSE){
            Display.getDefault().asyncExec(new Runnable(){
                public void run(){
                    IWorkbenchPage[] pages = getSite().getWorkbenchWindow().getPages();
                    for (int i = 0; i<pages.length; i++){
                        if(((FileEditorInput)editor.getEditorInput()).getFile().getProject().equals(event.getResource())){
                            IEditorPart editorPart = pages[i].findEditor(editor.getEditorInput());
                            pages[i].closeEditor(editorPart,true);
                        }
                    }
                }
            });
        }
    }
    /**
     * Sets the font related data to be applied to the text in page 2.
     */
    void setFont() {
        FontDialog fontDialog = new FontDialog(getSite().getShell());
        fontDialog.setFontList(text.getFont().getFontData());
        FontData fontData = fontDialog.open();
        if (fontData != null) {
            if (font != null)
                font.dispose();
            font = new Font(text.getDisplay(), fontData);
            text.setFont(font);
        }
    }
    /**
     * Sorts the words in page 0, and shows them in page 2.
     */
    void sortWords() {

        String editorText =
            editor.getDocumentProvider().getDocument(editor.getEditorInput()).get();

        StringTokenizer tokenizer =
            new StringTokenizer(editorText, " \t\n\r\f!@#\u0024%^&*()-_=+`~[]{};:'\",.<>/?|\\");
        ArrayList editorWords = new ArrayList();
        while (tokenizer.hasMoreTokens()) {
            editorWords.add(tokenizer.nextToken());
        }

        Collections.sort(editorWords, Collator.getInstance());
        StringWriter displayText = new StringWriter();
        for (int i = 0; i < editorWords.size(); i++) {
            displayText.write(((String) editorWords.get(i)));
            displayText.write(System.getProperty("line.separator"));
        }
        text.setText(displayText.toString());
    }
}

MasterDetailsPage:
public class MasterDetailsPage extends FormPage {
    private ScrolledPropertiesBlock block;
    public MasterDetailsPage(FormEditor editor) {
        super(editor, "fourth", "test"); //$NON-NLS-1$ //$NON-NLS-2$
        block = new ScrolledPropertiesBlock(this);
    }
    protected void createFormContent(final IManagedForm managedForm) {
        final ScrolledForm form = managedForm.getForm();
        //FormToolkit toolkit = managedForm.getToolkit();
        form.setText("Test"); //$NON-NLS-1$
        block.createContent(managedForm);
    }
}

The problem is in this method:
void createMasterDetailPage() {
    int index = addPage(new MasterDetailsPage(this)); // ERROR
    setPageText(index, "Master Detail Page");
}

How can I add the MasterDetailsPage to my MultiPageEditor?

A: You normally use FormEditor rather than MultiPageEditorPart when using FormPage (FormEditor extends MultiPageEditorPart).
FormEditor has an addPage that accepts a FormPage.


Q: Upload,read and display the image with Tkinter and Opencv-Python I want to upload this file using tkinter method and read it using cv2.imread and display .But i have a problem,this is the code i am using:
wid=Tk()
def myown():
file = tkFileDialog.askopenfile(parent=wid,mode='rb',title='Choose a file')
if file != None:
   data = file.read()
   b=cv2.imread(data)
   cv2.imshow('img',b)
   cv2.waitKey(0)

   file.close()

after this,
  wid3=Button(None,text="upload it",command=myown)
  wid.mainloop

but i am getting an opencv error,the image is not being displayed by the imshow,it says size.width>0 && size.height>0


Q: Not getting the right result in base64 string when I try to convert base64 encoded string EC Public Key generated on iOS to Java PublicKey As the title suggests I am trying to convert base64 encoded string (EC Public Key) generated on IOS device(Swift) to Java PublicKey which will be used to calculate a Shared Secret Key between two parties. There is neither runtime nor compile time exception/error in the code, it compiles and runs successfully and generates a PublicKey but when I encode the PublicKey (Base64.encodeToString(PublicKey.encoded), Base64.NO_WRAP) back to Base64 string to confirm whether I have gotten the same public key I have passed as an argument, they are not the same.
import android.util.Base64
import org.bouncycastle.asn1.sec.SECNamedCurves
import org.bouncycastle.math.ec.ECCurve
import java.math.BigInteger
import java.nio.charset.StandardCharsets
import java.security.*
import java.security.spec.*
import javax.crypto.*
import javax.crypto.spec.IvParameterSpec
import javax.crypto.spec.SecretKeySpec

fun iosB64EncodedStrPKToPK(iOSB64EncodedPK: String): PublicKey {
    val decodedPK = Base64.decode(iOSB64EncodedPK, Base64.NO_WRAP)
    val x9ECParamSpec = SECNamedCurves.getByName("secp256r1")
    val curve = x9ECParamSpec.curve
    val point = curve.decodePoint(decodedPK)
    val xBcEC = point.affineXCoord.toBigInteger()
    val yBcEC = point.affineYCoord.toBigInteger()
    val gBcEC = x9ECParamSpec.g
    val xGBcEC = gBcEC.affineXCoord.toBigInteger()
    val yGBcEC = gBcEC.affineYCoord.toBigInteger()
    val hBcEC = x9ECParamSpec.h.toInt()
    val nBcEC = x9ECParamSpec.n
    val jPEC = ECPoint(xBcEC, yBcEC)
    val gJpEC = ECPoint(xGBcEC, yGBcEC)
    val jEllipticCurve = convertECCurveToEllipticCurve(curve, gJpEC, nBcEC, hBcEC)
    val eCParameterSpec = ECParameterSpec(jEllipticCurve, gJpEC, nBcEC, hBcEC)
    val ecPubLicKeySpec = ECPublicKeySpec(jPEC, eCParameterSpec)
    val keyFactorySpec = KeyFactory.getInstance("EC")
    return keyFactorySpec.generatePublic(ecPubLicKeySpec)
}

private fun convertECCurveToEllipticCurve(
    curve: ECCurve,
    ecPoint: ECPoint,
    n: BigInteger,
    h: Int
): EllipticCurve {
    val ecField = ECFieldFp(curve.field.characteristic)
    val firstCoefficient = curve.a.toBigInteger()
    val secondCoefficient = curve.b.toBigInteger()
    val ecParams = ECParameterSpec(
        EllipticCurve(ecField, firstCoefficient, secondCoefficient),
            ecPoint,
            n,
            h
        )
    return ecParams.curve
}

The public key I am passing to the iosB64EncodedStrPKToPK() function: BAlWWu46il/ly6Axd/qclmhEVhGth93QN5+h3JBJEKEmhKd1LfqkpCqX1cT1cQDs9nPq9Lq0/FtZitkjr7Rqd94=
The output I get: MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAECVZa7jqKX+XLoDF3+pyWaERWEa2H3dA3n6HckEkQoSaEp3Ut+qSkKpfVxPVxAOz2c+r0urT8W1mK2SOvtGp33g==
val pkIOS = "BAlWWu46il/ly6Axd/qclmhEVhGth93QN5+h3JBJEKEmhKd1LfqkpCqX1cT1cQDs9nPq9Lq0/FtZitkjr7Rqd94="

Log.i("SOME_TAG","PUBLIC_KEY_IOS:${Base64.encodeToString(iosB64EncodedStrPKToPK(pkIOS).encoded,Base64.NO_WRAP)}")

I am not an expert on the matter, maybe someone may guide me in the right direction and can see the mistake I am making. Cryptography is out of my field expertise.
I have tried Googling, ChatGPT and other insightful resources, if you know a source around the issue I would gladly accept it too.
I am running the code in an Android Environment
The version of BouncyCastle I am using:
def bouncy_castle_version = '1.70'
implementation "org.bouncycastle:bcpkix-jdk15on:$bouncy_castle_version"
implementation "org.bouncycastle:bcprov-jdk15on:$bouncy_castle_version"

A: The keys are identical, only their formats differ:

*

*The input BAlW... is an uncompressed public EC key (Base64 encoded).

*The output MFkw... is an ASN.1/DER encoded key in X.509/SPKI format (Base64) encoded.

This can be easily verified by encoding both keys not in Base64 but in hex:
input :                                                     0409565aee3a8a5fe5cba03177fa9c9668445611ad87ddd0379fa1dc904910a12684a7752dfaa4a42a97d5c4f57100ecf673eaf4bab4fc5b598ad923afb46a77de
output: 3059301306072a8648ce3d020106082a8648ce3d0301070342000409565aee3a8a5fe5cba03177fa9c9668445611ad87ddd0379fa1dc904910a12684a7752dfaa4a42a97d5c4f57100ecf673eaf4bab4fc5b598ad923afb46a77de

As can be seen, the ASN.1/DER encoded X.509/SPKI key contains the uncompressed public key at the end (the last 65 bytes).

Background:
Keep in mind that a public EC key is a point (x, y) on an EC curve (obtained by multiplying the private key by the generator point) and that there are different formats for its representation, e.g. the following two:

*

*The uncompressed format, which corresponds to the concatenation of a 0x04 byte, and the x and y coordinates of the point: 04|x|y.
For the secp256r1 curve (aka prime256v1 aka NIST P-256), x and y are both 32 bytes, so the uncompressed key is 65 bytes.

*The X.509/SPKI format as defined in RFC 5280. This format is described with ASN.1 and serialized/encoded with DER (s. here).
PublicKey#getEncoded() returns the ASN.1/DER encoded X.509/SPKI key. With an ASN.1/DER parser the ASN.1/DER can be decoded, e.g. https://lapo.it/asn1js/.


Q: How can display text only when mouse over I have this sample:
link
CODE HTML:

                SED PERSPICIATIS

                    Sed ut perspiciatis unde omnis iste natus error sit
                    voluptatem accusantium doloremque laudantium,
                    totam rem aperiam, eaque ipsa quae ab illo inventore
                    veritatis et quasi architecto beatae vitae dicta sunt
                    explicabo.

SED PERSPICIATIS

                Sed ut perspiciatis unde omnis iste natus error sit

                voluptatem accusantium doloremque laudantium,

                totam rem aperiam, eaque ipsa quae ab illo inventore

                veritatis et quasi architecto beatae vitae dicta sunt

                explicabo.

SED PERSPICIATIS

                Sed ut perspiciatis unde omnis iste natus error sit

                voluptatem accusantium doloremque laudantium,

                totam rem aperiam, eaque ipsa quae ab illo inventore

                veritatis et quasi architecto beatae vitae dicta sunt

                explicabo.

CODE CSS:
.col-md-4 {
    width: 33.33333333%;
}
.tab-bottom {
    position: relative;
    height: 400px;
    float:left;
}
.tab-bottom-img {
    width: 100%;
    position: absolute;
    top: 50%;
    height: 100%;
    left: 50%;
    transform: translate(-50%, -50%);
}
.tab-bottom-content {
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
}

CODE JS:
$(".tab-bottom").bind('mouseover',function(event){
    $(this).find("tab-bottom-content").css("display", "block");
});
$('.tab-bottom-img').bind('mouseleave', function(e) {

});

I want the text in the div tab-bottom-content to be displayed only when the mouse is over.
I tried to use the script above but unfortunately does not work
Can you help me to solve this problem?
Thanks in advance!

A: I would solve this using CSS instead.
like this fiddle
Example html:

     Test

CSS:
.tab-bottom{
  border: 1px SOLID #F00; /* For display purpose */
  width: 200px;
  height: 200px;
}

.tab-bottom.tab-bottom-content{
  display: none;
}
.tab-bottom:hover .tab-bottom-content{
  display: block;
}

There is no need for JavaScript or jQuery here :)

A: You should initially hide .tab-bottom-content using display: none like following.
.tab-bottom-content {
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    display: none
}

And the use following jQuery. You missed the . before tab-bottom-content
$(".tab-bottom").mouseover(function(event){
    $(this).find(".tab-bottom-content").show(300);
}).mouseleave(function(e) {
    $(this).find(".tab-bottom-content").hide(300);
});

A: You need '.' in this .find("tab-bottom-content")
$(".tab-bottom").on('mouseover',function(event){
    $(this).find(".tab-bottom-content").show(300);
});
$('.tab-bottom').on('mouseleave', function(e) {
    $(this).find(".tab-bottom-content").hide(300);
});

Here is the pen
You must also add CSS
.tab-bottom-content {
    display:none;
 }

or inline style to hide the 'tab-bottom-content' content first

A: You can set the opacity of the tab-bottom-content to 0 and then change it to 1 in its :hover pseudo-selector class so that the text appears when you hover over the tab-bottom-content div. You may even want to add a transition so that the opacity changes smoothly. Do this,
.tab-bottom-content {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  border: 1px solid black;
  opacity: 0;
  transition: opacity .4s ease-in;
}

.tab-bottom-content:hover {
  opacity: 1
}

Check it out https://jsfiddle.net/5s1fv2a9/


Q: C++: Storing user inputs I just want the user to enter some numbers. If the number is -1 the program stops and then outputs those same numbers. Why is that so difficult? I don't understand why the logic is not working here.
For example when the user types:
1 2 3 -1

The program should then print out:
    1
    2
    3
    -1
#include <iostream>

using namespace std;

int main()
{
    int input, index=0;
    int array[200];

    do
    {
        cin >> input;
        array[index++]=input;
    } while(input>0);

    for(int i=0; i < index; i++)
    {
        cout << array[index] << endl;
    }
}

A: Change this
for(int i=0; i < index; i++)
{
    cout << array[index] << endl;
}

To
for(int i=0; i < index; i++)
{
    cout << array[i] << endl;
}

You used index at the seconde loop causing your program to print all the array cell's after the user input.
Also, if -1 is your condition you should change it to
} while(input>=0);
             ^^

Otherwise, also 0 will stop the loop, which is not what you asking for.


Q: Print child category slug nicename I want to print (display) the child category slug, so I can use it in a dynamic url, on categories pages.
 So
 If I am on the category www.example.com/category/main-category/child-category
  Example: www.example.com/category/games/board-games
In the sidebar I will have a link Updates from Board Games
  so I need the code to simply display child-category slug, in this case is "board-games", and child category name, in this case is "Board Games"
on post pages it's simple, I have this code and it's working (maybe someone will find it useful)
<?php $cat_slug = get_the_category(); ?><a href="<?php echo get_bloginfo('url') . "/updates-from-" . $cat_slug[0]->category_nicename; ?>" > Updates from '<?php echo $cat_slug[0]->cat_name . "";?>'

thank you for your help!

A: seems nobody understood 'my question', so I solved it myself here is the code for getting the slug I needed
<?php $cat = get_term_by('name', single_cat_title('',false), 'category'); echo $cat->slug; ?>


Q: Sending email in Asp.net / C# with attachments - Issues with Gmail In an ASP/C# application I'm sending an email with 3 file attached. The 3 files are the same type, same extension and more or less same size ( but none are empty ).
The email is sent correctly. If I open it using outlook, I have no problems. I can see the body, and the 3 files attached.
But here is my issue: If I send that mail to a Gmail Adress, then on Gmail I can see only 2 attachments.

And if I click on the download all attachment icon ( on the right ), it will download the 2 visible attachment + the third one but empty.
It's a really weird issue.
Also there is a 4th attachment which is an embedded image. And this image is display correctly in the mail body.
Here is the code I'm using to send the mail:
            MailMessage mail = new MailMessage();
            SmtpClient SmtpServer = new SmtpClient("SMTP_IP_ADRESS", SMTP_IP_PORT);

            mail.From = new MailAddress("MYEMAIL@DOMAIN.COM");

            mail.To.Add("GMAIL_EMAIL");
            mail.To.Add("OUTLOOK_EMAIL");

            mail.Subject = "MSN "+Request.Params["nameMsn"];

            Attachment imageAttachment = new
            Attachment(Server.MapPath(Url.Content("~/Content/images/image.png")));
            string contentID = "logoCare";
            imageAttachment.ContentId = contentID;
            mail.IsBodyHtml = true;
            mail.Body = "Have a good day.
Best regards.

";

            for (int i = 0; i < Request.Files.Count; i++)
            {
                HttpPostedFileBase file = Request.Files[i];
                var attachment = new Attachment(file.InputStream, file.FileName,
                MediaTypeNames.Application.Octet);
                mail.Attachments.Add(attachment);
            }

            mail.Attachments.Add(imageAttachment);

            SmtpServer.Send(mail);

A: The third attachment you see empty can possibly be the CID embedded image that web based email clients (like Gmail) can't manage, meanwhile it works with desktop email clients like Outlook. Can you verify this?
Please take a look at here


Q: Out of memory errors in Java API that uses finalizers in order to free memory allocated by C calls We have a Java API that is a wrapper around a C API.
As such, we end up with several Java classes that are wrappers around C++ classes.
These classes implement the finalize method in order to free the memory that has been allocated for them.
Generally, this works fine. However, in high-load scenarios we get out of memory exceptions.
Memory dumps indicate that virtually all the memory (around 6Gb in this case) is filled with the finalizer queue and the objects waiting to be finalized.
For comparison, the C API on its own never goes over around 150 Mb of memory usage.
Under low load, the Java implementation can run indefinitely. So this doesn't seem to be a memory leak as such. It just seem to be that under high load, new objects that require finalizing are generated faster than finalizers get executed.
Obviously, the 'correct' fix is to reduce the number of objects being created. However, that's a significant undertaking and will take a while. In the meantime, is there a mechanism that might help alleviate this issue? For example, by giving the GC more resources.

A: Java was designed around the idea that finalizers could be used as the primary cleanup mechanism for objects that go out of scope.  Such an approach may have been almost workable when the total number of objects was small enough that the overhead of an "always scan everything" garbage collector would have been acceptable, but there are relatively few cases where finalization would be appropriate cleanup measure in a system with a generational garbage collector (which nearly all JVM implementations are going to have, because it offers a huge speed boost compared to always scanning everything).
Using Closable along with a try-with-resources constructs is a vastly superior approach whenever it's workable.  There is no guarantee that finalize methods will get called with any degree of timeliness, and there are many situations where patterns of interrelated objects may prevent them from getting called at all.  While finalize can be useful for some purposes, such as identifying objects which got improperly abandoned while holding resources, there are relatively few purposes for which it would be the proper tool.
If you do need to use finalizers, you should understand an important principle: contrary to popular belief, finalizers do not trigger when an object is actually garbage collected"--they fire when an object would have been garbage collected but for the existence of a finalizer somewhere [including, but not limited to, the object's own finalizer].  No object can actually be garbage collected while any reference to it exists in any local variable, in any other object to which any reference exists, or any object with a finalizer that hasn't run to completion.  Further, to avoid having to examine all objects on every garbage-collection cycle, objects which have been alive for awhile will be given a "free pass" on most GC cycles.  Thus, if an object with a finalizer is alive for awhile before it is abandoned, it may take quite awhile for its finalizer to run, and it will keep objects to which it holds references around long enough that they're likely to also earn a "free pass".
I would thus suggest that to the extent possible, even when it's necessary to use finalizer, you should limit their use to privately-held objects which in turn avoid holding strong references to anything which isn't explicitly needed for their cleanup task.

A: Phantom references is an alternative to finalizers available in Java.
Phantom references allow you to better control resource reclamation process.

*

*you can combine explicit resource disposal (e.g. try with resources construct) with GC base disposal

*you can employ multiple threads for postmortem housekeeping

Using phantom references is complicated tough. In this article you can find a minimal example of phantom reference base resource housekeeping.
In modern Java there are also Cleaner class which is based on phantom reference too, but provides infrastructure (reference queue, worker threads etc) for ease of use.


Q: Hibernate Search Error Can someone help, i'm trying a simple example with hibernate search but getting the following error:
Exception in thread "main" org.hibernate.HibernateException: could not init listeners
    at org.hibernate.event.EventListeners.initializeListeners(EventListeners.java:205)
    at org.hibernate.cfg.Configuration.getInitializedEventListeners(Configuration.java:1396)
    at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:1385)
    at FirstExample.main(FirstExample.java:32)
Caused by: java.lang.NullPointerException
    at java.io.Reader.<init>(Reader.java:61)
    at java.io.InputStreamReader.<init>(InputStreamReader.java:55)
    at org.hibernate.search.util.HibernateSearchResourceLoader.getLines(HibernateSearchResourceLoader.java:52)
    at org.apache.solr.analysis.StopFilterFactory.inform(StopFilterFactory.java:53)
    at org.hibernate.search.impl.SolrAnalyzerBuilder.buildAnalyzer(SolrAnalyzerBuilder.java:79)
    at org.hibernate.search.impl.InitContext.buildAnalyzer(InitContext.java:185)
    at org.hibernate.search.impl.InitContext.initLazyAnalyzers(InitContext.java:155)
    at org.hibernate.search.impl.SearchFactoryImpl.initDocumentBuilders(SearchFactoryImpl.java:541)
    at org.hibernate.search.impl.SearchFactoryImpl.<init>(SearchFactoryImpl.java:171)
    at org.hibernate.search.event.ContextHolder.getOrBuildSearchFactory(ContextHolder.java:60)
    at org.hibernate.search.event.FullTextIndexEventListener.initialize(FullTextIndexEventListener.java:122)
    at org.hibernate.event.EventListeners$1.processListener(EventListeners.java:198)
    at org.hibernate.event.EventListeners.processListeners(EventListeners.java:181)
    at org.hibernate.event.EventListeners.initializeListeners(EventListeners.java:194)
    ... 3 more

My Item Class:
@Indexed
@AnalyzerDef(name="customanalyzer",
        tokenizer = @TokenizerDef(factory = StandardTokenizerFactory.class),
        filters = {
                @TokenFilterDef(factory = ISOLatin1AccentFilterFactory.class),
                @TokenFilterDef(factory = LowerCaseFilterFactory.class),
                @TokenFilterDef(factory = StopFilterFactory.class, params = {
                    @Parameter(name="words", value= "org/hibernate/search/test/analyzer/solr/stoplist.properties" ),
                    @Parameter(name="ignoreCase", value="true")
                })
})

public class Item
{
    @DocumentId
      private Integer id;

      @Field @Analyzer(definition = "customanalyzer")
      private String title;

      @Field @Analyzer(definition = "customanalyzer")
      private String description;

      @Field(index=Index.UN_TOKENIZED, store=Store.YES)
      private String ean;

      private String imageURL;
      //public getters and setters
}

Program code:
Session session = null;
        Transaction tx = null;

            SessionFactory sessionFactory = new Configuration().configure().buildSessionFactory();
            session =sessionFactory.openSession();
            FullTextSession ftem = org.hibernate.search.Search.getFullTextSession(session);

            ftem.beginTransaction();
            List <Item> AllItem=session.createQuery("From Item").list();

            for (Item item : AllItem) {
                  ftem.index(item);
            }
            ftem.getTransaction().commit();

            String searchQuery = "title:Batman";

            QueryParser parser = new QueryParser(
                    "title",
                    ftem.getSearchFactory().getAnalyzer("customanalyzer")
        );
            org.apache.lucene.search.Query luceneQuery;
            try {
                 luceneQuery = parser.parse(searchQuery);
            }
            catch (ParseException e) {
                  throw new RuntimeException("Unable to parse query: " + searchQuery, e);
            }

            org.hibernate.Query query = ftem.createFullTextQuery(
                    luceneQuery,
                    Item.class);
            query.setFirstResult(20).setMaxResults(20);
            List results = query.list();

A: It looks like Hibernate Search can't find org/hibernate/search/test/analyzer/solr/stoplist.properties in the classpath. Make sure it's there.


Q: Efficient way to calculate average MAPE and MSE in R I have a real data and predicted data and I want to calculate overall MAPE and MSE. The data are time series, with each column representing data for different weeks. I predict value for each of the 52 weeks for each of the items as shown below. What would be the best possible calculate overall Error in R.
real = matrix(
    c("item1", "item2", "item3", "item4", .5, .7, 0.40, 0.6, 0.3, 0.29, 0.7, 0.09, 0.42, 0.032, 0.3, 0.37),
     nrow=4,
     ncol=4)
colnames(real) <- c("item", "week1", "week2", "week3")

predicted = matrix(
  c("item1", "item2", "item3", "item4", .55, .67, 0.40, 0.69, 0.13, 0.9, 0.47, 0.19, 0.22, 0.033, 0.4, 0.37),
  nrow=4,
  ncol=4)
colnames(predicted) <- c("item", "week1", "week2", "week3")

A: How do you get the predicted values in the first place? The model you use to get the predicted values is probably based on minimising some function of prediction errors (usually MSE). Therefore, if you calculate your predicted values, the residuals and some metrics on MSE and MAPE have been calculated somewhere along the line in fitting the model. You can probably retrieve them directly.
If the predicted values happened to be thrown into your lap and you have nothing to do with fitting the model, then you calculate MSE and MAPE as per below:
You have only one record per week for every item. So for every item, you can only calculate one prediction error per week. Depending on your application, you can choose to calculate the MSE and MAPE per item or per week.
This is what your data looks like:
real <- matrix(
  c(.5, .7, 0.40, 0.6, 0.3, 0.29, 0.7, 0.09, 0.42, 0.032, 0.3, 0.37),
  nrow = 4, ncol = 3)
colnames(real) <- c("week1", "week2", "week3")

predicted <- matrix(
  c(.55, .67, 0.40, 0.69, 0.13, 0.9, 0.47, 0.19, 0.22, 0.033, 0.4, 0.37),
  nrow = 4, ncol = 3)
colnames(predicted) <- c("week1", "week2", "week3")

Calculate the (percentage/squared) errors for every entry:
pred_error    <- real - predicted
pct_error     <- pred_error/real
squared_error <- pred_error^2

Calculate MSE, MAPE:
# For per-item prediction errors
apply(squared_error,  MARGIN = 1, mean)    # MSE
apply(abs(pct_error), MARGIN = 1, mean)    # MAPE

# For per-week prediction errors
apply(squared_error,  MARGIN = 0, mean)    # MSE
apply(abs(pct_error), MARGIN = 0, mean)    # MAPE


Q: Copy nodes with changed element values XSLT I have input xml

<?xml version="1.0" encoding="UTF-8"?>
<catalog>
  <cd>
    <title>Empire Burlesque</title>
    <artist>Bob Dylan</artist>
    <country>USA</country>
    <company>Columbia</company>
    <price>10.90</price>
    <year>1981</year>
  </cd>
  <cd>
    <title>Hide your heart</title>
    <artist>Bonnie Tyler</artist>
    <country>UK</country>
    <company>CBS Records</company>
    <price>9.90</price>
    <year>1985</year>
  </cd>
  <cd>
    <title>Greatest Hits</title>
    <artist>Dolly Parton</artist>
    <country>USA</country>
    <company>RCA</company>
    <price>9.90</price>
    <year>1982</year>
  </cd>
</catalog>

How do the follow?
For each "catalog/cd"
1) if "year" = '1985', then copy all elemets of "catalog/cd" without changed values
2) else copy all elements "catalog/cd" without changed values, exclude elements "company" (need to set value 'MyCompany') and "country" (need to set value 'MyCountry')

Result XML

<?xml version="1.0" encoding="UTF-8"?>
<catalog>
  <cd>
    <title>Empire Burlesque</title>
    <artist>Bob Dylan</artist>
    <country>MyCountry</country>
    <company>MyCompany</company>
    <price>10.90</price>
    <year>1981</year>
  </cd>
  <cd>
    <title>Hide your heart</title>
    <artist>Bonnie Tyler</artist>
    <country>UK</country>
    <company>CBS Records</company>
    <price>9.90</price>
    <year>1985</year>
  </cd>
  <cd>
    <title>Greatest Hits</title>
    <artist>Dolly Parton</artist>
    <country>MyCountry</country>
    <company>MyCompany</company>
    <price>9.90</price>
    <year>1982</year>
  </cd>
</catalog>

A: There are different options to achieve what you need. You need to start with an identity template that would copy the input XML as is to output.
<xsl:template match="@* | node()">
    <xsl:copy>
        <xsl:apply-templates select="@* | node()" />
    </xsl:copy>
</xsl:template>

Next you can declare separate templates for modifying country and company where the year != 1985.
<xsl:template match="cd[year != '1985']/country">
    <country>MyCountry</country>
</xsl:template>
<xsl:template match="cd[year != '1985']/company">
    <company>MyCompany</company>
</xsl:template>

Another option is to change the values of both elements in a single template cd whose child element year != 1985.
<xsl:template match="cd[year != '1985']">
    <xsl:copy>
        <xsl:apply-templates select="title | artist" />
        <country>MyCountry</country>
        <company>MyCompany</company>
        <xsl:apply-templates select="price | year" />
    </xsl:copy>
</xsl:template>

Hope this helps. However you need to go online and do some reading / hands on tutorials related to XSLT.

A:  <xsl:template match="catalog">
        <catalog>
        <xsl:for-each select="cd">
            <cd>
            <title>
                <xsl:value-of select="title"/>
            </title>
            <artist>
                <xsl:value-of select="artist"/>
            </artist>
            <xsl:choose>
                <xsl:when test="not(year = 1985)">
                    <country>MY Country</country>
                    <company>My Company</company>
                </xsl:when>
                <xsl:otherwise>
                    <country><xsl:value-of select="country"/></country>
                    <company><xsl:value-of select="company"/></company>
                </xsl:otherwise>
            </xsl:choose>
            <price><xsl:value-of select="price"/></price>
            <year><xsl:value-of select="year"/></year>
            </cd>
        </xsl:for-each>
        </catalog>
    </xsl:template>
Check it, I may be helful for you


Q: external raid 1 system basic questions For my cubox-i I would like to have external RAID 1 system in order to have a reliable storage.

*

*Do RAID external systems work out-of-the-box or are any additional drivers required? Is there something I should be careful about?

*Are all hard-drives RAID capable?

A: *

*Depending on how you access it, but generally only the host system needs the drivers. When accessing a NAS over the network, or using a USB enclosure with a RAID controller onboard, you won't need to hunt the drivers down yourself. It will present itself to the OS as one hard drive volume already.

*Yes, all hard drives are RAID capable. This does not mean you can use ANY drive and have great results.
I will use Western Digital for my following explanations... They use Red, Green, Black, Blue and RE4 drives.

*

*The Greens are the cheapest, and are power saving. They do not spin too fast, they're quiet, and ideal for archiving data you don't need fast access to.

*The Blues are the middle-of-the-road drives, ideal for inexpensive computers that don't want a Green to boot up their system.

*The Blacks are the speed demons for the home user. They constantly spin at 7,200RPM, and have a larger cache onboard for bursts of reads or writes to go quicker.

The above drives are not really built for RAID. Yes, they can be used in a RAID system, but they can wait anywhere from 30 seconds to 2 minutes before telling the OS there's an error, which will freeze up the systems wanting access to them. The reason? Because they want to be sure that the data is inaccessible, so it keeps trying and trying on the same spot.

*

*The Reds are built for being on all the time, but also having power saving features of the Green drives. They will alert the OS within 2 seconds (like the RE4s) if there are issues reading the data, so you can replace the disk quickly, and not freeze your system constantly.

*The RE4s are the RAID Edition drives, built for the enterprise. They spin fast (like the Blacks), and have the logic onboard to tell the OS when there is a problem, much quicker.


Q: What is a good, free, windows disk wiping utility similar in functionality to DBAN? I have an external ESATA drive I want to do more than zero, (I would rather clobber with random data, such as the  U.S. Department of Defense disk wiping policy), that is free as in GNU/OSS.
Short hand requirements

*

*Windows only, x64 preferred but not required.

*No linux live-CD

*No virtual OS creation

*Free/OSS

Surely such software exists, or can exist but my google-foo could not locate it.
Perhaps Windows cannot actually do this? I would imagine it could with a non-system drive, at least.

edit:
This question is not an exact duplicate. The linked question (which I read fully before asking) says to use a linux utility. The linked question recommends two linux utilities, only, in the accepted answer! This question is specifically, clearly, and deliberately is asking for a windows only solution, which requires no linux or unix parts. So from my perspective, "exact duplicate" is provably inaccurate. What is the best way to appeal an improperly closed question?

A: Use HDD Low Level Format Tool and then Sdelete if you want a random re-write... its not necessary though. You should also run HDDScan afterwards.
If it has to be OSS you can use Eraser


Q: mongodb query about listing one field as an array with all collections in detailed Assume I have db structure as;
[
    {name: "alex" , age: 21, school: "x university" },
    {name: "felix" , age: 24, school: "y university" },
    {name: "tom" , age: 43, school: "z university" }
]

I want to write a query to get the details of the collection plus the array of the names. I mean as a result of the query I expect to get;
details:[
    {name: "alex" , age: 21, school: "x university" },
    {name: "felix" , age: 24, school: "y university" },
    {name: "tom" , age: 43, school: "z university" }
],

names: ["alex", "felix", "tom"]

To able to get the names as an array I wrote,
db.colletion.aggregate([
    {$group: {_id: "", names: {$addToSet : "$name"}}}
])

But this just prints the names as;
{ "_id" : "", "names" : [ "alex", "felix", "tom"] }

In grouping I can project fields something like,
db.colletion.aggregate([
    {$group: {age: {$first: "$age"}, _id: "", names: {$addToSet : "$name"}}}
])

But this db is just an example, I have dynamic fields that I don't know in advanced. So how can I build this query?


Q: What is the difference between margin and padding in html? I have made a educational website and I am facing problem to set the paragraph block in the on the background page. So kindly help me.
I was trying to manage the text on the background image but it was coming on the top-left of the image.


Q: Past perfect or past simple in combination with present perfect? Suppose I received a document from my colleague, studied it and then gave him feedback in a letter. How should I construct the following sentense?

I have examined the document you gave me and...

or it should be

I have examined the document you had given me and...

and just in case (though I hardly believe it is correct)

I have examined the document you have given me and...

From one point of view both he and I know when he gave me the document so one should use past simple. On the other hand past perfect might be used here to indicate that the moment he gave it to me occurred before I read it.

A: In most contexts the first of the three would be the one to use. The other two would be possible only in rather unusual circumstances.

A: You can use either the simple past (typical American English)

I examined the document you gave me and ...

or the present perfect and the simple

I have examined the document you gave me and ...
I've examined the document you gave me and ...

If you're writing to a colleague, there should be no reason not to use a contraction ("I've").

A: Most probably the first sentence "I have examined the document you GAVE me and..." would be the one to choose.
Have examined because the present conversation with your colleague is the result of examining the document, hence a past event with present results - present perfect. The actual giving, in contrast, is over and finished, so it it should be past simple gave.
To confuse the matter a little, there is an argument for "I examined the document you have given me". Examined because the examination is over and have given because the present ownership is the result of past giving.
Which one you choose depends on the context. If the conversation is about the results of the examination, reporting the conclusions for example, go with have examined. If the conversation is about your ownership of the document, perhaps because it is very old and interesting, have given me would be a better choice.