问:
Multiple Many-To-Many relationships scenario in MySQL
I'm a beginner in SQL and Database management, I have an idea that I don't know how to model into database tables.

I have these tables : users, orders, bills, lessons, tickets, coaches.

Lessons are posted by coaches.

The users are able to order lessons.

A bill is registered after the order.

The users are also able to order tickets.

A ticket gives access to a lesson.

When users buy a ticket, the coache benefit or half or the ticket price.

So when a user buy a ticket that costs 6$ for a specific lesson, the coache who owns the lesson will get 3$.

Do I need another bills table for the coaches? or I can use the same bills table to register their gains from the purchased lessons?
I really have no idea how to achive my List of ideas above, sorry.

For now I've just managed to do this, I don't know how to complete the rest of the DB.

```<code>|bills|<--|orders| *<------ |users|
            |
            v
            *
        |order_lesson|
            *
            /\
            |
        |lessons| *<----- |coaches|
</code>```

I can't ask you for a complete answer, but I really need some explication or guidance.

答:
From what I can tell the ticket is no different then a regular order and can be placed with the orders as the only difference is the money the coach gets. So maybe just a column in the orders table would signify the type of order.

```<code> |bills|<--|orders|<----|users|
                / \
                 |
              |lessons|<---|coaches|
</code>```

Body:
I'm a beginner in SQL and Database management, I have an idea that I don't know how to model into database tables.

I have these tables : users, orders, bills, lessons, tickets, coaches.

Lessons are posted by coaches.

The users are able to order lessons.

A bill is registered after the order.

The users are also able to order tickets.

A ticket gives access to a lesson.

When users buy a ticket, the coache benefit or half or the ticket price.

So when a user buy a ticket that costs 6$ for a specific lesson, the coache who owns the lesson will get 3$.

Do I need another bills table for the coaches? or I can use the same bills table to register their gains from the purchased lessons?
I really have no idea how to achive my List of ideas above, sorry.

For now I've just managed to do this, I don't know how to complete the rest of the DB.

|bills|<--|orders| *<------ |users|
            |
            v
            *
        |order_lesson|
            *
            /\
            |
        |lessons| *<----- |coaches|

I can't ask you for a complete answer, but I really need some explication or guidance.

Body:
From what I can tell the ticket is no different then a regular order and can be placed with the orders as the only difference is the money the coach gets. So maybe just a column in the orders table would signify the type of order.

 |bills|<--|orders|<----|users|
                / \
                 |
              |lessons|<---|coaches|


来源: stackexchange

问:
How to remove wonderplugin.com link from free Wonder Plugin slider?
I am integrating Wonder Plugin Slider and I don’t have very much knowledge about wonder Plugin. How to remove watermark form top left corner.
I am using 4.2.3 WordPress and Wonder Plugin Slider Free Version 2.6
Do any one have any solution for the same, please let me know.</p>

答:
```<code>engine->wonderpluginslider.js (line 385)

mkdiv.attr({style:mkdiv.attr("style")+"display:block !important;visibility:visible !important;font-size:12px!important;"})}
</code>```

change to

```<code>mkdiv.attr({style:mkdiv.attr("style")+"display:none !important;visibility:hidden !important;font-size:12px!important;"})}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
engine->wonderpluginslider.js (line 385)

mkdiv.attr({style:mkdiv.attr("style")+"display:block !important;visibility:visible !important;font-size:12px!important;"})}

change to

mkdiv.attr({style:mkdiv.attr("style")+"display:none !important;visibility:hidden !important;font-size:12px!important;"})}


问:
Can't get POST value from AJAX
Can't get value of filter. Don't know why. Am I doing AJAX wrong?
For the record, I'm new to ajax and have looked many places, with many not getting real answers to the same issue.

JQUERY: index.php

```<code>$(document).ready(function(){
    $.ajax({
        url: 'news.php',
        type: "POST",
        data: {filter:'some value'},
    });
});
</code>```

HTML: index.php

```<code><div>
    <div>
        <? include($_SERVER['DOCUMENT_ROOT']."/news/news.php"); ?>
    </div>
</div>
</code>```

PHP: news.php

```<code>$sbFilter = $_POST['filter'];
echo "select* from test_table where status='3'and ('". $sbFilter."') ORDER BY  `test_table`.`date` DESC, nid DESC   limit 0 , 6"
</code>```

Console Log:

Warning:  mysql_query() [function.mysql-query]: Access denied for user ''@'localhost' (using password: NO) in /home/news/news.php on line 36

Warning:  mysql_query() [function.mysql-query]: A link to the server could not be established in /home/news/news.php on line 36

// HERE IS MY ECHO
select* from test_table where status='3'and press<>1 and ('some value') ORDER BY  test_table.date DESC, nid DESC   limit 0 , 6

Warning:  mysql_query() [function.mysql-query]: Access denied for user ''@'localhost' (using password: NO) in /home/news/news.php on line 42

Warning:  mysql_query() [function.mysql-query]: A link to the server could not be established in /home/news/news.php

On the page, I get:

select* from test_table where status='3' and ('') ORDER BY  test_table.date DESC, nid DESC   limit 0 , 6

答:
The ajax sents the post variable to a php script that php script indeed echos the value BUT you are not capturing the output with your ajax to show it to the screen. Try adding to the ajax </p>

```<code>$(document).ready(function () {
        $.ajax({
            url: 'news.php',
            type: "POST",
            data: {filter: 'some value'}
        }).done(function (data) {
            alert(data);
        });
    });
</code>```

Title: Can't get POST value from AJAX

Body:
Can't get value of filter. Don't know why. Am I doing AJAX wrong?
For the record, I'm new to ajax and have looked many places, with many not getting real answers to the same issue.

JQUERY: index.php

$(document).ready(function(){
    $.ajax({
        url: 'news.php',
        type: "POST",
        data: {filter:'some value'},
    });
});

HTML: index.php

        <? include($_SERVER['DOCUMENT_ROOT']."/news/news.php"); ?>

PHP: news.php

$sbFilter = $_POST['filter'];
echo "select* from test_table where status='3'and ('". $sbFilter."') ORDER BY  `test_table`.`date` DESC, nid DESC   limit 0 , 6"

Console Log:

Warning:  mysql_query() [function.mysql-query]: Access denied for user ''@'localhost' (using password: NO) in /home/news/news.php on line 36

Warning:  mysql_query() [function.mysql-query]: A link to the server could not be established in /home/news/news.php on line 36

// HERE IS MY ECHO
select* from test_table where status='3'and press<>1 and ('some value') ORDER BY  test_table.date DESC, nid DESC   limit 0 , 6

Warning:  mysql_query() [function.mysql-query]: Access denied for user ''@'localhost' (using password: NO) in /home/news/news.php on line 42

Warning:  mysql_query() [function.mysql-query]: A link to the server could not be established in /home/news/news.php

On the page, I get:

select* from test_table where status='3' and ('') ORDER BY  test_table.date DESC, nid DESC   limit 0 , 6

Body:
The ajax sents the post variable to a php script that php script indeed echos the value BUT you are not capturing the output with your ajax to show it to the screen. Try adding to the ajax

$(document).ready(function () {
        $.ajax({
            url: 'news.php',
            type: "POST",
            data: {filter: 'some value'}
        }).done(function (data) {
            alert(data);
        });
    });


问:
Concatenate the database name in a SQL multipart identifier
I'm writing a stored procedure and I'm trying to concatenate the database name in the multipart identifier after FROM without success. This is one way that I tried but it didn't work

```<code>INSERT INTO CONTROL_LOGISTICA.dbo.ITEMS_TRAMITE (NRODCTO, TIPODCTO, PRODUCTO, EMPRESA, CODUSUARIO, CODUBICA, CANTIDAD, CCHECK_HIJO)
    SELECT
        @pNrodcto, @pTipodcto,
        M.PRODUCTO, @pEmpresa, @pUsuario,
        M.CODUBICA, M.CANTIDAD, 0
    FROM
        "@mEmpresa".dbo.MVTRADE M WITH(NOLOCK) -- Here I'm stuck
    INNER JOIN
        Dbo.vReporteMercia_ESP P ON P.PRODUCTO = M.PRODUCTO
    WHERE
        M.CANTIDAD <> 0 AND M.Origen = 'FAC'
        AND M.NRODCTO = @pNrodcto AND M.TIPODCTO = @pTipodcto
</code>```

I get the variable directly from the stored procedure

```<code>@pEmpresa AS char(20)
</code>```

I know that I can do an IF like

```<code>IF (@pEmpresa = 'John Doe')
 BEGIN
 --..... and the query here
 END
</code>```

Is it possible to concatenate the database name using the variable? How? Or should I just use the IF?

答:
You would have to use dynamic sql to do something like that.

```<code>declare @sql nvarchar(max);
declare @params nvarchar(max);

set @params= N'@pNrodcto int, @pTipodcto int, @pUsuario int, @pEmpresa char(20)';

set @sql = N'INSERT INTO CONTROL_LOGISTICA.dbo.ITEMS_TRAMITE (NRODCTO, TIPODCTO, PRODUCTO, EMPRESA, CODUSUARIO, CODUBICA, CANTIDAD, CCHECK_HIJO)
  SELECT @pNrodcto,@pTipodcto,M.PRODUCTO,@pEmpresa,@pUsuario,M.CODUBICA,M.CANTIDAD,0
  FROM '+db_name(db_id(@pEmpresa))+'.dbo.MVTRADE M WITH(NOLOCK) --Here im stuck
  INNER JOIN Dbo.vReporteMercia_ESP P ON P.PRODUCTO = M.PRODUCTO
  WHERE M.CANTIDAD <> 0 AND M.Origen = ''FAC''
  AND M.NRODCTO = @pNrodcto AND M.TIPODCTO = @pTipodcto';
exec sp_executesql @sql, @params, @pNrodcto, @pTipodcto, @pUsuario, @pEmpresa;
</code>```

To avoid directly concatenating a parameter to an executed sql string, I wrapped the parameter in calls to db_name() and db_id(). This would return null for an invalid database name, but wouldn't stop someone from referencing a database you do not want them to. Consider comparing the parameter value against a white list.

Reference:

The curse and blessings of dynamic SQL - Erland Sommarskog

sp_executesql

Body:
I'm writing a stored procedure and I'm trying to concatenate the database name in the multipart identifier after FROM without success. This is one way that I tried but it didn't work

INSERT INTO CONTROL_LOGISTICA.dbo.ITEMS_TRAMITE (NRODCTO, TIPODCTO, PRODUCTO, EMPRESA, CODUSUARIO, CODUBICA, CANTIDAD, CCHECK_HIJO)
    SELECT
        @pNrodcto, @pTipodcto,
        M.PRODUCTO, @pEmpresa, @pUsuario,
        M.CODUBICA, M.CANTIDAD, 0
    FROM
        "@mEmpresa".dbo.MVTRADE M WITH(NOLOCK) -- Here I'm stuck
    INNER JOIN
        Dbo.vReporteMercia_ESP P ON P.PRODUCTO = M.PRODUCTO
    WHERE
        M.CANTIDAD <> 0 AND M.Origen = 'FAC'
        AND M.NRODCTO = @pNrodcto AND M.TIPODCTO = @pTipodcto

I get the variable directly from the stored procedure

@pEmpresa AS char(20)

I know that I can do an IF like

IF (@pEmpresa = 'John Doe')
 BEGIN
 --..... and the query here
 END

Is it possible to concatenate the database name using the variable? How? Or should I just use the IF?

Body:
You would have to use dynamic sql to do something like that.

declare @sql nvarchar(max);
declare @params nvarchar(max);

set @params= N'@pNrodcto int, @pTipodcto int, @pUsuario int, @pEmpresa char(20)';

set @sql = N'INSERT INTO CONTROL_LOGISTICA.dbo.ITEMS_TRAMITE (NRODCTO, TIPODCTO, PRODUCTO, EMPRESA, CODUSUARIO, CODUBICA, CANTIDAD, CCHECK_HIJO)
  SELECT @pNrodcto,@pTipodcto,M.PRODUCTO,@pEmpresa,@pUsuario,M.CODUBICA,M.CANTIDAD,0
  FROM '+db_name(db_id(@pEmpresa))+'.dbo.MVTRADE M WITH(NOLOCK) --Here im stuck
  INNER JOIN Dbo.vReporteMercia_ESP P ON P.PRODUCTO = M.PRODUCTO
  WHERE M.CANTIDAD <> 0 AND M.Origen = ''FAC''
  AND M.NRODCTO = @pNrodcto AND M.TIPODCTO = @pTipodcto';
exec sp_executesql @sql, @params, @pNrodcto, @pTipodcto, @pUsuario, @pEmpresa;

To avoid directly concatenating a parameter to an executed sql string, I wrapped the parameter in calls to db_name() and db_id(). This would return null for an invalid database name, but wouldn't stop someone from referencing a database you do not want them to. Consider comparing the parameter value against a white list.

Reference:

The curse and blessings of dynamic SQL - Erland Sommarskog

sp_executesql


问:
Reading Clipboard with WIC
I'm trying to write a function to read images copied to the clipboard with Windows Imaging Component. Currently my code is based off how I load resources but modified to work with the clipboard. everything up to initializing the stream works fine but once I try to use CreateDecoderFromeStream it fails. I've tried copying images from numerous places to no avail. Is there something different about the copied image format that can't be read by WIC?

Here's my code below...

Creating a memory object to read from the clipboard

```<code>COMStreamSPtr WIC::createStreamFromClipboard() {
    IStream* ipStream = NULL;
    COMStreamSPtr stream = nullptr;
    CoInitialize(nullptr);
    if (!IsClipboardFormatAvailable(CF_BITMAP) && !IsClipboardFormatAvailable(CF_DIB) && !IsClipboardFormatAvailable(CF_DIBV5))
        goto Return;

    if (!OpenClipboard(NULL))
        goto Return;

    // Load the clipboard
    HGLOBAL hMem = GetClipboardData(CF_BITMAP);
    if (hMem == NULL || hMem == INVALID_HANDLE_VALUE)
        hMem = GetClipboardData(CF_DIB);
    if (hMem == NULL || hMem == INVALID_HANDLE_VALUE)
        hMem = GetClipboardData(CF_DIBV5);
    if (hMem == NULL || hMem == INVALID_HANDLE_VALUE)
        goto CloseClipboard;

    // Lock the clipboard, getting a pointer to its data
    LPVOID pvSourceClipboardData = GlobalLock(hMem);
    if (pvSourceClipboardData == NULL)
        goto CloseClipboard;

    // Read the clipboard data size
    DWORD dwClipboardSize = GlobalSize(hMem);
    if (dwClipboardSize == 0)
        goto GlobalUnlock;

    // Allocate memory to hold the clipboard data
    HGLOBAL hgblClipboardData = GlobalAlloc(GMEM_MOVEABLE, dwClipboardSize);
    if (hgblClipboardData == NULL)
        goto GlobalUnlock;

    // Get a pointer to the allocated memory
    LPVOID pvClipboardData = GlobalLock(hgblClipboardData);
    if (pvClipboardData == NULL)
        goto FreeData;

    // Copy the data from the clipboard to the new memory block
    CopyMemory(pvClipboardData, pvSourceClipboardData, dwClipboardSize);
    GlobalUnlock(hgblClipboardData);

    // Create a stream on the HGLOBAL containing the data
    if (SUCCEEDED(CreateStreamOnHGlobal(hgblClipboardData, TRUE, &ipStream))) {
        stream = std::make_shared<COMStream>(ipStream);
        goto CloseClipboard;
    }

FreeData:
    // Couldn't create stream; free the memory
    GlobalFree(hgblClipboardData);
GlobalUnlock:
    // Unlock the clipboard data
    GlobalUnlock(hMem);
CloseClipboard:
    // Close the clipboard
    CloseClipboard();
Return:
    // No need to unlock or free the resource
    CoUninitialize(); // CoInialize is called by my COMObjects in the constructor so this is just decrementing the count.
    return stream;
}
</code>```

Elsewhere in the code using the returned stream.

```<code>WICBitmapDecoderSPtr WIC::createDecoderFromStream(COMStreamSPtr stream) {
    if (isCOMObjectNull(stream))
        return nullptr;

    IWICImagingFactory* ipFactory = NULL;
    IWICBitmapDecoder* ipDecoder = NULL;
    WICBitmapDecoderSPtr decoder = nullptr;

    // Create the factory
    if (FAILED(CoCreateInstance(CLSID_WICImagingFactory, NULL, CLSCTX_INPROC_SERVER, IID_PPV_ARGS(&ipFactory))))
        goto Return;

    // Create the decoder
    if (FAILED(ipFactory->CreateDecoderFromStream(stream->ipObject, NULL, WICDecodeMetadataCacheOnDemand, &ipDecoder)))
        goto ReleaseFactory; // FAILS HERE

    decoder = std::make_shared<WICBitmapDecoder>(ipDecoder);
ReleaseFactory:
    ipFactory->Release();
Return:
    return decoder;
}
</code>```

答:
I've finally figured out how to do this. What I did is I used IWICImagingFactory's CreateBitmapFromHBITMAP function. Since reading an HBITMAP from the clipboard work trivial, the solution becomes pretty straight forward.

```<code>IWICBitmapSource* WIC::readSourceFromClipboard() {
    IWICBitmapSource* ipSource = NULL;
    if (Clipboard::containsFormat(CF_BITMAP)) {
        if (OpenClipboard(NULL)) {
            HBITMAP hBitmap = (HBITMAP)GetClipboardData(CF_BITMAP);
            ipSource = createSourceFromHBitmap(hBitmap);
            CloseClipboard();
        }
    }
    return ipSource;
}

IWICBitmapSource* WIC::createSourceFromHBitmap(HBITMAP hBitmap) {
    if (hBitmap == NULL)
        return NULL;

    IWICImagingFactory* ipFactory = NULL;
    IWICBitmap* ipBitmap = NULL;

    CoInitialize(NULL);

    // Create the factory
    if (FAILED(CoCreateInstance(CLSID_WICImagingFactory, NULL, CLSCTX_INPROC_SERVER, IID_PPV_ARGS(&ipFactory))))
        goto Return;

    // Create the bitmap
    if (FAILED(ipFactory->CreateBitmapFromHBITMAP(hBitmap, NULL, WICBitmapIgnoreAlpha, &ipBitmap)))
        goto ReleaseFactory;

ReleaseFactory:
    ipFactory->Release();
Return:
    CoUninitialize();
    return ipBitmap;
}
</code>```

Title: Reading Clipboard with WIC

Body:
I'm trying to write a function to read images copied to the clipboard with Windows Imaging Component. Currently my code is based off how I load resources but modified to work with the clipboard. everything up to initializing the stream works fine but once I try to use CreateDecoderFromeStream it fails. I've tried copying images from numerous places to no avail. Is there something different about the copied image format that can't be read by WIC?

Here's my code below...

Creating a memory object to read from the clipboard

COMStreamSPtr WIC::createStreamFromClipboard() {
    IStream* ipStream = NULL;
    COMStreamSPtr stream = nullptr;
    CoInitialize(nullptr);
    if (!IsClipboardFormatAvailable(CF_BITMAP) && !IsClipboardFormatAvailable(CF_DIB) && !IsClipboardFormatAvailable(CF_DIBV5))
        goto Return;

    if (!OpenClipboard(NULL))
        goto Return;

    // Load the clipboard
    HGLOBAL hMem = GetClipboardData(CF_BITMAP);
    if (hMem == NULL || hMem == INVALID_HANDLE_VALUE)
        hMem = GetClipboardData(CF_DIB);
    if (hMem == NULL || hMem == INVALID_HANDLE_VALUE)
        hMem = GetClipboardData(CF_DIBV5);
    if (hMem == NULL || hMem == INVALID_HANDLE_VALUE)
        goto CloseClipboard;

    // Lock the clipboard, getting a pointer to its data
    LPVOID pvSourceClipboardData = GlobalLock(hMem);
    if (pvSourceClipboardData == NULL)
        goto CloseClipboard;

    // Read the clipboard data size
    DWORD dwClipboardSize = GlobalSize(hMem);
    if (dwClipboardSize == 0)
        goto GlobalUnlock;

    // Allocate memory to hold the clipboard data
    HGLOBAL hgblClipboardData = GlobalAlloc(GMEM_MOVEABLE, dwClipboardSize);
    if (hgblClipboardData == NULL)
        goto GlobalUnlock;

    // Get a pointer to the allocated memory
    LPVOID pvClipboardData = GlobalLock(hgblClipboardData);
    if (pvClipboardData == NULL)
        goto FreeData;

    // Copy the data from the clipboard to the new memory block
    CopyMemory(pvClipboardData, pvSourceClipboardData, dwClipboardSize);
    GlobalUnlock(hgblClipboardData);

    // Create a stream on the HGLOBAL containing the data
    if (SUCCEEDED(CreateStreamOnHGlobal(hgblClipboardData, TRUE, &ipStream))) {
        stream = std::make_shared<COMStream>(ipStream);
        goto CloseClipboard;
    }

FreeData:
    // Couldn't create stream; free the memory
    GlobalFree(hgblClipboardData);
GlobalUnlock:
    // Unlock the clipboard data
    GlobalUnlock(hMem);
CloseClipboard:
    // Close the clipboard
    CloseClipboard();
Return:
    // No need to unlock or free the resource
    CoUninitialize(); // CoInialize is called by my COMObjects in the constructor so this is just decrementing the count.
    return stream;
}

Elsewhere in the code using the returned stream.

WICBitmapDecoderSPtr WIC::createDecoderFromStream(COMStreamSPtr stream) {
    if (isCOMObjectNull(stream))
        return nullptr;

    IWICImagingFactory* ipFactory = NULL;
    IWICBitmapDecoder* ipDecoder = NULL;
    WICBitmapDecoderSPtr decoder = nullptr;

    // Create the factory
    if (FAILED(CoCreateInstance(CLSID_WICImagingFactory, NULL, CLSCTX_INPROC_SERVER, IID_PPV_ARGS(&ipFactory))))
        goto Return;

    // Create the decoder
    if (FAILED(ipFactory->CreateDecoderFromStream(stream->ipObject, NULL, WICDecodeMetadataCacheOnDemand, &ipDecoder)))
        goto ReleaseFactory; // FAILS HERE

    decoder = std::make_shared<WICBitmapDecoder>(ipDecoder);
ReleaseFactory:
    ipFactory->Release();
Return:
    return decoder;
}

Body:
I've finally figured out how to do this. What I did is I used IWICImagingFactory's CreateBitmapFromHBITMAP function. Since reading an HBITMAP from the clipboard work trivial, the solution becomes pretty straight forward.

IWICBitmapSource* WIC::readSourceFromClipboard() {
    IWICBitmapSource* ipSource = NULL;
    if (Clipboard::containsFormat(CF_BITMAP)) {
        if (OpenClipboard(NULL)) {
            HBITMAP hBitmap = (HBITMAP)GetClipboardData(CF_BITMAP);
            ipSource = createSourceFromHBitmap(hBitmap);
            CloseClipboard();
        }
    }
    return ipSource;
}

IWICBitmapSource* WIC::createSourceFromHBitmap(HBITMAP hBitmap) {
    if (hBitmap == NULL)
        return NULL;

    IWICImagingFactory* ipFactory = NULL;
    IWICBitmap* ipBitmap = NULL;

    CoInitialize(NULL);

    // Create the factory
    if (FAILED(CoCreateInstance(CLSID_WICImagingFactory, NULL, CLSCTX_INPROC_SERVER, IID_PPV_ARGS(&ipFactory))))
        goto Return;

    // Create the bitmap
    if (FAILED(ipFactory->CreateBitmapFromHBITMAP(hBitmap, NULL, WICBitmapIgnoreAlpha, &ipBitmap)))
        goto ReleaseFactory;

ReleaseFactory:
    ipFactory->Release();
Return:
    CoUninitialize();
    return ipBitmap;
}


问:
What's the best way to manage dates across PHP, MySQL, etc?
My server is in Dallas.  I'm in New York City.. and both PHP and MySQL have configuration variables for setting the timezone.

How do I get them all to work together?  What dates should I store in MySQL?  How do I get PHP to handle changing the date based on the user's preference?

Bear in mind:  I don't think I'm ever having PHP explicitly set the date, it's always using "NOW()" in queries.. however I foresee the need to do this.  How would this be done?

I'm hoping SO's experience can help me out here.

答:
Use Unix Time everywhere. It's using UTC so it's the same for every timezone. Methods for dates usually convert to it and back from it using timezone information they have, so you would have yourself a correct time.

Alternatively you could use Unix Time only to transfer time from one computer to another (like from DB to your server running PHP, or to JavaScript client). There's functions to convert to it and from it in every language. For MySQL it is:

```<code>UNIX_TIMESTAMP(date)
FROM_UNIXTIME(unix_timestamp)
</code>```

That way you could have your time properly formatted on the DB and in logs but still have correct local time everywhere.

OwnerDisplayName: Sam

ContentLicense: CC BY-SA 2.5

Body:
Use Unix Time everywhere. It's using UTC so it's the same for every timezone. Methods for dates usually convert to it and back from it using timezone information they have, so you would have yourself a correct time.

Alternatively you could use Unix Time only to transfer time from one computer to another (like from DB to your server running PHP, or to JavaScript client). There's functions to convert to it and from it in every language. For MySQL it is:

UNIX_TIMESTAMP(date)
FROM_UNIXTIME(unix_timestamp)

That way you could have your time properly formatted on the DB and in logs but still have correct local time everywhere.

OwnerDisplayName: Vadim

LastEditorDisplayName: Vadim


问:
Import csv file into SQL Server slow because of double loop
I want to import a .csv file into SQL Server and I need for each value on a given row check it's type to make sure there's no error in the file.

This becomes very slow for large files since I am effectively doing a double loop, for each row, and then for each element in the row.

Is there a faster solution to this problem? I put the current slow code for reference to see if I get some suggestions. Note that schema is a dictionary that defines the data type for each column (i.e, varchar, date, etc.)

```<code>with open(csv_filename, encoding='utf8') as csv_f:
    reader = csv.DictReader(csv_f)
    idx = 1

    select_code_l = []

    for row in reader:
       # add new value to row
       if d is not None:
           for key,value in d.items():
               row[key] = value
       # get all the values in the schema
       row_values = []
       schema_iterator = schema_df.iterrows()
       for i, schema in schema_iterator:
           schema_name = schema['field']
           value = row[schema2csv[schema_name]]
           #print(value)
           schema_type = schema['type'].split('(')[0].lower()
           if schema_type == 'varchar' or schema_type == 'date' or schema_type == 'datetime2' or schema_type == 'datetime2':
               row_values.append("'"+str(value).replace("'","''")+"'")
           elif schema_type == 'bigint':
               if value == '':
                   row_values.append('NULL')
               else:
                   row_values.append(str(int(float(value))))
           elif schema_type == 'float':
               if value == '':
                   row_values.append('NULL')
               else:
                   row_values.append(str(float(value)))
           else:
               print ('ERROR')
               return 0
</code>```

答:
Most easy way would be BULK INSERT directly from sql.
If you need some validation, create a cleanup table with the same schema and then get it into the real table with a select query. This is for sure faster.
https://msdn.microsoft.com/de-de/library/ms188365.aspx</p>

```<code>BULK INSERT AdventureWorks2012.Sales.SalesOrderDetail
   FROM 'f:\orders\lineitem.tbl'
   WITH
      (
         FIELDTERMINATOR =' |',
         ROWTERMINATOR =' |\n'
      );
</code>```

Body:
I want to import a .csv file into SQL Server and I need for each value on a given row check it's type to make sure there's no error in the file.

This becomes very slow for large files since I am effectively doing a double loop, for each row, and then for each element in the row.

Is there a faster solution to this problem? I put the current slow code for reference to see if I get some suggestions. Note that schema is a dictionary that defines the data type for each column (i.e, varchar, date, etc.)

with open(csv_filename, encoding='utf8') as csv_f:
    reader = csv.DictReader(csv_f)
    idx = 1

    select_code_l = []

    for row in reader:
       # add new value to row
       if d is not None:
           for key,value in d.items():
               row[key] = value
       # get all the values in the schema
       row_values = []
       schema_iterator = schema_df.iterrows()
       for i, schema in schema_iterator:
           schema_name = schema['field']
           value = row[schema2csv[schema_name]]
           #print(value)
           schema_type = schema['type'].split('(')[0].lower()
           if schema_type == 'varchar' or schema_type == 'date' or schema_type == 'datetime2' or schema_type == 'datetime2':
               row_values.append("'"+str(value).replace("'","''")+"'")
           elif schema_type == 'bigint':
               if value == '':
                   row_values.append('NULL')
               else:
                   row_values.append(str(int(float(value))))
           elif schema_type == 'float':
               if value == '':
                   row_values.append('NULL')
               else:
                   row_values.append(str(float(value)))
           else:
               print ('ERROR')
               return 0

Body:
Most easy way would be BULK INSERT directly from sql.
If you need some validation, create a cleanup table with the same schema and then get it into the real table with a select query. This is for sure faster.
https://msdn.microsoft.com/de-de/library/ms188365.aspx

BULK INSERT AdventureWorks2012.Sales.SalesOrderDetail
   FROM 'f:\orders\lineitem.tbl'
   WITH
      (
         FIELDTERMINATOR =' |',
         ROWTERMINATOR =' |\n'
      );


问:
How to set language (locale) inside a Route::group()... in Laravel 5.4?
Inside blade - welcome.blade.php.

```<code> <div class="links">
      <a href="https://laravel.com/docs">{{ __('passwords.reset') }}</a>
 </div>
</code>```

Inside web.php.

If I run:

```<code>Route::get('/', function () {
    return view('welcome');
});
</code>```

I get the correct welcome blade page with the correct translation.

Another Route:

```<code>Route::get('welcome/{lang}', function ($lang) {
//    echo $lang;
//    dd(Lang::getLocale());
    App::setLocale($lang);
    //dd(Lang::getLocale());
    return view('welcome');
    //
});
</code>```

If I run dd(Lang::getLocale()); I can see the correct language sent by the URL http://testapp/welcome/en. In this case 'en'. If I put dd() in comment I can see the correct translation in Laravel Welcome page.

But when I run this code:

```<code>Route::group(['prefix'=>'welcome'], function (){
    Route::group(['prefix'=>'{lang}'], function ($lang){
        //echo $lang;
        //dd(Lang::getLocale());
        App::setLocale($lang);
        //dd(Lang::getLocale());
        return view('welcome');
    });
});
</code>```

This is what I have:

echo $lang; gives me ErrorException in web.php line 30: Object of class Illuminate\Routing\Router could not be converted to string

dd(Lang::getLocale());  gives me 'en'.

App::setLocale($lang); gives me 404 Not Found

App::setLocale($lang); AND return view('welcome'); gives me 404 Not Found

return view('welcome'); gives me 404 Not Found

And When I run

```<code>App::setLocale($lang);
dd(Lang::getLocale());
return view('welcome');
</code>```

I get an object:

```<code>Router {#21 ▼
  #events: Dispatcher {#23 ▶}
  #container: Application {#3 ▶}
  #routes: RouteCollection {#25 ▶}
  #current: null
  #currentRequest: null
  #middleware: array:6 [▶]
  #middlewareGroups: array:2 [▶]
  +middlewarePriority: array:6 [▶]
  #binders: []
  #patterns: []
  #groupStack: array:3 [▶]
}
</code>```

So, my guess is that Route::group(['prefix'=>'{lang}'... is returning a object not a string. This is why it crashes the process.

How can I solve this issue using Route::group()?

答:
The problem is that Route::group is just a wrapper to organize and group other routes. It is not a defined url. Route::group and Route::post/get don't work that same, so you cannot put logic inside a Route::group call.

What you can do is the following

```<code>Route::group(['prefix'=>'welcome'], function (){
    Route::group(['prefix'=>'{lang}'], function (){
        Route::get('/', function ($lang) {
            App::setLocale($lang);
            return view('welcome');
        });
     });
});
</code>```

Body:
Inside blade - welcome.blade.php.

      {{ __('passwords.reset') }}

Inside web.php.

If I run:

Route::get('/', function () {
    return view('welcome');
});

I get the correct welcome blade page with the correct translation.

Another Route:

Route::get('welcome/{lang}', function ($lang) {
//    echo $lang;
//    dd(Lang::getLocale());
    App::setLocale($lang);
    //dd(Lang::getLocale());
    return view('welcome');
    //
});

If I run dd(Lang::getLocale()); I can see the correct language sent by the URL http://testapp/welcome/en. In this case 'en'. If I put dd() in comment I can see the correct translation in Laravel Welcome page.

But when I run this code:

Route::group(['prefix'=>'welcome'], function (){
    Route::group(['prefix'=>'{lang}'], function ($lang){
        //echo $lang;
        //dd(Lang::getLocale());
        App::setLocale($lang);
        //dd(Lang::getLocale());
        return view('welcome');
    });
});

This is what I have:

echo $lang; gives me ErrorException in web.php line 30: Object of class Illuminate\Routing\Router could not be converted to string

dd(Lang::getLocale());  gives me 'en'.

App::setLocale($lang); gives me 404 Not Found

App::setLocale($lang); AND return view('welcome'); gives me 404 Not Found

return view('welcome'); gives me 404 Not Found

And When I run

App::setLocale($lang);
dd(Lang::getLocale());
return view('welcome');

I get an object:

Router {#21 ▼
  #events: Dispatcher {#23 ▶}
  #container: Application {#3 ▶}
  #routes: RouteCollection {#25 ▶}
  #current: null
  #currentRequest: null
  #middleware: array:6 [▶]
  #middlewareGroups: array:2 [▶]
  +middlewarePriority: array:6 [▶]
  #binders: []
  #patterns: []
  #groupStack: array:3 [▶]
}

So, my guess is that Route::group(['prefix'=>'{lang}'... is returning a object not a string. This is why it crashes the process.

How can I solve this issue using Route::group()?

Body:
The problem is that Route::group is just a wrapper to organize and group other routes. It is not a defined url. Route::group and Route::post/get don't work that same, so you cannot put logic inside a Route::group call.

What you can do is the following

Route::group(['prefix'=>'welcome'], function (){
    Route::group(['prefix'=>'{lang}'], function (){
        Route::get('/', function ($lang) {
            App::setLocale($lang);
            return view('welcome');
        });
     });
});


问:
Locales as part of the URL in Spring MVC
I'm now looking for a framework for multilingual web-applications. At the moment it seems to me that the best choice is Spring MVC. But I faced the fact that all the guidelines for developers suggests to switch languages using LocaleChangeInterceptor in such way:

http://www.somesite.com/action/?locale=en

Unfortunately, there are a number of reasons why I would like avoid this. How could I make language code to be an essential part of URL? For example:

http://www.somesite.com/en/action

Thanks.

UPD: I've found following solution. It's not complete yet, but works. Solution consists in two parts - servlet filter and locale resolver bean. It's looks little bit hackish, but I do not see other way to solve this problem.

```<code>public class LocaleFilter implements Filter
{

    ...

    private static final String DEFAULT_LOCALE = "en";
    private static final String[] AVAILABLE_LOCALES = new String[] {"en", "ru"};

    public LocaleFilter() {}

    private List<String> getSevletRequestParts(ServletRequest request)
    {
        String[] splitedParts = ((HttpServletRequest) request).getServletPath().split("/");
        List<String> result = new ArrayList<String>();

        for (String sp : splitedParts)
        {
            if (sp.trim().length() > 0)
                result.add(sp);
        }

        return result;
    }

    private Locale getLocaleFromRequestParts(List<String> parts)
    {
        if (parts.size() > 0)
        {
            for (String lang : AVAILABLE_LOCALES)
            {
                if (lang.equals(parts.get(0)))
                {
                    return new Locale(lang);
                }
            }
        }

        return null;
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response,
                         FilterChain chain) throws IOException, ServletException
    {
        List<String> requestParts = this.getSevletRequestParts(request);
        Locale locale = this.getLocaleFromRequestParts(requestParts);

        if (locale != null)
        {
            request.setAttribute(LocaleFilter.class.getName() + ".LOCALE", locale);

            StringBuilder sb = new StringBuilder();
            for (int i = 1; i < requestParts.size(); i++)
            {
                sb.append('/');
                sb.append((String) requestParts.get(i));
            }

            RequestDispatcher dispatcher = request.getRequestDispatcher(sb.toString());
            dispatcher.forward(request, response);
        }
        else
        {
            request.setAttribute(LocaleFilter.class.getName() + ".LOCALE", new Locale(DEFAULT_LOCALE));
            chain.doFilter(request, response);
        }
    }

    ...
}

public class FilterLocaleResolver implements LocaleResolver
{

    private Locale DEFAULT_LOCALE = new Locale("en");

    @Override
    public Locale resolveLocale(HttpServletRequest request)
    {
        Locale locale = (Locale) request.getAttribute(LocaleFilter.class.getName() + ".LOCALE");
        return (locale != null ? locale : DEFAULT_LOCALE);
    }

    @Override
    public void setLocale(HttpServletRequest request, HttpServletResponse response, Locale locale)
    {
        request.setAttribute(LocaleFilter.class.getName() + ".LOCALE", locale);
    }

}
</code>```

So there is no need to map locale in each action in controllers. The following example will work fine:

```<code>@Controller
@RequestMapping("/test")
public class TestController
{

    @RequestMapping("action")
    public ModelAndView action(HttpServletRequest request, HttpServletResponse response)
    {
        ModelAndView mav = new ModelAndView("test/action");
        ...
        return mav;
    }

}
</code>```

答:
I came across very same problem recently. So I would like to have stateless locale not depending on session or cookie or anything else than simply URL.

I tried filter/interceptor/localeResolver solutions suggested in previous answers however these did not suite my needs as I had:

static content (images etc ..)

parts of page not locale dependent (admin panel)

RestController inside same app

multipart file uploader

I also wanted to avoid duplicated content for SEO reasons (In particular I do not want my english content to be accessible from both paths: /landingPage and /en/landingPage).

The solution that worked best for me was to create LanguageAwareController and then inherit from it in all controllers that I wanted to support multiple locales.

```<code>@Controller
@RequestMapping(path = "/{lang}")
public class LanguageAwareController {
    @Autowired
    LocaleResolver localeResolver;

    @ModelAttribute(name = "locale")
    Locale getLocale(@PathVariable(name = "lang") String lang, HttpServletRequest request,
                 HttpServletResponse response){
        Locale effectiveLocale = Arrays.stream(Locale.getAvailableLocales())
            .filter(locale -> locale.getLanguage().equals(lang))
            .findFirst()
            .orElseGet(Locale::getDefault);
        localeResolver.setLocale(request, response, effectiveLocale);
        return effectiveLocale;
    }
}
</code>```

Usage in one of controllers:

```<code>@Controller
public class LandingPageController extends LanguageAwareController{

    private Log log = LogFactory.getLog(LandingPageController.class);

    @GetMapping("/")
    public String welcomePage(Locale locale, @PathVariable(name = "lang") String lang ){
        log.info(lang);
        log.info(locale);
        return "landing";
    }
}
</code>```

Body:
I'm now looking for a framework for multilingual web-applications. At the moment it seems to me that the best choice is Spring MVC. But I faced the fact that all the guidelines for developers suggests to switch languages using LocaleChangeInterceptor in such way:

http://www.somesite.com/action/?locale=en

Unfortunately, there are a number of reasons why I would like avoid this. How could I make language code to be an essential part of URL? For example:

http://www.somesite.com/en/action

Thanks.

UPD: I've found following solution. It's not complete yet, but works. Solution consists in two parts - servlet filter and locale resolver bean. It's looks little bit hackish, but I do not see other way to solve this problem.

public class LocaleFilter implements Filter
{

    ...

    private static final String DEFAULT_LOCALE = "en";
    private static final String[] AVAILABLE_LOCALES = new String[] {"en", "ru"};

    public LocaleFilter() {}

    private List<String> getSevletRequestParts(ServletRequest request)
    {
        String[] splitedParts = ((HttpServletRequest) request).getServletPath().split("/");
        List<String> result = new ArrayList<String>();

        for (String sp : splitedParts)
        {
            if (sp.trim().length() > 0)
                result.add(sp);
        }

        return result;
    }

    private Locale getLocaleFromRequestParts(List<String> parts)
    {
        if (parts.size() > 0)
        {
            for (String lang : AVAILABLE_LOCALES)
            {
                if (lang.equals(parts.get(0)))
                {
                    return new Locale(lang);
                }
            }
        }

        return null;
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response,
                         FilterChain chain) throws IOException, ServletException
    {
        List<String> requestParts = this.getSevletRequestParts(request);
        Locale locale = this.getLocaleFromRequestParts(requestParts);

        if (locale != null)
        {
            request.setAttribute(LocaleFilter.class.getName() + ".LOCALE", locale);

            StringBuilder sb = new StringBuilder();
            for (int i = 1; i < requestParts.size(); i++)
            {
                sb.append('/');
                sb.append((String) requestParts.get(i));
            }

            RequestDispatcher dispatcher = request.getRequestDispatcher(sb.toString());
            dispatcher.forward(request, response);
        }
        else
        {
            request.setAttribute(LocaleFilter.class.getName() + ".LOCALE", new Locale(DEFAULT_LOCALE));
            chain.doFilter(request, response);
        }
    }

    ...
}

public class FilterLocaleResolver implements LocaleResolver
{

    private Locale DEFAULT_LOCALE = new Locale("en");

    @Override
    public Locale resolveLocale(HttpServletRequest request)
    {
        Locale locale = (Locale) request.getAttribute(LocaleFilter.class.getName() + ".LOCALE");
        return (locale != null ? locale : DEFAULT_LOCALE);
    }

    @Override
    public void setLocale(HttpServletRequest request, HttpServletResponse response, Locale locale)
    {
        request.setAttribute(LocaleFilter.class.getName() + ".LOCALE", locale);
    }

}

So there is no need to map locale in each action in controllers. The following example will work fine:

@Controller
@RequestMapping("/test")
public class TestController
{

    @RequestMapping("action")
    public ModelAndView action(HttpServletRequest request, HttpServletResponse response)
    {
        ModelAndView mav = new ModelAndView("test/action");
        ...
        return mav;
    }

}

Body:
I came across very same problem recently. So I would like to have stateless locale not depending on session or cookie or anything else than simply URL.

I tried filter/interceptor/localeResolver solutions suggested in previous answers however these did not suite my needs as I had:

static content (images etc ..)

parts of page not locale dependent (admin panel)

RestController inside same app

multipart file uploader

I also wanted to avoid duplicated content for SEO reasons (In particular I do not want my english content to be accessible from both paths: /landingPage and /en/landingPage).

The solution that worked best for me was to create LanguageAwareController and then inherit from it in all controllers that I wanted to support multiple locales.

@Controller
@RequestMapping(path = "/{lang}")
public class LanguageAwareController {
    @Autowired
    LocaleResolver localeResolver;

    @ModelAttribute(name = "locale")
    Locale getLocale(@PathVariable(name = "lang") String lang, HttpServletRequest request,
                 HttpServletResponse response){
        Locale effectiveLocale = Arrays.stream(Locale.getAvailableLocales())
            .filter(locale -> locale.getLanguage().equals(lang))
            .findFirst()
            .orElseGet(Locale::getDefault);
        localeResolver.setLocale(request, response, effectiveLocale);
        return effectiveLocale;
    }
}

Usage in one of controllers:

@Controller
public class LandingPageController extends LanguageAwareController{

    private Log log = LogFactory.getLog(LandingPageController.class);

    @GetMapping("/")
    public String welcomePage(Locale locale, @PathVariable(name = "lang") String lang ){
        log.info(lang);
        log.info(locale);
        return "landing";
    }
}


问:
Call requires permissions that may be rejected by user
I am trying to make an application that sends location updates of a user after every five minutes. I suppose my code is working just fine but i get an error regarding the permissions that are being used by the application. I am pretty sure that i have added the permissions in the manifest file. Can someone tell me what's wrong? Here is my code.

MainActivity.java

```<code>LocationManager locationManager ;
String provider;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    // Getting LocationManager object
    locationManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE);

    // Creating an empty criteria object
    Criteria criteria = new Criteria();

    // Getting the name of the provider that meets the criteria
    provider = locationManager.getBestProvider(criteria, false);

    if(provider!=null && !provider.equals("")){

        // Get the location from the given provider
        Location location = locationManager.getLastKnownLocation(provider);
        locationManager.requestLocationUpdates(provider,5*60*1000,0,this);

        if(location!=null)
            onLocationChanged(location);
        else
            Toast.makeText(getBaseContext(), "Location can't be retrieved", Toast.LENGTH_SHORT).show();

    }else{
        Toast.makeText(getBaseContext(), "No Provider Found", Toast.LENGTH_SHORT).show();
    }
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    getMenuInflater().inflate(R.menu.main, menu);
    return true;
}

@Override
public void onLocationChanged(Location location) {
    // Getting reference to TextView tv_longitude
    TextView tvLongitude = (TextView)findViewById(R.id.tv_longitude);

    // Getting reference to TextView tv_latitude
    TextView tvLatitude = (TextView)findViewById(R.id.tv_latitude);

    // Setting Current Longitude
    tvLongitude.setText("Longitude:" + location.getLongitude());

    // Setting Current Latitude
    tvLatitude.setText("Latitude:" + location.getLatitude() );
}

@Override
public void onProviderDisabled(String provider) {
    // TODO Auto-generated method stub
}

@Override
public void onProviderEnabled(String provider) {
    // TODO Auto-generated method stub
}

@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
    // TODO Auto-generated method stub
}
</code>```

}

I am getting an error as Call requires permission which may be rejected by user in these lines-

```<code>Location location = locationManager.getLastKnownLocation(provider);
        locationManager.requestLocationUpdates(provider,5*60*1000,0,this);
</code>```

My AndroidManifest is like this

```<code><uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
<uses-permission android:name="android.permission.INTERNET"/>

<application
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:theme="@style/AppTheme" >
    <activity
        android:name=".MainActivity"
        android:label="@string/title_activity_main" >
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />
            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
</application>
</code>```

答:
Here are the bunch of steps you need to perform to fix this

Main Activity .java

```<code>if (ContextCompat.checkSelfPermission(this,
 android.Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED
 || ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION)
 == PackageManager.PERMISSION_GRANTED) {
locationManager.requestLocationUpdates
 (locationManager.requestLocationUpdates(provider,5*60*1000,0,this);
}//end of if
</code>```

Now you also need to update your build.gradle

```<code>dependencies{
 ------------- //your pre-generated code
compile 'com.android.support:support-v4:23.0.1'
}
</code>```

this is what Android.Developers say about it.

And don't forget to give permissions from application settings if you're using an emulator because it may not prompt for such

Body:
I am trying to make an application that sends location updates of a user after every five minutes. I suppose my code is working just fine but i get an error regarding the permissions that are being used by the application. I am pretty sure that i have added the permissions in the manifest file. Can someone tell me what's wrong? Here is my code.

MainActivity.java

LocationManager locationManager ;
String provider;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    // Getting LocationManager object
    locationManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE);

    // Creating an empty criteria object
    Criteria criteria = new Criteria();

    // Getting the name of the provider that meets the criteria
    provider = locationManager.getBestProvider(criteria, false);

    if(provider!=null && !provider.equals("")){

        // Get the location from the given provider
        Location location = locationManager.getLastKnownLocation(provider);
        locationManager.requestLocationUpdates(provider,5*60*1000,0,this);

        if(location!=null)
            onLocationChanged(location);
        else
            Toast.makeText(getBaseContext(), "Location can't be retrieved", Toast.LENGTH_SHORT).show();

    }else{
        Toast.makeText(getBaseContext(), "No Provider Found", Toast.LENGTH_SHORT).show();
    }
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    getMenuInflater().inflate(R.menu.main, menu);
    return true;
}

@Override
public void onLocationChanged(Location location) {
    // Getting reference to TextView tv_longitude
    TextView tvLongitude = (TextView)findViewById(R.id.tv_longitude);

    // Getting reference to TextView tv_latitude
    TextView tvLatitude = (TextView)findViewById(R.id.tv_latitude);

    // Setting Current Longitude
    tvLongitude.setText("Longitude:" + location.getLongitude());

    // Setting Current Latitude
    tvLatitude.setText("Latitude:" + location.getLatitude() );
}

@Override
public void onProviderDisabled(String provider) {
    // TODO Auto-generated method stub
}

@Override
public void onProviderEnabled(String provider) {
    // TODO Auto-generated method stub
}

@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
    // TODO Auto-generated method stub
}

}

I am getting an error as Call requires permission which may be rejected by user in these lines-

Location location = locationManager.getLastKnownLocation(provider);
        locationManager.requestLocationUpdates(provider,5*60*1000,0,this);

My AndroidManifest is like this

<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
<uses-permission android:name="android.permission.INTERNET"/>

<application
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:theme="@style/AppTheme" >
    <activity
        android:name=".MainActivity"
        android:label="@string/title_activity_main" >
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />
            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
</application>

Body:
Here are the bunch of steps you need to perform to fix this

Main Activity .java

if (ContextCompat.checkSelfPermission(this,
 android.Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED
 || ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION)
 == PackageManager.PERMISSION_GRANTED) {
locationManager.requestLocationUpdates
 (locationManager.requestLocationUpdates(provider,5*60*1000,0,this);
}//end of if

Now you also need to update your build.gradle

dependencies{
 ------------- //your pre-generated code
compile 'com.android.support:support-v4:23.0.1'
}

this is what Android.Developers say about it.

And don't forget to give permissions from application settings if you're using an emulator because it may not prompt for such


问:
Handling back button in React Native, Navigator on Android
I have a Navigator in an Android react native application.

I'm using navigator.push() to navigate to a different page. It would seem natural that the back button would pop the navigator and to go back one page, but that's not what's happening (it quits the app).

Do the react-native Navigator really has no back button support, do I need to plug it myself with a BackAndroid?

答:
Don't forget bind [this]

The correct answer should be:

```<code>export default class MyPage extends Component {
  constructor(props) {
    super(props)
    this.navigator = null;

    this.handleBack = (() => {
      if (this.navigator && this.navigator.getCurrentRoutes().length > 1){
        this.navigator.pop();
        return true; //avoid closing the app
      }

      return false; //close the app
    }).bind(this) //don't forget bind this, you will remember anyway.
  }

  componentDidMount() {
    BackAndroid.addEventListener('hardwareBackPress', this.handleBack);
  }

  componentWillUnmount() {
    BackAndroid.removeEventListener('hardwareBackPress', this.handleBack);
  }

  render() {
    return (
      <Navigator
        ref={navigator => {this.navigator = navigator}}
  ...
</code>```

Body:
Don't forget bind [this]

The correct answer should be:

export default class MyPage extends Component {
  constructor(props) {
    super(props)
    this.navigator = null;

    this.handleBack = (() => {
      if (this.navigator && this.navigator.getCurrentRoutes().length > 1){
        this.navigator.pop();
        return true; //avoid closing the app
      }

      return false; //close the app
    }).bind(this) //don't forget bind this, you will remember anyway.
  }

  componentDidMount() {
    BackAndroid.addEventListener('hardwareBackPress', this.handleBack);
  }

  componentWillUnmount() {
    BackAndroid.removeEventListener('hardwareBackPress', this.handleBack);
  }

  render() {
    return (
      <Navigator
        ref={navigator => {this.navigator = navigator}}
  ...


问:
Reading a specific sector from a hard drive using C on Linux (GNU/Linux )
I know that a hard drive are system's files (/dev/sdXX) –then treated like files-, I have questions about this:

I tried those following lines of code but nothing positive

-------first attempt----------

```<code>int numSecteur=2;
char secteur [512];
FILE* disqueF=fopen("/dev/sda","r"); //tried "rb" and sda1 ...every thing
fseek(disqueF, numSecteur*512,SEEK_SET);
fread(secteur, 512, 1, disqueF);
fclose(disqueF);
</code>```

-------Second attempt----------

```<code>    int i=open("/dev/sda1",O_RDONLY);
    lseek(i, 0, SEEK_SET);
    read(i,secteur,512);
    close(i);
</code>```

------printing the results----------

```<code>printf("hex : %04x\n",secteur);
printf("string : %s\n",secteur);
</code>```

Why the size is of the file /dev/sda1 is just 8 KBytes ?

How the data is stored (binary or hex….) "for the printing"

Please, I need some clues, and if someone need more details just he ask.

Thanks a lot.

Ps: Running kali 2 64bits ”debian” on VMware and i am RooT.

答:
You cannot printf() array of chat like that, you need right print result. For example as hex dump:</p>

```<code>for (int i = 0; i < sizeof(secteur); i++) {
    printf ("%02x ", secteur[i]);
    if ((i + 1) % 16 == 0)
        printf ("\n");
}
</code>```

Body:
I know that a hard drive are system's files (/dev/sdXX) –then treated like files-, I have questions about this:

I tried those following lines of code but nothing positive

-------first attempt----------

int numSecteur=2;
char secteur [512];
FILE* disqueF=fopen("/dev/sda","r"); //tried "rb" and sda1 ...every thing
fseek(disqueF, numSecteur*512,SEEK_SET);
fread(secteur, 512, 1, disqueF);
fclose(disqueF);

-------Second attempt----------

    int i=open("/dev/sda1",O_RDONLY);
    lseek(i, 0, SEEK_SET);
    read(i,secteur,512);
    close(i);

------printing the results----------

printf("hex : %04x\n",secteur);
printf("string : %s\n",secteur);

Why the size is of the file /dev/sda1 is just 8 KBytes ?

How the data is stored (binary or hex….) "for the printing"

Please, I need some clues, and if someone need more details just he ask.

Thanks a lot.

Ps: Running kali 2 64bits ”debian” on VMware and i am RooT.

Body:
You cannot printf() array of chat like that, you need right print result. For example as hex dump:

for (int i = 0; i < sizeof(secteur); i++) {
    printf ("%02x ", secteur[i]);
    if ((i + 1) % 16 == 0)
        printf ("\n");
}


问:
How to get the subscription id related to the current order?
I'm using woocommerce subscriptions and I'm writing a plugin to update an external system, if the user upgrade or downgrade his subscription it shows as a new order with its ID, but I can't get the subscription ID (which it's constant) related to the order ID, I check the documentation but I couldn't find a solution.  </p>

答:
You can access this data by hooking into the processed_subscription_payment action provided by WooCommerce Subscriptions:

```<code>add_action( 'processed_subscription_payment', 'se43079522_process_subscription', 10, 2 );

function se43079522_process_subscription($user_id, $subscription_key) {
    // here you have access to the $subscription_key (ID) and the $user_id associated
}
</code>```

Take a look at this link: https://docs.woocommerce.com/document/subscriptions/develop/action-reference/ for more information on the available actions with this plugin.

OR, you can do this manually like so:

Read comments for walk-through

```<code>global $woocommerce;

// Get the order ID and save as variable
$order_id = [ORDER_ID];

// Get the order object
$order = new WC_Order( $order_id );

// Loop through the subscription order
foreach ( WC_Subscriptions_Order::get_recurring_items( $order ) as $order_item ) {

    // Get the subscription key
    $subscription_key = WC_Subscriptions_Manager::get_subscription_key( $order->id, WC_Subscriptions_Order::get_items_product_id( $order_item ) );

}

// This is your subscription key (ID)
echo $subscription_key;
</code>```

Body:
You can access this data by hooking into the processed_subscription_payment action provided by WooCommerce Subscriptions:

add_action( 'processed_subscription_payment', 'se43079522_process_subscription', 10, 2 );

function se43079522_process_subscription($user_id, $subscription_key) {
    // here you have access to the $subscription_key (ID) and the $user_id associated
}

Take a look at this link: https://docs.woocommerce.com/document/subscriptions/develop/action-reference/ for more information on the available actions with this plugin.

OR, you can do this manually like so:

Read comments for walk-through

global $woocommerce;

// Get the order ID and save as variable
$order_id = [ORDER_ID];

// Get the order object
$order = new WC_Order( $order_id );

// Loop through the subscription order
foreach ( WC_Subscriptions_Order::get_recurring_items( $order ) as $order_item ) {

    // Get the subscription key
    $subscription_key = WC_Subscriptions_Manager::get_subscription_key( $order->id, WC_Subscriptions_Order::get_items_product_id( $order_item ) );

}

// This is your subscription key (ID)
echo $subscription_key;


问:
Why do these sum operations not "add up" as they should?
Note: This is a follow[on,up] to this question and this question and this question.

The responses all moved me forward, but even that last one, although it improved matters, did not completely solve this issue.

This query:

```<code>select monthlysales, MemberNo from ReportingMonthlySales
where unit = 'Abuelos' and CYear = 2017 and cmonth = 3
</code>```

...returns a bunch of rows, where the Monthly Sales total is $364,121.69

However, when I try to compartmentalize these monthly sales into four categories, although the sum of them all should be the same, the sum is actually astronomically "huger" - the following code returns the vastly inflated value of 23,924,211.30

24 millions of dollars is almost 70 times as much as the 364 thousand that is the actual sum total. Why is this "crazy" inflation occurring?

Here is the fancy pants but apparently bamboozled code:

```<code>declare @Unit varchar(30);
declare @Year int = 2017;
declare @Month int = 3;
declare @paramdate datetime;
set @paramdate = convert(datetime,convert(char(4),@Year)
                +right('0'+convert(varchar(2),@month),2)
                +'01')

IF OBJECT_ID('tempdb.dbo.#Units', 'U') IS NOT NULL
DROP TABLE #Units

select distinct unit
into #Units
from ReportingMonthlySales;

select
    u.Unit
  , New      = sum(case when ccl.Subcategory = 'New'      then rms.MonthlySales else 0 end)
  , Assumed  = sum(case when ccl.Subcategory = 'Assumed'  then rms.MonthlySales else 0 end)
  , Existing = sum(case when ccl.Subcategory = 'Existing' then rms.MonthlySales else 0 end)
  , Organic  = sum(case when ccl.Subcategory = 'Organic'  then rms.MonthlySales else 0 end)
from #Units u
  left join CustomerCategoryLog ccl
    on u.Unit = ccl.Unit
   and @paramdate >= ccl.begindate and
   (@paramdate <= ccl.enddate OR ccl.enddate is null)
  left join ReportingMonthlySales rms
    on u.Unit = rms.Unit
   and rms.cyear  = @year
   and rms.cmonth = @month
group by u.unit;

The two tables queried are:

CustomerCategoryLog
-------------------
MemberNo (VarChar)
Unit (VarChar)
Custno (VarChar)
Category (VarChar)
Subcategory (VarChar)
BeginDate (DateTime)
EndDate (DateTime)
ChangedBy (VarChar)
ChangedOn (DateTime)

ReportingMonthlySales
---------------------
AutoID (Int)
Unit (VarChar)
MemberNo (VarChar)
NumUnits (Int)
MonthlySales (Money)
CYear (Int)
Cmonth (Int)
CreateDate (DateTime)
</code>```

Is there something faulty in the fancy-pants sql, or ... ?!?

答: Your CustomerCategoryTable as what its name implies could have multiple records for different CustNo for the same UnitNo and that makes your first left join returns duplicate rows which will multiplies the monthly sales, and what I think is that there is no solution for your query except if you try to fix the schema itself for one simple information is that you are trying to find the monthly sales for each unit for it's different subcategorues and your ReportingMonthlySales table doesn't have any information regarding the subcategories.</p>

Body:
Note: This is a follow[on,up] to this question and this question and this question.

The responses all moved me forward, but even that last one, although it improved matters, did not completely solve this issue.

This query:

select monthlysales, MemberNo from ReportingMonthlySales
where unit = 'Abuelos' and CYear = 2017 and cmonth = 3

...returns a bunch of rows, where the Monthly Sales total is $364,121.69

However, when I try to compartmentalize these monthly sales into four categories, although the sum of them all should be the same, the sum is actually astronomically "huger" - the following code returns the vastly inflated value of 23,924,211.30

24 millions of dollars is almost 70 times as much as the 364 thousand that is the actual sum total. Why is this "crazy" inflation occurring?

Here is the fancy pants but apparently bamboozled code:

declare @Unit varchar(30);
declare @Year int = 2017;
declare @Month int = 3;
declare @paramdate datetime;
set @paramdate = convert(datetime,convert(char(4),@Year)
                +right('0'+convert(varchar(2),@month),2)
                +'01')

IF OBJECT_ID('tempdb.dbo.#Units', 'U') IS NOT NULL
DROP TABLE #Units

select distinct unit
into #Units
from ReportingMonthlySales;

select
    u.Unit
  , New      = sum(case when ccl.Subcategory = 'New'      then rms.MonthlySales else 0 end)
  , Assumed  = sum(case when ccl.Subcategory = 'Assumed'  then rms.MonthlySales else 0 end)
  , Existing = sum(case when ccl.Subcategory = 'Existing' then rms.MonthlySales else 0 end)
  , Organic  = sum(case when ccl.Subcategory = 'Organic'  then rms.MonthlySales else 0 end)
from #Units u
  left join CustomerCategoryLog ccl
    on u.Unit = ccl.Unit
   and @paramdate >= ccl.begindate and
   (@paramdate <= ccl.enddate OR ccl.enddate is null)
  left join ReportingMonthlySales rms
    on u.Unit = rms.Unit
   and rms.cyear  = @year
   and rms.cmonth = @month
group by u.unit;

The two tables queried are:

CustomerCategoryLog
-------------------
MemberNo (VarChar)
Unit (VarChar)
Custno (VarChar)
Category (VarChar)
Subcategory (VarChar)
BeginDate (DateTime)
EndDate (DateTime)
ChangedBy (VarChar)
ChangedOn (DateTime)

ReportingMonthlySales
---------------------
AutoID (Int)
Unit (VarChar)
MemberNo (VarChar)
NumUnits (Int)
MonthlySales (Money)
CYear (Int)
Cmonth (Int)
CreateDate (DateTime)

Is there something faulty in the fancy-pants sql, or ... ?!?


问:
Is there any shortcut for array size / length in C?
Is there any way to speed up getting an array size in C?

Typing out sizeof(array)/sizeof(int) every time gets old.  Do any C libraries have something like .length or is there some way I can define sizeof(array)/sizeof(int) as a shorter constant of some sort (possible also using dot notation)?

答:
You can use sizeof(array)/sizeof(*array) and make a macro.

```<code>#define length(array) (sizeof(array)/sizeof(*(array)))
</code>```

Body:
You can use sizeof(array)/sizeof(*array) and make a macro.

#define length(array) (sizeof(array)/sizeof(*(array)))


问:
Tests magically disappeared from Test Explorer pane in Visual Studio 2013
I have created a unit test project in VS2013, and I'm using it to create a test suite for my SQL Server 2012 database.

I have created 4 test classes so far and everything worked fine. When I created the 5th - magic! All tests disappear from the test explorer window.

I tried rebuilding the project - didn't work. Rebuilt the database project too; didn't work. Created a new unit testing project with a single unit test inside it - doesn't work.

Has this happened to anyone? Does anyone know what to do? Please help!

答:
I just had the exact same thing happen to be. Build, Rebuild, Clean Build, the Test Explorer couldn't list for me my unit tests!

This came after I changed the unit test project's platform target from "any CPU" to x64. I switched it back to "any CPU", built, and they appeared again. How frustrating.


问:
How to setup the linux "hcitool lecup" from within a python script?
I am trying to read some sensor data from a wireless BLE IMU sensor into my Raspberry Pi 3B. I need to be able to read the data at 100Hz (10ms intervals). It appears that one of the aspects I need to configure is the polling interval of "hcitool lecup". Here are the two main things I am struggling:

How can I configure the command from my python script without having to run it from my terminal window?

What would be the correct way to configure the intervals to get 10Hz polling rate? Can I set the min and max intervals to be the same: hcitool lecup -H handle -m 0x0008 -M 0x0008 -l 0000 -t 0x0064?

Thank you!

答:
Calling subprocesses with python is best done with the subprocess module and the Popen method.

This question might be of help to you


问:
How to access mysql outside my kubernetes cluster?
I am running a kubernetes cluster in my centos machine.
I donot want to create a pod for mysql. MySQL is installed in another machine in same network (Machine is not in kubernates private network).

How can I access the mysql service from the pods running in kubernetes cluster ?

I have tried with service and end point with below configuration. But, No luck.

```<code>apiVersion: v1
kind: Service
metadata:
  name: database
spec:
  ports:
  - port: 13080
    targetPort: 13080
    protocol: TCP
---
kind: Deployment
apiVersion: v1
metadata:
  name: database
subsets:
  - addresses:
      - ip: XX.XX.XX.XX
    ports:
      - port: 13080
---
kind: ReplicationController
metadata:
  name: test
spec:
  replicas: 1
  selector:
    app: test
  template:
    metadata:
      name: test
      labels:
        app: test
    spec:
      containers:
      - name: my_pods
        image: my_pods
        env:
         - name: DATABASE_HOST
           value: database
         - name: DATABASE_PORT
           value: "13080"
         - name: DATABASE_USER
           value: "SAAS"
         - name: DATABASE_PASSWORD
           value: "SAAS"
         - name: DATABASE_NAME
           value: "SAASDB"
        ports:
          - containerPort: 8080
      imagePullSecrets:
        - name: my-secret
---
apiVersion: v1
kind: Service
metadata:
  name: test-service
  labels:
    name: test-service
spec:
  type: NodePort
  ports:
     - port: 11544
       targetPort: 8080
       nodePort: 30600
  selector:
    name: test
</code>```

答: You don't need a service for things outside the cluster. Depending on the networking model you're using, the docker container (ie kubernetes pod) should be able to connect to the MySQL container normally via the bridge that Docker sets up. Check the host has connectivity on port 3306, and it does, simply put in the DNS name (your kube-dns pod should forward any non kubernetes based requests on to the hosts resolv.conf of the host it was scheduled on)</p>

Body:
I am running a kubernetes cluster in my centos machine.
I donot want to create a pod for mysql. MySQL is installed in another machine in same network (Machine is not in kubernates private network).

How can I access the mysql service from the pods running in kubernetes cluster ?

I have tried with service and end point with below configuration. But, No luck.

apiVersion: v1
kind: Service
metadata:
  name: database
spec:
  ports:
  - port: 13080
    targetPort: 13080
    protocol: TCP
---
kind: Deployment
apiVersion: v1
metadata:
  name: database
subsets:
  - addresses:
      - ip: XX.XX.XX.XX
    ports:
      - port: 13080
---
kind: ReplicationController
metadata:
  name: test
spec:
  replicas: 1
  selector:
    app: test
  template:
    metadata:
      name: test
      labels:
        app: test
    spec:
      containers:
      - name: my_pods
        image: my_pods
        env:
         - name: DATABASE_HOST
           value: database
         - name: DATABASE_PORT
           value: "13080"
         - name: DATABASE_USER
           value: "SAAS"
         - name: DATABASE_PASSWORD
           value: "SAAS"
         - name: DATABASE_NAME
           value: "SAASDB"
        ports:
          - containerPort: 8080
      imagePullSecrets:
        - name: my-secret
---
apiVersion: v1
kind: Service
metadata:
  name: test-service
  labels:
    name: test-service
spec:
  type: NodePort
  ports:
     - port: 11544
       targetPort: 8080
       nodePort: 30600
  selector:
    name: test


问:
How do I simulate transient errors with Azure Database?
I am working with the Transient Fault Handling Application Block (TFHAB) to define a retry policy when interfacing with an Azure Database. I'm wondering if there is a way to invoke a throttling response in order to plan and handle likely production scenarios?

I could place an SQL command in a loop and run it until I invoke a response however presumably this is not considered to be "best practice"?

Can anyone suggest some practical ways in which I can test my transient error handling logic?

答: My recommendation to you is dependency injection:) To eloborate, your higher level client code should not take a direct dependency to azure, put the client SDK behind an interface and pass that interface as dependency to your higher level client code. Pass the actual sdk for production code as the interface implementation and for your tests pass a test implementation of the interface where you can return any error code or response you want. </p>


问:
CSS - Absolute unit that stays the same between devices
As mentioned in this question, a pixel is not an absolute unit, and I've found this to be the case in practice.

I've also tried using pt, cm and mm but I can't find an absolute unit, I want a unit I can use to specify element sizes that will always stay the same regardless of the screen size or device that is used.

Is there a unit I can use to accomplish this?

答:
What about using VW and VH to size both fonts and elements?<br>
https://webflow.com/blog/how-and-why-to-use-vh-and-vw-in-webflow  </p>

Body:
What about using VW and VH to size both fonts and elements?

https://webflow.com/blog/how-and-why-to-use-vh-and-vw-in-webflow


问:
How to get automatic table creation working in spring / hibernate / jpa?
I can't get automatic table creation working in spring when using hibernate / jpa.

Here are my config files:

```<code><?xml version="1.0" encoding="UTF-8"?>
<persistence
   xmlns="http://java.sun.com/xml/ns/persistence"
   xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
   xsi:schemaLocation="http://java.sun.com/xml/ns/persistence
   http://java.sun.com/xml/ns/persistence/persistence_1_0.xsd"
   version="1.0">

    <persistence-unit name="naveroTest">
     <provider>org.hibernate.ejb.HibernatePersistence</provider>
     <class>xxx</class>
        ...

        <properties>
            <property name="hibernate.archive.autodetection" value="class, hbm"/>
            <property name="hibernate.show_sql" value="true"/>
            <property name="hibernate.connection.driver_class" value="org.hsqldb.jdbcDriver"/>
   <property name="hibernate.connection.url" value="jdbc:hsqldb:file:/tmp/naveroTestDB"/>
            <property name="hibernate.connection.username" value="sa"/>
            <property name="hibernate.connection.password" value=""/>
            <property name="hibernate.hbm2ddl.auto" value="create"/>
            <property name="hibernate.dialect" value="org.hibernate.dialect.HSQLDialect"/>
        </properties>
    </persistence-unit>
</persistence>
</code>```

context.xml

```<code>   <?xml version="1.0" encoding="UTF-8"?>
    <beans xmlns:tx="http://www.springframework.org/schema/tx"
        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-2.0.xsd
                            http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.0.xsd
                           http://www.springframework.org/schema/security http://www.springframework.org/schema/security/spring-security-2.0.4.xsd">

     <!-- For auto creation of tables -->
     <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
      <property name="driverClassName" value="org.hsqldb.jdbcDriver" />
      <property name="url" value="jdbc:hsqldb:file:/tmp/naveroTestDB" />
      <property name="username" value="sa" />
      <property name="password" value="" />
     </bean>

     <bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
      <property name="dataSource" ref="dataSource" />
      <property name="loadTimeWeaver">
       <bean class="org.springframework.instrument.classloading.InstrumentationLoadTimeWeaver" />
      </property>
      <property name="jpaVendorAdapter">
       <bean id="jpaAdapter" class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
        <property name="generateDdl" value="true" />
        <property name="databasePlatform" value="org.hibernate.dialect.HSQLDialect" />
        <property name="showSql" value="true" />
       </bean>
      </property>
     </bean>

     <bean id="PictureBean" class="de.navero.server.bl.PictureBean">
      <property name="entityManagerFactory"><ref local="entityManagerFactory" /></property>
     </bean>

    </beans>
</code>```

Any ideas what may be wrong?
Thanks for any help :).

答:
try the following:

```<code>
<?xml version="1.0" encoding="UTF-8"?>
<persistence version="1.0" xmlns="http://java.sun.com/xml/ns/
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://.sun.com/xml/ns/persistence
  http://java.sun.com/xml/ns/persistence/persistence_1_0.xsd">
    <persistence-unit name="naveroTest" transaction-type="RESOURCE_LOCAL" />
</persistence>
</code>```

```<code>
<?xml version="1.0" encoding="UTF-8"?>
<bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
    <property name="jpaVendorAdapter">
        <bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter"/>
    </property>
    <property name="jpaProperties">
        <props>
...
            <prop key="hibernate.hbm2ddl.auto">create-drop</prop>
        </props>
    </property>
    <property name="dataSource" ref="dataSource" />
</bean>
</code>```

This works for me.

Body:
I can't get automatic table creation working in spring when using hibernate / jpa.

Here are my config files:

<?xml version="1.0" encoding="UTF-8"?>
<persistence
   xmlns="http://java.sun.com/xml/ns/persistence"
   xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
   xsi:schemaLocation="http://java.sun.com/xml/ns/persistence
   http://java.sun.com/xml/ns/persistence/persistence_1_0.xsd"
   version="1.0">

    <persistence-unit name="naveroTest">
     <provider>org.hibernate.ejb.HibernatePersistence</provider>
     <class>xxx</class>
        ...

        <properties>
            <property name="hibernate.archive.autodetection" value="class, hbm"/>
            <property name="hibernate.show_sql" value="true"/>
            <property name="hibernate.connection.driver_class" value="org.hsqldb.jdbcDriver"/>
   <property name="hibernate.connection.url" value="jdbc:hsqldb:file:/tmp/naveroTestDB"/>
            <property name="hibernate.connection.username" value="sa"/>
            <property name="hibernate.connection.password" value=""/>
            <property name="hibernate.hbm2ddl.auto" value="create"/>
            <property name="hibernate.dialect" value="org.hibernate.dialect.HSQLDialect"/>
        </properties>
    </persistence-unit>
</persistence>

context.xml

   <?xml version="1.0" encoding="UTF-8"?>
    <beans xmlns:tx="http://www.springframework.org/schema/tx"
        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-2.0.xsd
                            http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.0.xsd
                           http://www.springframework.org/schema/security http://www.springframework.org/schema/security/spring-security-2.0.4.xsd">

     <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
      <property name="driverClassName" value="org.hsqldb.jdbcDriver" />
      <property name="url" value="jdbc:hsqldb:file:/tmp/naveroTestDB" />
      <property name="username" value="sa" />
      <property name="password" value="" />
     </bean>

     <bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
      <property name="dataSource" ref="dataSource" />
      <property name="loadTimeWeaver">
       <bean class="org.springframework.instrument.classloading.InstrumentationLoadTimeWeaver" />
      </property>
      <property name="jpaVendorAdapter">
       <bean id="jpaAdapter" class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
        <property name="generateDdl" value="true" />
        <property name="databasePlatform" value="org.hibernate.dialect.HSQLDialect" />
        <property name="showSql" value="true" />
       </bean>
      </property>
     </bean>

     <bean id="PictureBean" class="de.navero.server.bl.PictureBean">
      <property name="entityManagerFactory"><ref local="entityManagerFactory" /></property>
     </bean>

    </beans>

Any ideas what may be wrong?
Thanks for any help :).

Body:
try the following:

<?xml version="1.0" encoding="UTF-8"?>
<persistence version="1.0" xmlns="http://java.sun.com/xml/ns/
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://.sun.com/xml/ns/persistence
  http://java.sun.com/xml/ns/persistence/persistence_1_0.xsd">
    <persistence-unit name="naveroTest" transaction-type="RESOURCE_LOCAL" />
</persistence>

<?xml version="1.0" encoding="UTF-8"?>
<bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
    <property name="jpaVendorAdapter">
        <bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter"/>
    </property>
    <property name="jpaProperties">
        <props>
...
            <prop key="hibernate.hbm2ddl.auto">create-drop</prop>
        </props>
    </property>
    <property name="dataSource" ref="dataSource" />
</bean>

This works for me.


问:
smart table column show/hide toggle
I'm new to AngularJS and SmartTable...I'm currently trying to get SmartTable to have a show/hide toggle for the columns.  From what I undertstand SmartTable doesn't do this, so I am using the ng-Grid show/hide feature...trying to follow this solution:
how to hide/show ng-grid column externally?

When I implemented this solution my columns aren't showing up.

How do you set smartTable columns to "show" upon initial set up?  I think this is what I'm missing...

Here is my js:

```<code>var app = angular.module('myApp', ['smart-table', 'ngGrid']);

app.controller('paginationCtrl', ['$scope', function (scope) {
var nameList = ['Brian', 'Bob', 'Marie', 'Jennifer', 'Frank'],
    familyName = ['Smith', 'Miller', 'Patel', 'Jefferson', 'Mendez'];

...

$scope.toggleCol= function(i) {
   $scope.gridOptions.$gridScope.columns[i].toggleVisible()
}

    scope.itemsByPage=15;

scope.rowCollection = [];
for (var j = 0; j < 200; j++) {
    scope.rowCollection.push(createRandomItem());
}

}]);
</code>```

and here's my html:

```<code><body ng-controller="paginationCtrl">
<p>Smart Table Example</p>
<input type="button" value="First Name" ng-click="toggleCol(0)" />
<table class="table table-striped" st-table="rowCollection">
  <thead>
    <tr>
      <th st-sort="firstName">first name</th>
      <th st-sort="lastName">last name</th>
      <th st-skip-natural="true" st-sort="balance">balance</th>
      <th>email</th>
    </tr>
  </thead>
  <tbody>
    <tr ng-repeat="row in rowCollection">
      <td>{{row.firstName}}</td>
      <td>{{row.lastName}}</td>
      <td>{{row.balance}}</td>
      <td>{{row.email}}</td>
    </tr>
  </tbody>
  <tfoot>
    <tr>
      <td class="text-center" colspan="5">
        <div st-displayed-pages="7" st-items-by-page="itemsByPage" st-pagination=""></div>
      </td>
    </tr>
  </tfoot>
</table>
</code>```

You can see my entire setup on my plunker example:

http://plnkr.co/edit/6F8NsDdgaWranTXeIQuV?p=preview

Thanks!!

答:
I know this is old but wrote this directive that solves it.
 it do all alone.

https://github.com/cesardmoro/tableColumnToggler

Title: smart table column show/hide toggle

Body:
I'm new to AngularJS and SmartTable...I'm currently trying to get SmartTable to have a show/hide toggle for the columns.  From what I undertstand SmartTable doesn't do this, so I am using the ng-Grid show/hide feature...trying to follow this solution:
how to hide/show ng-grid column externally?

When I implemented this solution my columns aren't showing up.

How do you set smartTable columns to "show" upon initial set up?  I think this is what I'm missing...

Here is my js:

var app = angular.module('myApp', ['smart-table', 'ngGrid']);

app.controller('paginationCtrl', ['$scope', function (scope) {
var nameList = ['Brian', 'Bob', 'Marie', 'Jennifer', 'Frank'],
    familyName = ['Smith', 'Miller', 'Patel', 'Jefferson', 'Mendez'];

...

$scope.toggleCol= function(i) {
   $scope.gridOptions.$gridScope.columns[i].toggleVisible()
}

    scope.itemsByPage=15;

scope.rowCollection = [];
for (var j = 0; j < 200; j++) {
    scope.rowCollection.push(createRandomItem());
}

}]);

and here's my html:

Smart Table Example

<input type="button" value="First Name" ng-click="toggleCol(0)" />

      first name
      last name
      balance
      email

      {{row.firstName}}
      {{row.lastName}}
      {{row.balance}}
      {{row.email}}

You can see my entire setup on my plunker example:

http://plnkr.co/edit/6F8NsDdgaWranTXeIQuV?p=preview

Thanks!!


问:
How to use json2html with random keys
So, I clearly understand how to transform JSON to HTML if I know what type of data i will get in json.

But how can I use json2html if I don't know what kind of keys I will get from server?

Here code, that works correctly with static keys:

var data = {'json': [{
    'order': 'By',
        'name': 'Stack',
        'randomkey': '3',
        'randomkey_n': '0',
        'score': '121',
        'id': '540'
}]};

var transform = {
    tag: 'tr',
    children: [{
        "tag": "td",
            "html": "${order}"
    }, {
        "tag": "td",
            "html": "${name}"
    }, {
        "tag": "td",
            "html": "${randomkey}"
    }, {
        "tag": "td",
            "html": "${randomkey_n}"
    }, {
        "tag": "td",
            "html": "${score}"
    }]
};

$('#placar > tbody ').json2html(data.json, transform);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="http://json2html.com/js/json2html.js"></script>
<script src="http://json2html.com/js/jquery.json2html.js"></script>
<div class="container">
    <p>
        <table id="placar" class="table table-condensed  table-bordered">
            <thead>
                <tr>
                    <th>1</th>
                    <th>2</th>
                    <th>3</th>
                    <th>4</th>
                    <th>5</th>
                </tr>
            </thead>
            <tbody></tbody>
        </table>
</div></code>```

I understand, that I should use inline function in transform, but I can't understand how to return value of "random" keys.

答:
Nice answer tincot .. just to add another way of doing this that might be a little easier to understand.  You could transform the json object into an array with the property name and value then use a static transform</p>

```<code>var data = {'json': [{
    'order': 'By',
        'name': 'Stack',
        'randomkey': '3',
        'randomkey_n': '0',
        'score': '121',
        'id': '540'
}]};

var transform = {"<>": "tr","html":[
            {"<>":"td","html":"${val}"}
        ]};

var _data = [];

for(var i=0; i < data.json.length; i++){

  var out = [];

  for(var prop in data.json[i])
    if(prop !== "id") out[i] = {"name":prop,"val":data.json[i][prop]};

  _data.push(out);
}

$('#placar > tbody ').json2html(_data, transform);
</code>```

Title: How to use json2html with random keys

Body:
So, I clearly understand how to transform JSON to HTML if I know what type of data i will get in json.

But how can I use json2html if I don't know what kind of keys I will get from server?

Here code, that works correctly with static keys:

var data = {'json': [{
    'order': 'By',
        'name': 'Stack',
        'randomkey': '3',
        'randomkey_n': '0',
        'score': '121',
        'id': '540'
}]};

var transform = {
    tag: 'tr',
    children: [{
        "tag": "td",
            "html": "${order}"
    }, {
        "tag": "td",
            "html": "${name}"
    }, {
        "tag": "td",
            "html": "${randomkey}"
    }, {
        "tag": "td",
            "html": "${randomkey_n}"
    }, {
        "tag": "td",
            "html": "${score}"
    }]
};

$('#placar > tbody ').json2html(data.json, transform);

                    1
                    2
                    3
                    4
                    5

I understand, that I should use inline function in transform, but I can't understand how to return value of "random" keys.

Body:
Nice answer tincot .. just to add another way of doing this that might be a little easier to understand.  You could transform the json object into an array with the property name and value then use a static transform

var data = {'json': [{
    'order': 'By',
        'name': 'Stack',
        'randomkey': '3',
        'randomkey_n': '0',
        'score': '121',
        'id': '540'
}]};

var transform = {"<>": "tr","html":[
            {"<>":"td","html":"${val}"}
        ]};

var _data = [];

for(var i=0; i < data.json.length; i++){

  var out = [];

  for(var prop in data.json[i])
    if(prop !== "id") out[i] = {"name":prop,"val":data.json[i][prop]};

  _data.push(out);
}

$('#placar > tbody ').json2html(_data, transform);


问:
Mysql find value in multiple database (same structure)
With the plan that I have with my hosting, I have size limit for the databases, but I do not have limit in number of database.
To solve this I have thought of dividing my databases by countries and each database has the same structure.
The problem is how to look up data in all these databases.
For example, each database can have a users table.
The problem is how to find a user (for example) in all these databases. (Can be 250 of databases)

```<code>/*This would be for one database*/
SELECT user_name FROM DB1.users WHERE user_name = 'my_user_name' LIMIT 1;
</code>```

Is there any way to search 'my_user_name' from all databases ?
(Users is only one example ... the value to search can be products , city , coordinates etc etc)

答:
You will need to open separate connections to each database and re-execute the query for each database, then combine the data together in your own code - this will be messy and you will run into problems with colliding primary-keys unless you prefix them all with a database-name qualifier.

You haven't said what language you're using, but in psuedocode it would be like this:

```<code>let connectionStrings: String[] {
    "server=dbServer,database=asia",
    "server=dbServer,database=europe",
    "server=dbServer,database=northAmerica"
}

let users = new List<User>()

foreach(connectionString in connectionStrings) {

    let connection = new DBConnection( connectionString )
    let reader = connection.executeQuery( "SELECT * FROM Users" )
    while( reader.read() ) {

        let user = new User() {
            userId = connection.databaseName + reader.get("userId"),
            userName = reader.get("userName"),
            // etc
        }
        users.add( user );
    }
}

return users;
</code>```

Repeat this for all the queries you want to do.

This is a bad idea - databases are cheap, most shared hosting providers offer gigabyte-sized databases even in their $5/mo plans.

Body:
With the plan that I have with my hosting, I have size limit for the databases, but I do not have limit in number of database.
To solve this I have thought of dividing my databases by countries and each database has the same structure.
The problem is how to look up data in all these databases.
For example, each database can have a users table.
The problem is how to find a user (for example) in all these databases. (Can be 250 of databases)

/*This would be for one database*/
SELECT user_name FROM DB1.users WHERE user_name = 'my_user_name' LIMIT 1;

Is there any way to search 'my_user_name' from all databases ?
(Users is only one example ... the value to search can be products , city , coordinates etc etc)

Body:
You will need to open separate connections to each database and re-execute the query for each database, then combine the data together in your own code - this will be messy and you will run into problems with colliding primary-keys unless you prefix them all with a database-name qualifier.

You haven't said what language you're using, but in psuedocode it would be like this:

let connectionStrings: String[] {
    "server=dbServer,database=asia",
    "server=dbServer,database=europe",
    "server=dbServer,database=northAmerica"
}

let users = new List<User>()

foreach(connectionString in connectionStrings) {

    let connection = new DBConnection( connectionString )
    let reader = connection.executeQuery( "SELECT * FROM Users" )
    while( reader.read() ) {

        let user = new User() {
            userId = connection.databaseName + reader.get("userId"),
            userName = reader.get("userName"),
            // etc
        }
        users.add( user );
    }
}

return users;

Repeat this for all the queries you want to do.

This is a bad idea - databases are cheap, most shared hosting providers offer gigabyte-sized databases even in their $5/mo plans.


问:
How can I render a VisualElement before the NavigationPage toolbar?
Using NavigationPage produces views likes this:

```<code>===== Start of view
<navigation toolbar>
<page content>
===== End of view
</code>```

I want this (pretty much the same thing as How to create a view above navigation bar or other screen content?):

```<code>===== Start of view
<arbitrary VisualElement>
<navigation toolbar>
<page content>
===== End of view
</code>```

I know this can be done without NavigationPage by using platform-specific navigation controller APIs. However, I would like to use the Xamarin.Forms NavigationPage navigation stack management, meaning that I either need to use NavigationPage or possibly a subclass of NavigationPage.

How can I render a VisualElement before the NavigationPage toolbar?

答: Honestly, this is not really a setup you would want to do in Xamarin.Forms. It is possible you could look at hiding the NavBar and making your own, but then you would no longer have things like the native back button or toolbar items and need to implement them yourself. This is definitely a case where you likely will want to look at solutions per platform; trying to leverage this in Forms will likely be messy at best.</p>

Body:
Using NavigationPage produces views likes this:

===== Start of view
<navigation toolbar>
<page content>
===== End of view

I want this (pretty much the same thing as How to create a view above navigation bar or other screen content?):

===== Start of view
<arbitrary VisualElement>
<navigation toolbar>
<page content>
===== End of view

I know this can be done without NavigationPage by using platform-specific navigation controller APIs. However, I would like to use the Xamarin.Forms NavigationPage navigation stack management, meaning that I either need to use NavigationPage or possibly a subclass of NavigationPage.

How can I render a VisualElement before the NavigationPage toolbar?


问:
Eclipse JDT: How to get java package name of a non-existing IFolder
Given an IFolder instsance fd (fd may or may not exist), how to get the java package name if fd represents a java package? Currently I coded in this way

```<code>IJavaProject jp = JavaCore.create(fd.getProject());
IPackageFragment pf = jp.findPackageFragment(f.getFullPath());
String pname = pf.getElementName();
</code>```

The code failed when fd does not exist (for example it was just deleted and the deletion was caught in IResourceDelta of an IResourceChangeListener), as IJavaProject#findPackageFragment(IPath) returns null for non-existing item. How to get the package name for a non-existing IFolder? Thanks

答:
Does the inexistent IFolder still have a useful parent chain? If so, you may want to find the parent that corresponds to a package fragment root of the current project.

```<code>IContainer parent = fd.getParent();
while (parent != null) {
    if (JavaCore.create(parent) instanceof IPackageFragmentRoot)
        // success: parent is a source folder
    else
        parent = parent.getParent();
}
</code>```

Then take the relative path from the package fragment root to the folder as the package name.

```<code>IPath myPath = fd.getFullPath();
IPath parentPath = parent.getFullPath();
IPath packagePath = myPath.makeRelativeTo(parentPath);
</code>```

PS: per JLS a package is only observable if a compilation unit in the package is observable. Ergo an inexistent folder can never represent a package (but I admit this is picking on words).

Body:
Given an IFolder instsance fd (fd may or may not exist), how to get the java package name if fd represents a java package? Currently I coded in this way

IJavaProject jp = JavaCore.create(fd.getProject());
IPackageFragment pf = jp.findPackageFragment(f.getFullPath());
String pname = pf.getElementName();

The code failed when fd does not exist (for example it was just deleted and the deletion was caught in IResourceDelta of an IResourceChangeListener), as IJavaProject#findPackageFragment(IPath) returns null for non-existing item. How to get the package name for a non-existing IFolder? Thanks

Body:
Does the inexistent IFolder still have a useful parent chain? If so, you may want to find the parent that corresponds to a package fragment root of the current project.

IContainer parent = fd.getParent();
while (parent != null) {
    if (JavaCore.create(parent) instanceof IPackageFragmentRoot)
        // success: parent is a source folder
    else
        parent = parent.getParent();
}

Then take the relative path from the package fragment root to the folder as the package name.

IPath myPath = fd.getFullPath();
IPath parentPath = parent.getFullPath();
IPath packagePath = myPath.makeRelativeTo(parentPath);

PS: per JLS a package is only observable if a compilation unit in the package is observable. Ergo an inexistent folder can never represent a package (but I admit this is picking on words).


问:
C Prints One Char More Without Value
I am trying to print the ASCII values of 3 char-type characters. When I input the first char it doesn't print the value of the char. After the first char it starts to give the value.

```<code>#include <stdio.h>
int main()  {
    char ch;
    int t;
    while(t < 3){
        scanf("%c\n", &ch);
        printf("%c - %d\n", ch,ch);
        t++;
    }
}
</code>```

http://i54.tinypic.com/2mdqb7d.png

答: Variable t is not automatically initialized to 0 by compiler. So You need to initialize t with 0. If printf doesn't print immediately it means the data is buffered. If you want to see immediatley you may consider flushing stdout right after printf.</p>

Title: C Prints One Char More Without Value

Body:
I am trying to print the ASCII values of 3 char-type characters. When I input the first char it doesn't print the value of the char. After the first char it starts to give the value.

#include <stdio.h>
int main()  {
    char ch;
    int t;
    while(t < 3){
        scanf("%c\n", &ch);
        printf("%c - %d\n", ch,ch);
        t++;
    }
}

http://i54.tinypic.com/2mdqb7d.png