text:
Q: BATCH - Mirrow two Folders in both Ways I safe some Files at my Local Drive(Laptop) and also have Files saved at my Network Storage at Work.
I want that both Folders have the same Files, If I create/delete or change an File in one Folder, the other Folder should get Updated when I use the BATCH.
It should use the newest Version on an Document.
So I tried it with ROBOCOPY Folder01 Folder02 /MIR /R:3 /W.20, it worked but only in one Way, from Folder01 to Folder02, so if I created an File in Folder02 and used the Batch, the File got deleted.
Then I tried to copy both Folders into one TEMP Folder and then copy the TEMP-Files to both Folders. I used
ROBOCOPY Folder01 TEMP /XO /E /R:3 /W:20
ROBOCOPY Folder02 TEMP /XO /E /R:3 /W:20
ROBOCOPY TEMP Folder01 /MIR /R:3 /W.20
ROBOCOPY TEMP Folder02 /MIR /R:3 /W.20
this was almost perfect, always the newest Document was used and everything was there, but when I delete a File from Folder01, which still exists in Folder02, it will come back next time I use my BATCH.
Sorry for my English
Greetings, Tobias

A: Try this solution provided by @Sachadee with Xcopy
:://Synchro.bat
:://SachaDee 2014
@echo off&cls
:: We set Folders to synchonized
set "Folders= C:\HackooTest E:\Backup\Folder1 E:\Backup\Folder2 E:\Backup\Folder3"

for %%a in (%Folders%) do (
  for %%b in (%Folders%) do (
     if not "%%a"=="%%b" (
        set "VAR%%a%%b=%%a %%b"
        )
    )
)
for /f "tokens=2,3 delims== " %%a in ('set VAR') Do (
    echo xcopy "%%a" "%%b" /E /D /C /Y /I
)
pause


text:
Q: casting an object with "as" still giving an error I have an object MyObject and I'm storing that in the session.
I write this:
MyObject TheObject = HttpContext.Current.Session["TheObjInSession"] as MyObject;

I'm getting error Object reference not set to an instance of an object Why? I thought that if you use as to cast and the cast produces an error then it just returns null and execution continues. How should I rewrite this line?
Thanks for your suggestions.
PS: The error is produced because I removed the enable session line [WebMethod(EnableSession = true)] I'll put the line back in but I want to make sure there are no exceptions in case anything goes wrong.

A: Chances are the Session is triggering it (it either doesn't exist or hasn't been established). This is common in handlers if you haven't marked the class to manage sessions.
Yes, you're right, as will attempt a cast or result in a null, but that's only assuming you're left-hand object is valid and has a value to attempt a cast on.
To explain it a bit more in depth:
HttpContext.Current.Session["Foo"]
HttpContext                         Probably fine
HttpContext.Current                 May not exist
HttpContext.Current.Session         Most likely cause (no access to session)

Which essentially makes referencing a key off the Session element impossible if Session itself doesn't exist.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Example for a block device on Windows I'm playing with the Posix stat() function on Linux, macOS and Windows and want to try it out with different devices, to see the outcome. Support for certain types, e.g. sockets and FIFOs is non-existent on Windows, but I'd like to check at least block and character devices. I found AUX (and a few others like that) to be character devices, however I cannot find any block device that's available on Windows by default. Can someone please suggest an example?

A: Windows, not being a POSIX OS, does not support stat. It has a similar function, _stat, which attempts to emulate the functionality.
However, even though Windows does have a notion of a block device, there is no S_IFBLK (block device) flag in the Windows implementation; if you look in stat.h you'll see that only the following mode flags are supported:
#define _S_IFMT   0xF000 // File type mask
#define _S_IFDIR  0x4000 // Directory
#define _S_IFCHR  0x2000 // Character special
#define _S_IFIFO  0x1000 // Pipe
#define _S_IFREG  0x8000 // Regular
#define _S_IREAD  0x0100 // Read permission, owner
#define _S_IWRITE 0x0080 // Write permission, owner
#define _S_IEXEC  0x0040 // Execute/search permission, owner

From this it can be concluded that what you're asking is impossible.
Indeed, _stat("C:") fails with ENOENT and _stat("\\\\.\\C:") fails with EINVAL.


text:
Q: Nested Pass by Reference I need to have a nested pass by reference.
EDITED TO INCLUDE ACTUAL CODE
Exact error is:

no matching function for call to 'CLItem::getValue(std::string*&)'

Complete error is:
App/CycCmdLine.cpp: In member function 'std::string CycCmdLine::getEnvironment()':
App/CycCmdLine.cpp:245: error: no matching function for call to 'CycCmdLine::getValue(const char [16], std::string&)'
./../CmdLine/CmdLine.h: In member function 'bool CmdLine::getValue(std::string, T&) [with T = std::string*]':
App/CycCmdLine.cpp:384:   instantiated from here
./../CmdLine/CmdLine.h:237: error: no matching function for call to 'CLItem::getValue(std::string*&)'
./../CmdLine/CmdLine.h:145: note: candidates are: bool CLItem::getValue(bool&)
./../CmdLine/CmdLine.h:146: note:                 bool CLItem::getValue(std::string&)
./../CmdLine/CmdLine.h:147: note:                 bool CLItem::getValue(long unsigned int&)
./../CmdLine/CmdLine.h:148: note:                 bool CLItem::getValue(std::list<std::basic_string<char, std::char_traits<char>, std::allocator<char> >, std::allocator<std::basic_string<char, std::char_traits<char>, std::allocator<char> > > >&)
./../CmdLine/CmdLine.h:149: note:                 bool CLItem::getValue(std::list<std::list<std::basic_string<char, std::char_traits<char>, std::allocator<char> >, std::allocator<std::basic_string<char, std::char_traits<char>, std::allocator<char> > > >, std::allocator<std::list<std::basic_string<char, std::char_traits<char>, std::allocator<char> >, std::allocator<std::basic_string<char, std::char_traits<char>, std::allocator<char> > > > > >&)

Updated code:
// initial caller
string CycCmdLine::getEnvironment()
{
    string sRet="";
    do
    {
        if(hasLogFile())
            {
                string sLogFile="";
                getValue(CYCCMD_CMDSTR_LOGFILE, sLogFile);
                sRet+="\n  -Profiler logfile: "+sLogFile;
            }
    }while(false);
    return(sRet);
}

// CmdLine::getValue function definition (this is in the header file, as a template should be)
template <typename T>
bool CmdLine::getValue(string sName, T &tValue)
{
    bool bRet=false;
    do
    {
    // try to get the iterator
    bool bExists;
    map<string, CLItem*>::iterator itItr;
    bExists=getMapElement(sName, itItr);

        // go ahead and return the value
        if(!itItr->second->getValue(tValue)) { break; }
        bRet=true;
    }while(false);
    return(bRet);
}

bool CLItem::getValue(string& sValue)
{
    bool bRet=false;
    do
    {
        // is this the correct type?
        if(!isType(CLType_STRING)) { break; }

        // return the value
        sValue=m_sValue;
        bRet=true;
    }while(false);
    return(bRet);
}

A: If we look into this part of the message
./../CmdLine/CmdLine.h: In member function 'bool CmdLine::getValue(std::string, T&) [with T = std::string*]':
App/CycCmdLine.cpp:384:   instantiated from here
./../CmdLine/CmdLine.h:237: error: no matching function for call to 'CLItem::getValue(std::string*&)'

It seems to say that atApp/CycCmdLine.cpp:384 you call getValue with T being a std::string*. This then causes the template to try to call a function that doesn't exist.
Start investigating this line 384!

A: You can reproduce that error with this code.
#include <string>

struct X
{
    void foo(std::string& n)
    {
    }

    void bar()
    {
       std::string* s;
       foo(s);
    }
};

prog.cpp: In member function 'void X::bar()':
prog.cpp:12: error: no matching function for call to 'X::foo(std::string*&)'
prog.cpp:5: note: candidates are: void X::foo(std::string&)

The suggested reference symbol is not very significant. You are indeed trying to pass a pointer where a value is expected, and the compiler is guessing what a suitable function for that call might look like. (It probably means that you are passing a lvalue, so the function might take it by reference.)
Also note that it lists candidates, functions by the same name but with unsuitable parameter types.

Now that you've posted real code, perhaps check what the template type is in your faulty instantiation (the error message should mention that too).

Now that you have also posted error messages:
App/CycCmdLine.cpp: In member function 'std::string CycCmdLine::getEnvironment()':
App/CycCmdLine.cpp:245: error: no matching function for call to 'CycCmdLine::getValue(const char [16], std::string&)'

This is the first error. Translation: the class CycCmdLine doesn't have a member function getValue (nor is there a global function by this name). A function by that name is a member of CmdLine.
./../CmdLine/CmdLine.h: In member function 'bool CmdLine::getValue(std::string, T&) [with T = std::string*]':
App/CycCmdLine.cpp:384:   instantiated from here
./../CmdLine/CmdLine.h:237: error: no matching function for call to 'CLItem::getValue(std::string*&)'

This is the second error, the one you are asking about. You are passing a pointer-to-string on line 384 of CycCmdLine.cpp (which is in a different place than you thought).


text:
Q: Clean callbacks in python In nodeJS using lambda expressions you can create very clean callback code but defining and returning a function at the same time. Like so:
events.on("loaded", ()=>{
  let x=1;
  console.log("loaded!", x+2);
});

If I were to try to accomplish the same thing in python, I would need to define the function before using it in the callback:
def l():
  x=1
  print("loaded!", x+2)

events.on("loaded", l)

By my eye is is a lot harder to read.
My question is: is there a clean way of writing a multi-line function in python for callbacks that can be used in-line?
Note: I cannot use a lambda expressions as I need multi-line functions.
Please alert me if there is already an answer to this question that I wasn't able to find. I will happly remove this myself if that is the case.


text:
Q: Nullpointer Exception on reading data using google spreadsheet oauth in Java Getting nullpointer exception on trying to read data using google spreadsheet API in Java. Created a spreadsheet and enabled Google Spreadsheet API. Also downloaded client_services.json file and added inside src/resources/ path. Still getting nullpointer exception on running.
package main.java;
import com.google.api.client.auth.oauth2.Credential;
import com.google.api.client.extensions.java6.auth.oauth2.AuthorizationCodeInstalledApp;
import com.google.api.client.extensions.jetty.auth.oauth2.LocalServerReceiver;
import com.google.api.client.googleapis.auth.oauth2.GoogleAuthorizationCodeFlow;
import com.google.api.client.googleapis.auth.oauth2.GoogleClientSecrets;
import com.google.api.client.googleapis.javanet.GoogleNetHttpTransport;
import com.google.api.client.http.HttpTransport;
import com.google.api.client.json.jackson2.JacksonFactory;
import com.google.api.client.json.JsonFactory;
import com.google.api.client.util.store.FileDataStoreFactory;
import com.google.api.services.sheets.v4.SheetsScopes;
import com.google.api.services.sheets.v4.model.*;
import com.google.api.services.sheets.v4.Sheets;

import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Arrays;
import java.util.List;

public class Quickstart {
    /** Application name. */
    private static final String APPLICATION_NAME =
        "Google Sheets API Java Quickstart";

    /** Directory to store user credentials for this application. */
    private static final java.io.File DATA_STORE_DIR = new java.io.File(
        System.getProperty("user.home"), ".credentials/sheets.googleapis.com-java-quickstart");

    /** Global instance of the {@link FileDataStoreFactory}. */
    private static FileDataStoreFactory DATA_STORE_FACTORY;

    /** Global instance of the JSON factory. */
    private static final JsonFactory JSON_FACTORY =
        JacksonFactory.getDefaultInstance();

    /** Global instance of the HTTP transport. */
    private static HttpTransport HTTP_TRANSPORT;

    /** Global instance of the scopes required by this quickstart.
     *
     * If modifying these scopes, delete your previously saved credentials
     * at ~/.credentials/sheets.googleapis.com-java-quickstart
     */
    private static final List<String> SCOPES =
        Arrays.asList(SheetsScopes.SPREADSHEETS_READONLY);

    static {
        try {
            HTTP_TRANSPORT = GoogleNetHttpTransport.newTrustedTransport();
            DATA_STORE_FACTORY = new FileDataStoreFactory(DATA_STORE_DIR);
        } catch (Throwable t) {
            t.printStackTrace();
            System.exit(1);
        }
    }

    /**
     * Creates an authorized Credential object.
     * @return an authorized Credential object.
     * @throws IOException
     */
    public static Credential authorize() throws IOException {
        // Load client secrets.
        InputStream in =
            Quickstart.class.getResourceAsStream("//client_secret.json");

        GoogleClientSecrets clientSecrets =
            GoogleClientSecrets.load(JSON_FACTORY, new InputStreamReader(in));

        // Build flow and trigger user authorization request.
        GoogleAuthorizationCodeFlow flow =
                new GoogleAuthorizationCodeFlow.Builder(
                        HTTP_TRANSPORT, JSON_FACTORY, clientSecrets, SCOPES)
                .setDataStoreFactory(DATA_STORE_FACTORY)
                .setAccessType("offline")
                .build();
        Credential credential = new AuthorizationCodeInstalledApp(
            flow, new LocalServerReceiver()).authorize("user");
        System.out.println(
                "Credentials saved to " + DATA_STORE_DIR.getAbsolutePath());
        return credential;

    }

    /**
     * Build and return an authorized Sheets API client service.
     * @return an authorized Sheets API client service
     * @throws IOException
     */
    public static Sheets getSheetsService() throws IOException {
        Credential credential = authorize();
        return new Sheets.Builder(HTTP_TRANSPORT, JSON_FACTORY, credential)
                .setApplicationName(APPLICATION_NAME)
                .build();
    }

    public static void main(String[] args) throws IOException {
        // Build a new authorized API client service.
        Sheets service = getSheetsService();

        // https://docs.google.com/spreadsheets/d/1BxiMVs0XRA5nFMdKvBdBZjgmUUqptlbs74OgvE2upms/edit
        String spreadsheetId = "12tEQZqb-12N-a8hF-4TG-1E0qqJuhrYTl5CYAeIg0Sc";
        String range = "Sheet1!A1:E";
        ValueRange response = service.spreadsheets().values()
            .get(spreadsheetId, range)
            .execute();
        List<List<Object>> values = response.getValues();
        if (values == null || values.size() == 0) {
            System.out.println("No data found.");
        } else {
          for (List row : values) {
            // Print columns A and E, which correspond to indices 0 and 4.
            System.out.printf("%s, %s\n", row.get(0), row.get(4));
          }
        }
    }

}

Also, added the "client_secret.json" file inside src/main/resources/ path.
This is the trace. Want to know why it is showing as null even after client_secret file has data. Want to know the proper reason why it is showing as null even if client_secret has proper data. Also it has been added in the right path.
    > java.lang.NullPointerException
    at java.io.Reader.<init>(Reader.java:78)
    at java.io.InputStreamReader.<init>(InputStreamReader.java:72)
    at main.java.Quickstart.authorize(Quickstart.java:73)
    at main.java.Quickstart.getSheetsService(Quickstart.java:102)
    at main.java.Quickstart.main(Quickstart.java:110)
Exception in thread "main" com.google.api.client.googleapis.json.GoogleJsonResponseException: 403 Forbidden
{
  "code" : 403,
  "errors" : [ {
    "domain" : "global",
    "message" : "The request is missing a valid API key.",
    "reason" : "forbidden"
  } ],
  "message" : "The request is missing a valid API key.",
  "status" : "PERMISSION_DENIED"
}
    at com.google.api.client.googleapis.json.GoogleJsonResponseException.from(GoogleJsonResponseException.java:146)
    at com.google.api.client.googleapis.services.json.AbstractGoogleJsonClientRequest.newExceptionOnError(AbstractGoogleJsonClientRequest.java:113)
    at com.google.api.client.googleapis.services.json.AbstractGoogleJsonClientRequest.newExceptionOnError(AbstractGoogleJsonClientRequest.java:40)
    at com.google.api.client.googleapis.services.AbstractGoogleClientRequest$1.interceptResponse(AbstractGoogleClientRequest.java:321)
    at com.google.api.client.http.HttpRequest.execute(HttpRequest.java:1065)
    at com.google.api.client.googleapis.services.AbstractGoogleClientRequest.executeUnparsed(AbstractGoogleClientRequest.java:419)
    at com.google.api.client.googleapis.services.AbstractGoogleClientRequest.executeUnparsed(AbstractGoogleClientRequest.java:352)
    at com.google.api.client.googleapis.services.AbstractGoogleClientRequest.execute(AbstractGoogleClientRequest.java:469)
    at main.java.Quickstart.main(Quickstart.java:118)


text:
Q: Win32Exception Access Denied So im trying to run python code in C#. But when I'm trying to execute the command I get a error message:
System.ComponentModel.Win32Exception: 'Access Denied'

Code:
private void run_cmd(string cmd, int args)
        {
            ProcessStartInfo start = new ProcessStartInfo();
            start.FileName = "C://Users//user//AppData//Local//Microsoft//WindowsApps//python.exe";
            start.Arguments = string.Format("{0} {1}", cmd, args);
            start.UseShellExecute = false;
            start.RedirectStandardOutput = true;
            using (Process process = Process.Start(start))
            {
                using (StreamReader reader = process.StandardOutput)
                {
                    string result = reader.ReadToEnd();
                    Console.Write(result);
                }
            }
        }

The error is happening at:
using (Process process = Process.Start(start))

A: Process.Start Method is not supported in UWP apps. To run the exe file from your UWP app, I'd suggest you use FullTrustProcessLauncher Class.
First, you need to copy the exe file and save it in the UWP app package, for example, the Assets folder. Then please go to the Manifest file and add the runFullTrust restricted capability.(App capability). Next, add the reference of Windows Desktop Extensions for the UWP project. At last, you could call await FullTrustProcessLauncher.LaunchFullTrustProcessForCurrentAppAsync(); to launch the exe file from your app.


text:
Q: ToList() responsibility for caller or callee? Have a look at the following example:
public IEnumerable<LogEntry> GetLogs(string groupName)
{
    return _Db.Logs.Where(l => l.groupName == groupName);
}

Should I actually add ToList() before returning this method? Or is this the responsibility for the caller?

A: If you will add ToList() before returning - it will cause full enumeration of your enumerable.
If you will return IEnumerable instead of converting it to list - then it will be enumerated by caller on the first use of it.
So if your data size in _Db.logs is large - possibly it's better to enumerate it on caller's size as caller will not nessesary enumerate whole set of data (depending on what caller plans to do with it).

A: Converting your IEnumerable to a List would rob you of all the benefits of having an IEnumerable, mainly lazy evaluation. So, if your caller really wants to create a List, let him, but don't force him to.

A: If you want to allow people choose when to evaluate the query, return IEnumerable. If you specify IList as return type, you must evaluate the expression by calling ToArray() or ToList().

A: I suggest use this method.
You should pass what you want and don't will loss control of data acquisition time.
public List<LogEntry> GetLogs(Expression<Predicate<LogEntry>> where)
{
    return _Db.Logs.Where(where).ToList();
}

}


text:
Q: What does this javascript code do? y = x?0:0x80

From googling the colon seems to be a ternary operator.

A: That's right. (The correct name is the conditional operator. It is a ternary operator, in that it takes three operands, but it's commonly misnamed the ternary operator because it's the only JavaScript operator that does so.)
The code is roughly equivalent to this:
var y;
if (x) {
    y = 0;
}
else {
    y = 0x80;
}

A: It is a ternary operator. It assigns 0 to y if x is true, otherwise it assigns 0x80.

A: Yes, it's a ternary operation, assigning y the value of 0 if x is true or 0x80 otherwise.

A: It translates to:
if(x) then
    y=0
else
    y=0x80

But is much shorter.

A: Yes to all of the above, but it is also checking for the existence of x. If x doesn't exist or is null, y = 0x80.


text:
Q: Invalid Characters error in LateX question marks all over the document The power energy was shut down while I was working and when I opened my file there were lots of question mark. My whole work is in here and lost it! What do I do?
Attempt:
I've tried to delete .aux file and nothing has changed. Here is part of my log file:
This is pdfTeX, Version 3.14159265-2.6-1.40.17 (MiKTeX 2.9) (preloaded format=pdflatex 2016.8.17)  19 DEC 2016 14:26
entering extended mode
**"./Contas e Dúvidas.tex"
("Contas e Dúvidas.tex"
LaTeX2e <2016/03/31> patch level 3
Babel <3.9r> and hyphenation patterns for 75 language(s) loaded.

! LaTeX Error: Missing \begin{document}.

See the LaTeX manual or LaTeX Companion for explanation.
Type  H <return>  for immediate help.
 ...

l.1 ï
     ¿½ï¿½  \�  q  u�  �2  t�  �.  s�  ��  2�  �3  a�...

You're in trouble here.  Try typing  <return>  to proceed.
If that doesn't work, type  X <return>  to quit.

Missing character: There is no ï in font nullfont!
Missing character: There is no ¿ in font nullfont!
Missing character: There is no ½ in font nullfont!
Missing character: There is no ï in font nullfont!
Missing character: There is no ¿ in font nullfont!
Missing character: There is no ½ in font nullfont!
! Text line contains an invalid character.
l.1 ��
            \�  q  u�  �2  t�  �.  s�  ��  2�  �3  a�...
A funny symbol that I can't read has just been input.
Continue, and I'll forget that it ever happened.

! Text line contains an invalid character.
l.1 ��
            \�  q  u�  �2  t�  �.  s�  ��  2�  �3  a�...
A funny symbol that I can't read has just been input.
Continue, and I'll forget that it ever happened.

! Undefined control sequence.
l.1 ��  \ï
              ¿½  q  u�  �2  t�  �.  s�  ��  2�  �3  a�...

My input file:
 ��

A: Mostly your output consists of terminal output showing �  assuming a latin1 (not UTF) terminal encoding that represents the three bytes
EF BF BD

which are the three bytes of the Unicode UTF-8 encoding of the character U+FFFD which is REPLACEMENT CHARACTER ie the character a Unicode system substitutes when it is confused and can not decode the input.
pdftex would not have done this, however your editing software might have, if it was given latin 1 (iso-8859-1) encoded data but told to read it as UTF-8.
You need to show some of your input file.


text:
Q: Lobachevsky's Formula for Integrals If the function $f:\mathbb{R}\to \mathbb{R}$ satisfies $f(x+\pi)=f(\pi-x)=f(x), \forall x \in \mathbb{R}$ then
$$\int_0^\infty f(x)\frac{\sin x }{x} \mathrm{d}x = \int _0^\frac\pi2 f(x) \mathrm{d}x$$
How can I prove this equality?

A: Indeed, let
$$I=\int_0^\infty f(x)\frac{\sin x}{x}dx$$
By asumption $f$ is even and $\pi$-periodic. Moreover,
$$\eqalign{
2I&=\lim_{n\to\infty}\int_{-n\pi}^{(n+1)\pi}\frac{\sin(x)}{x}f(x)dx
=\lim_{n\to\infty}\sum_{k=-n}^n\int_{k\pi}^{(k+1)\pi}\frac{\sin(x)}{x}f(x)dx\cr
&=\lim_{n\to\infty}\sum_{k=-n}^n\int_{0}^{ \pi}\frac{(-1)^k}{x+k\pi}\sin(x)f(x)dx\cr
&=\lim_{n\to\infty}\int_{0}^{ \pi}\left(\sum_{k=-n}^n\frac{(-1)^k}{x+k\pi}\right)\sin(x)f(x)dx\cr
&=\lim_{n\to\infty}\int_{0}^{ \pi}U_n(x)f(x)dx\cr
}
$$
with
$$
U_n(x) =\sin(x)\sum_{k=-n}^n\frac{(-1)^k}{x+k\pi}
$$
But it is well-known that $\lim_{n\to+\infty}U_n(x)=1$ for every $x\in(0,\pi)$ and that the sequence $\{U_n\}$ is bounded on $[0,\pi]$, so, by the Dominated Convergence Theorem, we conclude that
$$
2I=\int_0^\pi f(x)dx=2\int_0^{\pi/2}f(x)dx.
$$
and the desired conclusion follows.
Remark. Concerning the statements about the sequence $\{U_n\}$ these are well-known, and a simple proof can be found here. Indeed,
consider $\alpha\in(0,1)$, and let $f_\alpha$ be the $2\pi$-periodic function that coincides  with $x\mapsto e^{i\alpha x}$ on the interval $(-\pi,\pi)$. It is easy to check that the exponential Fourier coefficients of $f_\alpha$  are
given by
$$
C_n(f_\alpha)=\frac{1}{2\pi}\int_{-\pi}^{\pi}f_\alpha(x)e^{-inx}dx=\sin(\alpha\pi)\frac{(-1)^n}{\alpha \pi-n\pi}
$$
and since $f_\alpha$ is continuously differentiable on $(-\pi,\pi)$ the Fourier series of $f_\alpha$ converges to $f_\alpha$ on this interval:
$$
\forall\,x\in(-\pi,\pi),\quad e^{i\alpha x}=\lim_{n\to\infty}\sum_{k=-n}^{n}C_k(f_\alpha)e^{ikx}=\lim_{n\to\infty}\sum_{k=-n}^{n}\frac{(-1)^k\sin(\alpha\pi)}{\alpha\pi- k\pi}e^{ikx}
$$
Taking $x=0$, we get
$$
1=\lim_{n\to\infty}U_n(\alpha\pi)
$$


text:
Q: Generate xml by changeset Is it possible to generate an xml file from the resulting change set in TFS? I need to query TFS and get a list of the change sets within a date range. I then must transform the TFS data into an xml file.

A: Query changesets within a date range is easy. There are several ways to achieve this:

*

*In Source Control Explorer, right click the file, and choose Find--Find changesets.

*Install Team Foundation Sidekicks, query the changesets under History sidekick.

*Use History command.

*Use API.

But there is not a default way to generate the changesets list to a xml file. Alternative way will be:

*

*Save the changesets list to a .csv file in Team Foundation Sidekicks, then convert .csv file to .xml file.

*Use TFS API to get changesets list and transform it to a .xml file.


text:
Q: phonegap facebook connect integration issue I am trying to integrate my phonegap application with facebook through facebook connect plugin. I followed the instructions here since git wasn't working for me but I think I would end up with the exact same setup either way.
When I run the following code after doing FB.init() using my app ID, I get an alert saying "Cordova Facebook Connect Plugin failed on auth.status"
console.log('Debug 1');
var params = {
    method: 'feed',
    name: 'Facebook Dialogs',
    link: 'https://developers.facebook.com/docs/reference/dialogs/',
    picture: 'http://fbrell.com/f8.jpg',
    caption: 'Reference Documentation',
    description: 'Dialogs provide a simple, consistent interface for applications to interface with users.'
  };
console.log(params);
FB.ui(params, function(obj) { console.log(obj);});

While logcat output shows this:
09-03 21:29:00.230: D/CordovaLog(21824): Error: Status=2 Message=Class not found
09-03 21:29:00.230: D/CordovaLog(21824): file:///android_asset/www/cordova-2.0.0.js: Line 938 : Error: Status=2 Message=Class not found
09-03 21:29:00.230: I/Web Console(21824): Error: Status=2 Message=Class not found at file:///android_asset/www/cordova-2.0.0.js:938

I don't know if this is an issue with facebook authentication of my app or some code issue. I have generated an Android Hash Key using the keytool and submitted it to facebook developer page. When I export my android project as android application in eclipse using the same keystore, it doesn't show me the alias I used with keytool (same keystore). So I created a new alias with the same alias name and password and then install the apk on my phone. What seems to be the issue here?

A: Well there were many problems. First of all, and most confusing was that the following line is not to be placed in plugins.xml but in config.xml instead.
<plugin name="com.phonegap.facebook.Connect" value="com.phonegap.facebook.ConnectPlugin" />

After that, I had not entered the correct hash key at facebook developer page. Since you don't want to export an apk through a keystore every time you need to test your app, you should just run the debugging apk generated by eclipse (Run as > Android application) and attempt FB.login(). Facebook will give you an error that your key is 'xxxxxx' and it does not match the keys listed at your app page. Note 'xxxxxxx' down and enter it on the facebook app page.
Others were my own mistakes of not including the scripts in the correct order. I had not followed the example carefully. Be sure you get the example/Simple/index.html working first before you code for your own application. Hope it helps...


text:
Q: Is there any way to insert data in sqllite table sequentially? I want to insert some data in SQLite table with one column for keeping string values and other column for keeping sequence number.
SQLite documentation says that autoincrement does not guarantees the sequential insertion.
And i do not want to keep track of previously inserted sequence number.
Is there any way for storing data sequentially, without keeping track of previously inserted row?

A: The short answer is that you're right that the autoincrement documentation makes it clear that INTEGER PRIMARY KEY AUTOINCREMENT will be constantly increasing, though as you point out you using, not necessarily sequentially so. So you obviously have to either modify your code so it's not contingent on sequential values (which is probably the right course of action), or you have to maintain your own sequential identifier yourself. I'm sure that's not the answer you're looking for, but I think it's the practical reality of the situation.

A: Short answer: Stop worrying about gaps in AUTOINCREMENT id sequences. They are inevitable when dealing with transactional databases.
Long answer:
SQLite cannot guarantee that AUTOINCREMENT will always increase by one, and reason for this is transactions.
Say, you have 2 database connections that started 2 parallel transactions almost at the same time. First one acquired some AUTOINCREMENT id and it becomes previously used value +1. One tick later, second transaction acquired next id, which is now +2. Now imagine that first transaction rolls back for some reason (encounters some error, code decided to abort it, program crashed, etc.). After that, second transaction will commit id +2, creating a gap in id numbering.
Now, what if number of such parallel transactions is higher than 2? You cannot predict, and you also cannot tell currently running transactions to reuse ids that were not used for any reason.

A: If you insert data sequentially into your SQLite database, they will be stored sequentially.
From the Documentation: the automatically generated ROWIDs are guaranteed to be monotonically increasing.
So, for example, if you wanted to have a table for Person, then you could use the following command to create table with autoincrement.
CREATE table PERSON (personID integer PRIMARY KEY AUTOINCREMENT, personName string)
Link: http://www.sqlite.org/autoinc.html


text:
Q: Countable dense set and basis in product spaces $\{0,1\}^{\mathbb{N}}$, $[0,1]^{\mathbb{N}}$ and $\mathbb{R}^{\mathbb{N}}$ For $\mathbb{R}^{\mathbb{N}}$ and $[0,1]^{\mathbb{N}}$ I know a set of sequences that are constant for almost all $n$ is dense, but how to make it countable? Changing the condition to equal $0$ for all $n > N$ for some $N$ doesn't make it countable. How to define other set? What would be the countable basis? What about $\{0,1\}^{\mathbb{N}}$?

A: For the first two use members of $\Bbb Q^{\Bbb N}$ and $(\Bbb Q\cap[0,1])^{\Bbb N}$ that are $0$ for almost all $n$. For the last just use sequences that are $0$ for almost all $n$.


text:
Q: Reset specific tables with clean data I am doing a test that updates my database each time I run it
And I cannot do the test again with the updated values
I am recreating the WHOLE database with:
postgres=# drop database mydb;
DROP DATABASE
postgres=# CREATE DATABASE mydb WITH TEMPLATE mycleandb;
CREATE DATABASE

This takes a while
Is there any way I can update just the tables that I changed with tables from mycleandb?

A: Transactions
You haven't mentioned what your programming language or framework are. Many of them have built in test mechanisms that take care of this sort of thing. If you are not using one of them, what you can do is to start a transaction with each test setup. Then roll it back when you tear down the test.
BEGIN;
 ...
 INSERT ...
 SELECT ...
 DELETE ...
ROLLBACK;

Rollback, as the name suggests reverses all that has been done to the database so that it remains at the original condition.
There is one small problem with this approach though, you can't do integration tests where you intentionally enter incorrect values and cause a query to fail integrity tests. If you do that the transaction ends and no new statements can be executed until rolled back.
pg_dump/pg_restore
it's possible to use the -t option of pg_dump to dump and then restore one or a few tables. This maybe the next best option when transactions are not practical.
Non Durable Settings / Ramdisk
If both above options are inapplicable please see this answer: https://stackoverflow.com/a/37221418/267540
It's on a question about django testing but there's very little django specific stuff on that. However coincidentally django's rather excellent test framework relies on the begin/update/rollback mechanis described above by default.

A: Test inside a transaction:
begin;
update t
set a = 1;

Check the results and then:
rollback;

It will be back to a clean state;


text:
Q: Is it possible to add SSL support after a build is up and running? I recently tried to upgrade my postgresql from 9.0 to 9.1.
I got to a point where I was able to get both builds to run concurrently (on different ports).
Then I tried copying some settings from the old config file into the new one, and one of the settings was setting SSL to enabled. This by itself is alright, but unfortunately, back when I first built the build, I forgot to configure it with SSL. And as such, I get the following error when I try to start up the server:  FATAL:  SSL is not supported by this build.
So, can I add SSL support to an already built and installed Postgresql? Or, am I going to have to delete stuff, reconfigure the build, remake it and finally re-install it?
Also, could someone tell me how to set it up correctly. For example, at the moment, if I use the psql command in the terminal, it uses the old psql (i.e. the 9.0's psql), and if I want to use of any the new commands (i.e. 9.1's commands), I have to write out a full directory, like this: /usr/local/pgsql/bin/postgres -D /var/lib/postgresql/9.1/main -p 5433. It would also be nice to know how to have postgresql start up on boot time.
Thanks a lot for the help, I know my questions are a bit simplistic, but I am still getting used to linux development and administration.

A: In order to add SSL support to your installation, you need to rerun the configure, make, make install sequence with the appropriate options.  But you don't have to delete anything.  Just install the new binaries over the old ones and restart the server.


text:
Q: Writing a file using c program in the format of table I want to write a file in the format of table using c program.
I am using fputs to write the file. My file looks like :
    [sl] [Name] [School] [add]
    1 ABC DEF Dav India
    2 XYZ LLL USA

But, I want output file to look like :
    [sl]    [name]     [school]    [add]
     1      ABC DEF     DAV        INDIA
     2      XYZ         LLL        USA

I want to know is there something like length specifier in fputs like in printf so that I can change format of the file.

A: I think what you are looking for is fprintf. Find out more about fprintf here.
It is used exactly the same way as printf, except it writes to a file.
EDIT
If your string is stored in different variables, then use fprintf as follows :
fprintf(fp,"%-15s %-15s %-15s %-15s", "string 1", "string 2", "string 3", "string 4");

The number 15 is the fixed length that the string will use (You can change this based on the maximum string length you have or some other preference). The minus sign is for left Justified string.

A: As Kyuubi specified, you will want to use fprintf instead of fputs it will cut down on the amount of code needed. The fprintf will write your data to a file pursuant to a format string. Since your data will be string data, you will write it out in pieces specifying %s in the format string for each piece. Take for example your ABC DEF words. You can use fprintf to write the string literals as follows:
fprintf (fp, "   %s    %s\n", "ABC", "DEF");

You can also specify the minimum field width for each word you write by specifying and integer between % and s, such as %10s to write '-------ABC' out with a minimum width of 10 characters. You can also place a - sign before the number to left align the string. For example %-10s to output 'ABC-------'. (the dashes are really spaces, just for illustration) The can help you separate the information you want into table form without writing out a varying number of spaces for each different fprintf call.
See 'man 3 fprintf` for all the options. There are literally 1000s of examples on the web to help.


text:
Q: Why can a variable's dependance be neglected in a function? In this derivation of the 2nd order Runge-Kutta method it's said that from a certain point $y$'s dependence on $t$ in $f(t,y)$ will be neglected. Why is this possible?
Source: http://www.math.iit.edu/~fass/478578_Chapter_3.pdf

A: $\newcommand{\by}{\mathbf{y}}$
This is slightly wrong, as there are indeed terms missing in the Taylor expansion. These terms follow the pattern of the $\by$-derivatives, so that no information is lost, but ...
They should have just said that to derive the order conditions resp. the method of the highest possible order for the number of stages they only consider autonomous systems $\by'=f(\by)$. One has to take care that $\by$ is a vector and $f$ is vector valued, so that $f'(\by)$ is a matrix, the Jacobi matrix. Higher derivatives then are tensors, vector-valued symmetric multi-linear forms.
This is general enough, as you can transform any non-autonomous system into an artificially autonomous one as
$$
\frac{d}{dt}\pmatrix{t\\\by}=F((t,\by))=\pmatrix{1\\f(t,\by)}
$$
where now the state vector has the time $t$ as additional component.


text:
Q: No Activity found to handle Intent { act=android.settings.NOTIFICATION_POLICY_ACCESS_SETTINGS } I m using simple code as below to take permission for changing ringer during DND. App is being tested on Android 6.0. But it is crashing with below log
android.content.ActivityNotFoundException: No Activity found to handle Intent { act=android.settings.NOTIFICATION_POLICY_ACCESS_SETTINGS }

Here is my code:
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
    if (!notificationManager.isNotificationPolicyAccessGranted()) {
        startActivity(new Intent(ACTION_NOTIFICATION_POLICY_ACCESS_SETTINGS));
    }
}

Which I m calling on button click.

A: try this code snippet it worked for me
and yes don't forget to add permission in manifest ...
<uses-permission android:name="android.permission.ACCESS_NOTIFICATION_POLICY"/>

A: if (Build.VERSION.SDK_INT > Build.VERSION_CODES.M) {
    if (!notificationManager.isNotificationPolicyAccessGranted()) {
        startActivity(new Intent(ACTION_NOTIFICATION_POLICY_ACCESS_SETTINGS));
    }
}

A: Just surround with try n catch.
Worked for me
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M
                    && !notificationManager.isNotificationPolicyAccessGranted()) {
    try {
        Intent intent = new Intent(Settings.ACTION_NOTIFICATION_POLICY_ACCESS_SETTINGS);
                            startActivity(intent);
                        }catch (Exception et){
                            //tell user something went wrong
                        }
    }


text:
Q: rb_class_new_instance raises "ArgumentError: wrong type" - why? From my Ruby C Extension I wanted to create a new Geom::Vector3d instance from the Google SketchUp Ruby API: https://developers.google.com/sketchup/docs/ourdoc/vector3d
My initial code was this:
static inline VALUE
vector_to_sketchup( Point3d vector )
{
  VALUE skp_vector, args[3];

  args[0] = rb_float_new( vector.x );
  args[1] = rb_float_new( vector.y );
  args[2] = rb_float_new( vector.z );

  skp_vector = rb_class_new_instance( 3, args, cVector3d );
}

This however raised an error:
Error: #<ArgumentError: wrong type - expected Sketchup::Vector3d>

Instead I had to call the ruby new method - like so:
static inline VALUE
vector_to_sketchup( Point3d vector )
{
  VALUE skp_vector;

  skp_vector = rb_funcall( cVector3d, sNew, 3,
    rb_float_new( vector.x ),
    rb_float_new( vector.y ),
    rb_float_new( vector.z )
  );

  return skp_vector;
}

I ran into the same problem with Geom::Point3d and Sketchup::Color.
rb_class_new_instance is the preferred way to create a new instance in Ruby C, right?
Anyone got any idea why I needed to call new? Some oddity with how the class was defined in SketchUp?

A: After communicating with the developers of Google SketchUp I have found the cause of this.
SketchUp makes use of Data_Wrap_Struct to link their C classes with the Ruby classes. But they use an old method of allocating the data - which is within the #new method.
In Ruby 1.8 you use rb_define_alloc_func() to do the allocation and you never mess around with #new. Ruby (1.6 and 1.8) defines #new to call rb_class_new_instance().
Since I used rb_class_new_instance() on SketchUp's old style classes the objects where not created properly, the allocation function was bypassed and never triggered. The error I got came from SketchUp, not Ruby.
So the answer is, you can use rb_class_new_instance() to create new instances of classes provided they haven't overloaded the #new method to do any initializations. Before Ruby 1.6 this was common for Ruby C classes if they needed to allocate data, but as of 1.8 it should be done with rb_define_alloc_func(). (Matz says so here: https://web.archive.org/web/20131003102349/http://www.justskins.com/forums/the-new-allocation-scheme-132572.html#post437362 )
You can see the differences between Ruby 1.6 style and 1.8 style in this post: https://web.archive.org/web/20131003102349/http://www.justskins.com/forums/the-new-allocation-scheme-132572.html#post444948


text:
Q: PDFsharp and MigraDoc: How to render MigraDoc horizontal chart on PDFsharp page?
I have made a PDF document in MigraDoc containing all the details I need in my generated PDF file. The generated PDF page has two colored sections, cyan and white.
The cyan section contains horizontal charts.
I used another PDFsharp document and colored it in two parts, using the gfx of the PdfDocument page. Code below :
//---Color on page--------
gfx.DrawRectangle(new XSolidBrush(XColor.FromArgb(98, 183, 229)),    columnRect);
//---render migraddoc ---------------------------
MigraDoc.Rendering.DocumentRenderer docRenderer = new DocumentRenderer(document);
docRenderer.PrepareDocument();
//--- Render migradoc objects---------------------------------------------
docRenderer.RenderObject(gfx, XUnit.FromCentimeter(0.7), XUnit.FromCentimeter(0.5), "6cm", name);columnRect);
//-- above name is the migradoc paragraph object.
//-- ***rendering charts***
docRenderer.RenderObject(gfx, XUnit.FromCentimeter(1.2), XUnit.FromCentimeter(19), "0.6cm", chart);

The rendered charts are getting overlapped one above the other
 //--code for the chart
Chart chart = new Chart(ChartType.Bar2D);
chart.Width = Unit.FromPoint(100);
chart.Height = Unit.FromPoint(2);
chart.FillFormat.Color = Colors.White;

Series series = chart.SeriesCollection.AddSeries();

series.Add(new double[] {45, 20, 11, 23});
series.HasDataLabel = true;

XSeries xseries = chart.XValues.AddXSeries();
xseries.Add("A", "B", "C", "D");
document.LastSection.Add(chart);

Is there any way to render the series of the horizontal bars in proper format at the given coordinates?


text:
Q: react native android app to react native web app I am trying to convert my react-native android app into a react-native web app. While doing this I got an error in @react-native-picker\picker.
Failed to compile
./node_modules/@react-native-picker/picker/js/Picker.web.js
SyntaxError: C:\Users\User\Desktop\react-native\TestProject\node_modules@react-native-picker\picker\js\Picker.web.js: Unexpected token (9:12)
   7 |
   8 | import React from 'react';
>  9 | import type {
     |             ^
  10 |   ViewStyleProp,
  11 |   TextStyleProp,
  12 | } from 'react-native/Libraries/StyleSheet/StyleSheet';

how can i resolve this issue?

A: It looks like Picker.web.js contains code written with Flow so you'll need to make sure your web project has support for Flow enabled.

Since you are using Create React App, you'll need to customize the configuration to enable Babel for packages inside of node_modules:

*

*Install customize-cra and react-app-rewired:

npm install --save-dev customize-cra react-app-rewired

*Follow the steps to complete the installation of react-app-rewired: https://github.com/timarney/react-app-rewired#how-to-rewire-your-create-react-app-project

*Configure Babel include for node_modules/@react-native-picker/picker:
// config-overrides.js

const path = require('path');
const {
    babelInclude,
    override,
} = require('customize-cra');

module.exports = override(
    babelInclude([
        path.resolve('src'),
        path.resolve(__dirname, 'node_modules/@react-native-picker/picker'),
    ]),
);


text:
Q: ssmtp issue sending mail from command line and php I am having an issue with the following statement in the command line:
echo 'Subject: test' | /usr/sbin/sendmail -v <myemail>@gmail.com

it is returning the following:
# echo 'Subject: test' | /usr/sbin/sendmail -v <email>@gmail.com
[<-] 220 mail.xen.prgmr.com ESMTP Postfix
[->] HELO host.xen.prgmr.com
[<-] 250 mail.xen.prgmr.com
[->] MAIL FROM:<root@hostname.com>
[<-] 250 2.1.0 Ok
[->] RCPT TO:<<email>@gmail.com>
[<-] 554 5.7.1 <<email>@gmail.com>: Relay access denied
sendmail: RCPT TO:<<email>@gmail.com> (554 5.7.1 <<email>@gmail.com>: Relay access denied)

Any clues on how to configure this to actually send out would be greatly appreciated.  Here is some of the /var/log/mail.log
Jun 11 02:28:47 host sendmail[29388]: alias database /etc/mail/aliases rebuilt by root
Jun 11 02:28:47 host sendmail[29388]: /etc/mail/aliases: 12 aliases, longest 10 bytes, 134 bytes total
Jun 11 02:28:48 host sm-mta[29446]: starting daemon (8.14.4): SMTP+queueing@00:10:00
Jun 11 02:29:54 host sendmail[30867]: alias database /etc/mail/aliases rebuilt by root
Jun 11 02:29:54 host sendmail[30867]: /etc/mail/aliases: 12 aliases, longest 10 bytes, 134 bytes total
Jun 11 02:29:57 host sm-mta[29446]: restarting /usr/sbin/sendmail-mta due to signal
Jun 11 02:29:57 host sm-mta[30913]: starting daemon (8.14.4): SMTP+queueing@00:10:00
Jun 11 02:33:09 host sendmail[31513]: NOQUEUE: SYSERR(root): /etc/mail/sendmail.cf: line 6: invalid argument to V line: "ERSIONID(\001Id: startt"
Jun 11 02:33:09 host sendmail[31513]: NOQUEUE: SYSERR(root): /etc/mail/sendmail.cf: line 7: invalid argument to V line: "ERSIONID(\001Id: autoco"
Jun 11 02:33:11 host sm-mta[30913]: restarting /usr/sbin/sendmail-mta due to signal
Jun 11 02:33:11 host sm-mta[30913]: NOQUEUE: SYSERR(root): /etc/mail/sendmail.cf: line 6: invalid argument to V line: "ERSIONID(\001Id: startt"


text:
Q: Change Gridview Datasource using ASP .NET SQLDATASOURCE i have a gridview automaticly connecting with sqldatasource1, etc. For the grid, I also have a search textbox  If the user needs to filter the records it calls an another ((sqldatasource2-another procuder)) and put it in the same gridview ..,so i need to change the gridView.datasourceID to the another sqldatasource onclick a button ..
note :
sqldatasource1 and sqldatasource2 returning the same queries ,
the procuder of sqldatasource1 :
create proc AfficheDossiers
@Nom_GIAC varchar(50)
as
 begin
 select [ID_Dossier] as 'ID_Dossier'
      ,[ID_Entreprise] as 'ID_Entreprise'
      ,[Date_Depot] as 'Date_Dépôt'
      ,[Type_Etude] as 'Type_Etude'
      ,[Dernier_Type] as 'Dernier_Type'
      ,[Eligibile] as 'Eligibilité'
      ,[Fiche_Information] as 'Fiche_Information'
      ,[Buletin_Adhesion] as 'Bulletin_d'adhésion'
      ,[Fiche_Renseignment] as 'Fiche_Renseignment'
      ,[Attestation] as 'Attestation'
      ,[Date_Debut] as 'Date_Début'
      ,[Date_Fin] as 'Date_Fin'
      ,[ID_Cabinet] as 'ID_Cabinet'
      ,[Montant_Demander] as 'Montant_Demander'
      ,[Duree] as 'Durée'
      ,[Porcentage_Taux] as 'Pourcentage,Taux' from Dossier where Nom_Giac = @Nom_GIAC
 end

the procuder of sqldatasource2((searche) :
alter proc rechercherGIAC @nomgiac varchar(20),@nom varchar(30),@par varchar(50)
           as
            begin
            if @nom='CNSS'
              begin
              select d.[ID_Dossier] as 'ID_Dossier'
              ,d.[ID_Entreprise] as 'ID_Entreprise'
              ,[Date_Depot] as 'Date_Dépôt'
              ,[Type_Etude] as 'Type_Etude'
              ,[Dernier_Type] as 'Dernier_Type'
              ,[Eligibile] as 'Eligibilité'
              ,[Fiche_Information] as 'Fiche_Information'
              ,[Buletin_Adhesion] as 'Bulletin_d'adhésion'
              ,[Fiche_Renseignment] as 'Fiche_Renseignment'
              ,[Attestation] as 'Attestation'
              ,[Date_Debut] as 'Date_Début'
              ,[Date_Fin] as 'Date_Fin'
              ,[ID_Cabinet] as 'ID_Cabinet'
              ,[Montant_Demander] as 'Montant_Demander'
              ,[Duree] as 'Durée'
              ,[Porcentage_Taux] as 'Pourcentage,Taux'
              from dbo.Dossier d inner join entreprise e on d.ID_Entreprise=e.ID_Entreprise
              where CNSS_Entreprise=@par and d.Nom_Giac=@nomgiac
              end
            else if @nom='RS'
              begin
              select [ID_Dossier] as 'ID_Dossier'
              ,[ID_Entreprise] as 'ID_Entreprise'
              ,[Date_Depot] as 'Date_Dépôt'
              ,[Type_Etude] as 'Type_Etude'
              ,[Dernier_Type] as 'Dernier_Type'
              ,[Eligibile] as 'Eligibilité'
              ,[Fiche_Information] as 'Fiche_Information'
              ,[Buletin_Adhesion] as 'Bulletin_d'adhésion'
              ,[Fiche_Renseignment] as 'Fiche_Renseignment'
              ,[Attestation] as 'Attestation'
              ,[Date_Debut] as 'Date_Début'
              ,[Date_Fin] as 'Date_Fin'
              ,[ID_Cabinet] as 'ID_Cabinet'
              ,[Montant_Demander] as 'Montant_Demander'
              ,[Duree] as 'Durée'
              ,[Porcentage_Taux] as 'Pourcentage,Taux'
              from dbo.Dossier
              where  Nom_Giac=@nomgiac and ID_Entreprise in( select ID_Entreprise
                                                             from dbo.Entreprise
                                                             where Raison_Social=@par)
              end
           else if @nom ='Date'
            begin
             declare @v smalldatetime,@b smalldatetime
              set @b=SUBSTRING(@par,1,4)
              set @v=SUBSTRING(@par,5,8)
            select [ID_Dossier] as 'ID_Dossier'
              ,[ID_Entreprise] as 'ID_Entreprise'
              ,[Date_Depot] as 'Date_Dépôt'
              ,[Type_Etude] as 'Type_Etude'
              ,[Dernier_Type] as 'Dernier_Type'
              ,[Eligibile] as 'Eligibilité'
              ,[Fiche_Information] as 'Fiche_Information'
              ,[Buletin_Adhesion] as 'Bulletin_d'adhésion'
              ,[Fiche_Renseignment] as 'Fiche_Renseignment'
              ,[Attestation] as 'Attestation'
              ,[Date_Debut] as 'Date_Début'
              ,[Date_Fin] as 'Date_Fin'
              ,[ID_Cabinet] as 'ID_Cabinet'
              ,[Montant_Demander] as 'Montant_Demander'
              ,[Duree] as 'Durée'
              ,[Porcentage_Taux] as 'Pourcentage,Taux'
            from Dossier
            where Date_Depot between @b and @v and Nom_Giac like @nomgiac

            end
            end

this is the search text and button :
 Saisir la CNSS :
                     <asp:TextBox ID="CNSSTxt" class="TXTBOX" runat="server" Height="23px" placeholder="CNSS" style="font-family : Comic Sans MS, Arial, Tahoma; color:Red;"></asp:TextBox>

                     <asp:Button ID="BtnFiltrerCNSS" runat="server" Text="Filtrer" class="BTN" style="font-variant:small-caps;" />

this is the gridview :
 <div class="GridViewDiv">

              <asp:UpdatePanel ID="DossierUpdatePanel" runat="server" UpdateMode="Conditional" >
                  <ContentTemplate>
                      <asp:SqlDataSource ID="Dossier" runat="server"
                              ConnectionString="<%$ ConnectionStrings:OfficeConnectionString %>"
                              SelectCommand="AfficheDossiers" SelectCommandType="StoredProcedure">
                                   <SelectParameters>
                                       <asp:SessionParameter Name="Nom_GIAC" SessionField="Nom_GIAC" Type="String" />
                                   </SelectParameters>
                          </asp:SqlDataSource>

                      <asp:SqlDataSource ID="RechercheDossierDS" runat="server"
                          ConnectionString="<%$ ConnectionStrings:OfficeConnectionString %>"
                          SelectCommand="rechercherGIAC" SelectCommandType="StoredProcedure">
                          <SelectParameters>
                              <asp:SessionParameter Name="nomgiac" SessionField="Nom_GIAC" Type="String" />
                              <asp:ControlParameter ControlID="RecherhcerComboBox" Name="nom"
                                  PropertyName="SelectedValue" Type="String" />
                              <asp:SessionParameter Name="par" SessionField="Recherche" Type="String" />
                          </SelectParameters>
                      </asp:SqlDataSource>
                      <asp:GridView ID="DossierGV" runat="server" AllowPaging="True" AllowSorting="True"
          DataSourceID="Dossier" AutoGenerateColumns="False" DataKeyNames="ID_Dossier">
                          <Columns>
                              <asp:CommandField ShowSelectButton="True" />
                              <asp:BoundField DataField="ID_Dossier" HeaderText="ID_Dossier" ReadOnly="True"
                                  SortExpression="ID_Dossier" />
                              <asp:BoundField DataField="ID_Entreprise" HeaderText="ID_Entreprise"
                                  SortExpression="ID_Entreprise" />
                              <asp:BoundField DataField="Date_Dépôt" HeaderText="Date_Dépôt"
                                  SortExpression="Date_Dépôt" />
                              <asp:BoundField DataField="Type_Etude" HeaderText="Type_Etude"
                                  SortExpression="Type_Etude" />
                              <asp:BoundField DataField="Dernier_Type" HeaderText="Dernier_Type"
                                  SortExpression="Dernier_Type" />
                              <asp:BoundField DataField="Eligibilité" HeaderText="Eligibilité"
                                  SortExpression="Eligibilité" />
                              <asp:BoundField DataField="Fiche_Information" HeaderText="Fiche_Information"
                                  SortExpression="Fiche_Information" />
                              <asp:BoundField DataField="Bulletin_d'adhésion" HeaderText="Bulletin_d'adhésion"
                                  SortExpression="Bulletin_d'adhésion" />
                              <asp:BoundField DataField="Fiche_Renseignment" HeaderText="Fiche_Renseignment"
                                  SortExpression="Fiche_Renseignment" />
                              <asp:BoundField DataField="Attestation" HeaderText="Attestation"
                                  SortExpression="Attestation" />
                              <asp:BoundField DataField="Date_Début" HeaderText="Date_Début"
                                  SortExpression="Date_Début" />
                              <asp:BoundField DataField="Date_Fin" HeaderText="Date_Fin"
                                  SortExpression="Date_Fin" />
                              <asp:BoundField DataField="ID_Cabinet" HeaderText="ID_Cabinet"
                                  SortExpression="ID_Cabinet" />
                              <asp:BoundField DataField="Montant_Demander" HeaderText="Montant_Demander"
                                  SortExpression="Montant_Demander" />
                              <asp:BoundField DataField="Durée" HeaderText="Durée" SortExpression="Durée" />
                              <asp:BoundField DataField="Pourcentage,Taux" HeaderText="Pourcentage,Taux"
                                  SortExpression="Pourcentage,Taux" />
                          </Columns>
                      </asp:GridView>
                  </ContentTemplate>
              </asp:UpdatePanel>
       </div>

Any clues?
thanks,

A: In the onclick button event just set

gridview.datasource = newDataSource;

Then call the

girdView.DataBind();

Let me know if this is what you needed.
If you are using visual studio 2010, you need to click on your .aspx file and then click design view in the bottom right of the window. This will load a mock up of your screen and you can just double click the button that you want the click event on. It will then redirect you to the code behind (.aspx.cs) file. In that method is where you need to write this.
I only say this now because I see that your button has no onclick="methodName" property

A: You can give data source in code behind according to the condition.
   if(someCondition)
       myStoredProcedure = "storedProc1";
    else
       myStoredProcedure = "storedProc2";

    SqlDataSource dataSource = new SqlDataSource(ConfigurationManager.ConnectionStrings["connstr"].ConnectionString, searchQuery);
    dataSource.SelectCommandType = SqlDataSourceCommandType.StoredProcedure;
    dataSource.SelectCommand = myStoredProcedure;
    dataSource.ID = "myDataSource";

   // Your code to set datasource to grid

   gridBookings.DataSourceID = dataSource.ID;
   gridBookings.DataBind();


text:
Q: C++ code pass compling but return Segmentation fault I have the following C++ code for practising sequence list and it passed the complier. However, when I try to run it, it returns Segmentation fault. Please help!! Thanks a lot.
main.cpp
#include <iostream>
#include <string>
#include "SeqList.h"

using namespace std;

int main() {

    SeqList seq;

    string vv[] = {"a", "b", "c", "d"};

    for (int i = 0; i< 4; i++) {
        seq.addElement(vv[i], i);

    }

    string* v  = seq.getSeq();
    for (int i=0; i<seq.getSeqSize(); i++) {
        cout << v[i] <<endl;
    }

    return 0;
}

SeqList.h
#include<iostream>
#include<string>

using namespace std;

class SeqList {

    private:
        string seq[];
        int size;

    public:
        void addElement(string, int);
        void delElement(string, int);
        string* getSeq();
        int getSeqSize();

};

SeqList.cpp
#include <iostream>
#include <string>
#include "SeqList.h"

using namespace std;

string seq[100];
int size = 0;

string* SeqList::getSeq(){
    return seq;
};

int SeqList::getSeqSize(){
    return size;
};

void SeqList::addElement(string str, int pos) {
    int i;
    for (i = size; i > pos; i--) {
        seq[i] = seq[i-1];
    }
    seq[i-1] = str;
    size++;
};

A: Your segfault is happening because you're trying to access seq[i-1] in addElement when i = 0. This tries to access the memory outside of seq which causes a segfault. Try using seq[i] and seq[i+1] instead of seq[i-1] and seq[i], though you'll have to make sure you never call that code with more than 99 values or you'll run into a similar problem where the program tries to access memory past the end of seq.
Also, in SeqList.cpp
string seq[100];
int size = 0;

These lines are creating new variables, when it looks like you're trying to change the values you made in SeqList.h. To change those private values in your class you should either use a constructor or other function to initialize the values.


text:
Q: Is it good practice to use the Content folder in ASP.NET MVC as File System to store PDF Files? So I need a place (file system/folder) to store static PDF files for my ASP.NET MVC app. It will be around 36 pdf files a year. Can't use a database for this project.
So my questions is, is it good practice to store those 36 pdf files/a year in the 'Content' folder? Or should I instead store it in a folder outside the website structure? For people who don't store pdf files on the database, where do they usually store it? I'm concern storing all those files in the 'Content' folder is gonna affect performance.
Thanks in advance.


text:
Q: Plot the map (raster file) in R, ggplot2 in particular I want to plot the map of climate zones of Australia. Relevant files (ASCII file) have been downloded from: http://www.bom.gov.au/web01/ncc/www/climatology/climate-classification/kpngrp.zip
The orginal map looks like this.

But when I used the ASCII file to re-plot this map, I cannot make it. The used code is:
library(ggplot2);library(raster)
r<-raster("kpngrp.txt")
plot(r)

How do I fix this to plot the map?

A: You first have to properly read your dataset, which is not a raster file, but a txt. The first lines of the header provide information about "format" and georeferencing:

ncols           1681
nrows           1361
xllcorner       112
yllcorner -44
cellsize      0.025
NODATA_value  -9999

to properly read the data and convert it to a raster object, you can therefore do:
infile <- "/home/lb/Temp/buttami/kpngrp.txt"
data <- as.matrix(read.table(infile, skip = 6))
data[data == -9999] = NA
rr <- raster(data, crs = "+init=epsg:4326")
extent(rr) = c(112, 112+0.025*1681, -44, -44+0.025*1361)

> rr
class       : RasterLayer
dimensions  : 1361, 1681, 2287841  (nrow, ncol, ncell)
resolution  : 0.025, 0.025  (x, y)
extent      : 112, 154.025, -44, -9.975  (xmin, xmax, ymin, ymax)
coord. ref. : +init=epsg:4326 +proj=longlat +datum=WGS84 +no_defs +ellps=WGS84 +towgs84=0,0,0
data source : in memory
names       : layer
values      : 0, 42  (min, max)

now, to plot it you can use several approaches. However, to get something nice you'll first have to remove the "ocean" data by masking with a vector shapefile:
adm <- getData("GADM", country="AUS", level=1)
rr = mask(rr, adm)
plot(rr)

NOte that the plot shows more "colors" than your example, since I think they aggregated the Koppen regions by larger "categories". TO obtain a map osimilar to that you will have to "join" several values of the original ASCII in a smaller number of classes.


text:
Q: Trouble sorting records on unique attributes Working with the following code, I need to return only records where the `point' attribute is unique.  I can't seem to get there by myself.
uniques = Item.find_all_by_item_id(item_id)
uniques.sort! {|a, b| b.point <=> a.point } # how do I reject the equal points?

In other words.. I guess, how do you make [0, 1, 1, 1, 2, 3, 3, 4, 4, 7] #=> [0, 2, 7] ?

A: How about this:
# Get the number of items with each point value
counts = Item.count("point", :group => "point")

# Get the IDs of all entries that only show up once
unique_ids = counts.collect { |count| count[0] if count[1] == 1 }.compact

unique_items = Item.find_all_by_id(unique_ids)

A: I can think of few ways off the top of my head to do this:
uniques.reject!{|u| uniques.select{|x| x == u}.size > 1}

Basically iterate through the uniques array and then see if there is more than one of those items in the array.  Obviously there are lots of clever ways to speed this up, but for small arrays this should work.
or
h = Hash.new(0)
uniques.each{|u| h[u] += 1}
h.reject{|k,v| v > 1}.keys

Basically count how many times each item shows up in a hash, if its more than one reject it and then just look at the keys.


text:
Q: How can i change the appearance of Windows 7 menus? My Win32 Application displays Menus as shown when running on Win 7:

This is the Default for the themes Windows 7 as well as Windows 7 Aqua.
Please note that the selected menu entry is only slightly different from the other entries. I think it is much too less highlighted and therefore i am looking for a way to give the selected entry a different color. But unfortunately all possibilities to modify menu colors disappeared in Windows 7. The settings made in the window color dialog are non effective for menus.
But amazingly Microsoft's own applications look different. I.e. Paint has different color and appearance of menus:

This has good contrast and is much better than the default for a Win32 application.
Also Visual Studio 2010 looks different:

I know that VS 2010 is build on WPF. I don't know if and how the ribbon, used in paint influences the menu appearance. My menus are set up dynamically using SetMenu();
My Question: Is there any way to change the appearance of my applications menu using a API or maybe a manifest or resource?
Or is there a way to modify the color of the selected menu entry in Windows 7 through settings?

A: You can make your own user drawn menus. For an example, take a look at this CodeProject.com article: http://www.codeproject.com/KB/menus/newmenuxpstyle.aspx
Also, VS 2010 is not entirely built on WPF - only the code editor.


text:
Q: Draw a floating image HTML CSS I want to draw an image with HTML/CSS that "floats" above the main content. The position has to be relative to a table. Currently I am trying this:

Table Heading

The CSS style has:
position:relative;
top:10px;
left:10px;

The image itself is pretty large (in terms of dimensions). The code positions the image properly, but the problem is that the table cell becomes very large (large enough to accommodate the image). I want the image to float above the table and not affect the table size. If I change the position to absolute, the table cell does not expand, but the image will be positioned relative to the screen, which I don't want.
So I'm wondering what is the correct way to draw a floating image relative to a table in HTML?
Any help would be appreciated.

A: Set the position on the table to relative and the position on the image to absolute. This way the image's absolute position will be relative to the table, not the document.
jsFiddle example
.float {
    position:absolute;
    top:10px;
    left:10px;
}
table {
    border:1px solid #999;
    position:relative;
    top:100px;
}


text:
Q: DCMTK movescu error: response suceed but no file received I am new in DICOM and DCMTK. I was trying to retrieve dcm files from a private PACS server(172.18.1.1) with movescu command in Windows platform. The incoming and outgoing message were normal but no data was received in the specified directory.The command is as following:
movescu.exe -d -S -aec GEPACS -aet TEST1  -od c:\windows\dcmtk\dcm 172.18.1.1 4100 -k QueryRetrieveLevel=STUDY -k StudyInstanceUID=1.2.840.113619.186.351258914078.20100708160459594.417

The output message is as follow:
>D: $dcmtk: movescu v3.6.3 2018-02-05 $
>D:
>D: Request Parameters:
>D: ====================== BEGIN A-ASSOCIATE-RQ =====================
>D: Our Implementation Class UI>D:      1.2.276.0.7230010.3.0.3.6.3
>D: Our Implementation Version Name:   OFFIS_DCMTK_363
>D: Their Implementation Class UI>D:
>D: Their Implementation Version Name:
>D: Application Context Name:    1.2.840.10008.3.1.1.1
>D: Calling Application Name:    TEST1
>D: Called Application Name:     GEPACS
>D: Responding Application Name: GEPACS
>D: Our Max PDU Receive Size:    16384
>D: Their Max PDU Receive Size:  0
>D: Presentation Contexts:
>D:   Context I>D:        1 (Proposed)
>D:     Abstract Syntax: =FINDStudyRootQueryRetrieveInformationModel
>D:     Proposed SCP/SCU Role: Default
>D:     Proposed Transfer Syntax(es):
>D:       =LittleEndianExplicit
>D:       =BigEndianExplicit
>D:       =LittleEndianImplicit
>D:   Context I>D:        3 (Proposed)
>D:     Abstract Syntax: =MOVEStudyRootQueryRetrieveInformationModel
>D:     Proposed SCP/SCU Role: Default
>D:     Proposed Transfer Syntax(es):
>D:       =LittleEndianExplicit
>D:       =BigEndianExplicit
>D:       =LittleEndianImplicit
>D: Requested Extended Negotiation: none
>D: Accepted Extended Negotiation:  none
>D: Requested User Identity Negotiation: none
>D: User Identity Negotiation Response:  none
>D: ======================= END A-ASSOCIATE-RQ ======================
>I: Requesting Association
>D: setting network send timeout to 60 seconds
>D: setting network receive timeout to 60 seconds
>D: Constructing Associate RQ PDU
>D: PDU Type: Associate Accept, PDU Length: 208 + 6 bytes PDU header
>D:   02  00  00  00  00  d0  00  01  00  00  47  45  50  41  43  53
>D:   20  20  20  20  20  20  20  20  20  20  41  45  5f  41  52  43
>D:   48  31  20  20  20  20  20  20  20  20  00  00  00  00  00  00
>D:   00  00  00  00  00  00  00  00  00  00  00  00  00  00  00  00
>D:   00  00  00  00  00  00  00  00  00  00  10  00  00  15  31  2e
>D:   32  2e  38  34  30  2e  31  30  30  30  38  2e  33  2e  31  2e
>D:   31  2e  31  21  00  00  1b  01  00  00  00  40  00  00  13  31
>D:   2e  32  2e  38  34  30  2e  31  30  30  30  38  2e  31  2e  32
>D:   2e  31  21  00  00  1b  03  00  00  00  40  00  00  13  31  2e
>D:   32  2e  38  34  30  2e  31  30  30  30  38  2e  31  2e  32  2e
>D:   31  50  00  00  31  51  00  00  04  00  00  70  00  52  00  00
>D:   13  31  2e  32  2e  38  34  30  2e  31  31  33  36  31  39  2e
>D:   36  2e  39  34  55  00  00  0e  43  45  4e  54  52  49  43  49
>D:   54  59  5f  34  2e  30
>D: Parsing an A-ASSOCIATE PDU
>D: Association Parameters Negotiate>D:
>D: ====================== BEGIN A-ASSOCIATE-AC =====================
>D: Our Implementation Class UI>D:      1.2.276.0.7230010.3.0.3.6.3
>D: Our Implementation Version Name:   OFFIS_DCMTK_363
>D: Their Implementation Class UI>D:    1.2.840.113619.6.94
>D: Their Implementation Version Name: CENTRICITY_4.0
>D: Application Context Name:    1.2.840.10008.3.1.1.1
>D: Calling Application Name:    TEST1
>D: Called Application Nae:     GEPACS
>D: Responding Application Name: GEPACS
>D: Our Max PDU Receive Size:    16384
>D: Their Max PDU Receive Size:  28672
>D: Presentation Contexts:
>D:   Context I>D:        1 (Accepted)
>D:     Abstract Syntax: =FINDStudyRootQueryRetrieveInformationModel
>D:     Proposed SCP/SCU Role: Default
>D:     Accepted SCP/SCU Role: Default
>D:     Accepted Transfer Syntax: =LittleEndianExplicit
>D:   Context I>D:        3 (Accepted)
>D:     Abstract Syntax: =MOVEStudyRootQueryRetrieveInformationModel
>D:     Proposed SCP/SCU Role: Default
>D:     Accepted SCP/SCU Role: Default
>D:     Accepted Transfer Syntax: =LittleEndianExplicit
>D: Requested Extended Negotiation: none
>D: Accepted Extended Negotiation:  none
>D: Requested User Identity Negotiation: none
>D: User Identity Negotiation Response:  none
>D: ======================= END A-ASSOCIATE-AC ======================
>I: Association Accepted (Max Send PDV: 28660)
>I: Sending Move Request
>D: ===================== OUTGOING DIMSE MESSAGE ====================
>D: Message Type                  : C-MOVE RQ
>D: Presentation Context ID       : 3
>D: Message ID                    : 1
>D: Affected SOP Class UID        : MOVEStudyRootQueryRetrieveInformationModel
>D: Data Set                      : present
>D: Priority                      : medium
>D: Move Destination              : TEST1
>D: ======================= END DIMSE MESSAGE =======================
>I: Request Identifiers:
>I:
>I: # Dicom-Data-Set
>I: # Used TransferSyntax: Little Endian Explicit
>I: (0008,0052) CS [STUDY]                                  #   6, 1 QueryRetrieveLevel
>I: (0020,000d) UI [1.2.840.113619.186.351258914078.20100708160459594.417] #  54, 1 StudyInstanceUID
>I:
>D: DcmDataset::read() TransferSyntax="Little Endian Implicit"
>I: Received Final Move Response
>D: ===================== INCOMING DIMSE MESSAGE ====================
>D: Message Type                  : C-MOVE RSP
>D: Message ID Being Responded To : 1
>D: Affected SOP Class UID        : MOVEStudyRootQueryRetrieveInformationModel
>D: Remaining Suboperations       : none
>D: Completed Suboperations       : 6
>D: Failed Suboperations          : 0
>D: Warning Suboperations         : 0
>D: Data Set                      : none
>D: DIMSE Status                  : 0x0000: Success
>D: ======================= END DIMSE MESSAGE =======================
>I: Releasing Association

And also I tried to add --port 104 or -aem TEST1, but failed either.

A: The default "move destination" (option -aem) of movescu is "MOVESCU". Does your PACS know anything about this AE title? It seems that the 6 DICOM SOP Instances ("Completed Suboperations: 6") were sent successfully to this AE (Application Entity). The output directory (option -od) is only used when movescu also acts as a Storage SCP, i.e. if option --port (or +P) is used.

And also I tried to add --port 104 or -aem TEST1, but failed either.

Did you configure your PACS to map the AE title "TEST1" to the IP address of the system movescu is running on and to port 104?

A: It seems that the C-MOVE operation is successful:
>I: Received Final Move Response
>D: ===================== INCOMING DIMSE MESSAGE ====================
>D: Message Type                  : C-MOVE RSP
>D: Message ID Being Responded To : 1
>D: Affected SOP Class UID        : MOVEStudyRootQueryRetrieveInformationModel
>D: Remaining Suboperations       : none
>D: Completed Suboperations       : 6
>D: Failed Suboperations          : 0
>D: Warning Suboperations         : 0
>D: Data Set                      : none
>D: DIMSE Status                  : 0x0000: Success
>D: ======================= END DIMSE MESSAGE =======================

According to the message from the server, 6 Sub-Operations were successsfully completed (i.e. 6 images were moved to the move destination), and the Status is "Success". Thus, I would suspect that the AET "TEST1" maps to a different system, not yours.
As J. Riesmeier suggested, you should check the IP and Port configuration for "TEST1" in the PACS.


text:
Q: Spring MVC not initial request mapping Does the web deploy mechanism affect Spring MVC work?
I create a web project(SpringMVCTest) contains web.xml and a pjsp pages then I create a Java project(SpringMVCTestSrc) and use the link source function to link test_src and SpringMVCTestSrc.
My Eclipse workspace

My problem is if I deploy the project in war file then it works fine
, EX: if I open

localhost:8080/SpringMVCTest/message/showMessage.pages

it will forward to

main/showMessage.jsp

but if I deploy the project with separate web and jar file it will no request mapping found like below.
[DEBUG]-[2015/07/30 15:03:39,o.s.w.s.DispatcherServlet(init):139]: Servlet 'dispatcher' configured successfully
[DEBUG]-[2015/07/30 15:03:40,o.s.w.s.DispatcherServlet(doService):861]: DispatcherServlet with name 'dispatcher' processing GET request for [/SpringMVCTest/message/showMessage.pages]
[DEBUG]-[2015/07/30 15:03:40,o.s.w.s.m.m.a.RequestMappingHandlerMapping(getHandlerInternal):294]: Looking up handler method for path /message/showMessage.pages
[DEBUG]-[2015/07/30 15:03:40,o.s.w.s.m.m.a.RequestMappingHandlerMapping(getHandlerInternal):302]: Did not find handler method for [/message/showMessage.pages]
[WARN]-[2015/07/30 15:03:40,o.s.w.s.PageNotFound(noHandlerFound):1136]: No mapping found for HTTP request with URI [/SpringMVCTest/message/showMessage.pages] in DispatcherServlet with name 'dispatcher'

The log shows the different.
If I deploy in war file. The log shows found 18 bean definitions and request mapping works fine.

*

*Export war file from Eclipse and put it to apache-tomcat-8.0.21\webapps

*Startup Tomcat and open localhost:8080/SpringMVCTest/message/showMessage.pages

*The page will show Message : Hello world

o.s.c.a.ClassPathBeanDefinitionScanner(registerDefaultFilters):244]: JSR-250 'javax.annotation.ManagedBean' found and supported for component scanning
o.s.c.i.s.PathMatchingResourcePatternResolver(doFindMatchingFileSystemResources):631]: Looking for matching resources in directory tree [D:\Temp\apache-tomcat-8.0.21\webapps\SpringMVCTest\WEB-INF\classes\in\hotkey\mvc]
o.s.c.i.s.PathMatchingResourcePatternResolver(doRetrieveMatchingFiles):693]: Searching directory [D:\Temp\apache-tomcat-8.0.21\webapps\SpringMVCTest\WEB-INF\classes\in\hotkey\mvc] for files matching pattern [D:/Temp/apache-tomcat-8.0.21/webapps/SpringMVCTest/WEB-INF/classes/in/hotkey/mvc/**/*.class]
o.s.c.i.s.PathMatchingResourcePatternResolver(findPathMatchingResources):424]: Resolved location pattern [classpath*:in/hotkey/mvc/**/*.class] to resources [file [D:\Temp\apache-tomcat-8.0.21\webapps\SpringMVCTest\WEB-INF\classes\in\hotkey\mvc\MainForm.class]]
o.s.c.a.ClassPathBeanDefinitionScanner(findCandidateComponents):286]: Identified candidate component class: file [D:\Temp\apache-tomcat-8.0.21\webapps\SpringMVCTest\WEB-INF\classes\in\hotkey\mvc\MainForm.class]
o.s.b.f.x.XmlBeanDefinitionReader(loadBeanDefinitions):224]: Loaded 18 bean definitions from location pattern [classpath:test-dispatcher-context.xml]

If I deploy with separate web and jar file. The log shows found 17 bean definitions and request mapping does not work.

*

*Build a directory in apache-tomcat-8.0.21\webapps, EX: apache-tomcat-8.0.21\webapps\SpringMVCTest

*Copy WEB-INF, META-INF from Eclipse workspace to apache-tomcat-8.0.21\webapps\SpringMVCTest

*Export jar file from SpringMVCTestSrc and put it to apache-tomcat-8.0.21\webapps\SpringMVCTest\WEB-INF\lib

*Startup Tomcat and open localhost:8080/SpringMVCTest/message/showMessage.pages

*The page shows HTTP 404

o.s.c.a.ClassPathBeanDefinitionScanner(registerDefaultFilters):244]: JSR-250 'javax.annotation.ManagedBean' found and supported for component scanning
o.s.c.i.s.PathMatchingResourcePatternResolver(findPathMatchingResources):424]: Resolved location pattern [classpath*:in/hotkey/mvc/**/*.class] to resources []
o.s.b.f.x.XmlBeanDefinitionReader(loadBeanDefinitions):224]: Loaded 17 bean definitions from location pattern [classpath:test-dispatcher-context.xml]

Does someone know why the same code but different deploy mechanism has different result?
My code as blow
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 xmlns="http://xmlns.jcp.org/xml/ns/javaee"
  xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
   id="WebApp_ID" version="3.1">
    <display-name>SpringMVCTest</display-name>
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>classpath:test-service-context.xml</param-value>
    </context-param>
    <filter>
        <filter-name>SetCharacterEncodingFilter</filter-name>
        <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
        <init-param>
            <param-name>encoding</param-name>
            <param-value>UTF-8</param-value>
        </init-param>
    </filter>
    <filter-mapping>
        <filter-name>SetCharacterEncodingFilter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>
    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>
    <servlet>
        <servlet-name>dispatcher</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>classpath:test-dispatcher-context.xml</param-value>
        </init-param>
        <load-on-startup>3</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>dispatcher</servlet-name>
        <url-pattern>*.pages</url-pattern>
    </servlet-mapping>
</web-app>

Spring Configuration(test-service-context.xml)
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="
    http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd">

    <bean id="testMessageService" class="in.hotkey.service.TestMessageService" >
    </bean>

</beans>

Spring MVC Config(test-dispatcher-context.xml)
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:mvc="http://www.springframework.org/schema/mvc"
    xsi:schemaLocation="
    http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
    http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd
    http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd">

    <mvc:annotation-driven />
    <context:component-scan base-package="in.hotkey.mvc"/>

    <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/WEB-INF/views/" />
        <property name="suffix" value=".jsp" />
    </bean>

    <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver" />
</beans>

Main Controller
package in.hotkey.mvc;

import in.hotkey.service.TestMessageService;

import javax.annotation.Resource;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

@Controller
public class MainForm {

    @RequestMapping(value="/message/showMessage.pages")
    public ModelAndView handleShowMessage() throws Exception {
        ModelAndView mv = new ModelAndView("main/showMessage");
        mv.addObject("message", "Hello world!");

        return mv;
    }

}

JSP Content
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Test</title>

Message : ${message}

A: I found what the problem is....
Root cause founded from Spring MVC document.

It means annotation scan need directory entries!!
The problem is if I export whole project into war file. It contains the complete directory entries in WEB-INF/classes directory but jar file has no directory entry information.
Resolve this problem just check the "Add directory entries" option in Eclipse export function.


text:
Q: Refresh list and adapter when DB changed in custom Adapter my project is todo
i have 4 tab , 4 fragment with 4 list(Actionbar navigation contain 4 tab and ViewPager).
4 list(tab) use same db table but each of them retrieve different data with categoryID.
i use a Asynctask for all of them ,to read data and set adapter to list.
public class AsyncTaskDB extends AsyncTask<Void, Void, listAdapter> {

Context act;
int Categoryid;
ArrayList<memo> arraymemo;
listAdapter myadapter;
ListView list;
listAdapter listAdp;

public AsyncTaskDB(Context acti, int categoryID) {
    this.act = acti;
    this.Categoryid = categoryID;

}

@Override
protected listAdapter doInBackground(Void... params) {
    MemoDBHelper helper = new MemoDBHelper(act);

    // getAllDataByCategoryID
    if (Categoryid != CategoryID.Done_ID)
        arraymemo = helper.getAllTaskByCategory(Categoryid);
    else
        arraymemo = (ArrayList<memo>) helper.gatDoneMemo();

    myadapter = new listAdapter(act, arraymemo);
    if (myadapter == null) {
        Toast.makeText(act, "no data", Toast.LENGTH_SHORT).show();
        cancel(true);
    }
    return myadapter;

}

@Override
protected void onPostExecute(listAdapter result) {

    switch (Categoryid) {
    case CategoryID.Urgent_Imprtant_ID:
        list = (ListView) ((Activity) act)
                .findViewById(R.id.Urgent_Important_list);

                    break;

    case CategoryID.Urgent_Less_Imprtant_ID:
        list = (ListView) ((Activity) act)
                .findViewById(R.id.Urgent_Less_Important_list);

        break;
    case CategoryID.Less_Urgent_Imprtant_ID:
        list = (ListView) ((Activity) act)
                .findViewById(R.id.Less_Urgent_Imprtant_list);

        break;

    case CategoryID.Neither_Urgent_Or_Imprtant_ID:
        list = (ListView) ((Activity) act)
                .findViewById(R.id.Neither_Urgent_Imprtant_list);

        break;
    case CategoryID.Done_ID:

        list = (ListView) ((Activity) act).findViewById(R.id.ArchiveList);
        break;
    }
    list.setAdapter(result);
    this.listAdp = result;

}

public listAdapter getlistAdapter() {
    return this.listAdp;
}

}
each memo in list have Done CheckBox.when user check and uncheck it,automatically memo update in db.(in custom adapter)
 ----------------------------
|   --                      |
|  |  |          memotitle  |
|   --                      |
----------------------------

public class listAdapter extends BaseAdapter implements OnCheckedChangeListener { Context act;
ArrayList<memo> MemoArray;
SparseBooleanArray mcheck;
int pos;
MemoDBHelper helper;

public listAdapter(Context activity, ArrayList<memo> memoarray) {
    this.act = activity;
    this.MemoArray = memoarray;
    mcheck = new SparseBooleanArray(memoarray.size());
    helper = new MemoDBHelper(act);
}

@Override
public int getCount() {
    // TODO Auto-generated method stub
    return MemoArray.size();
}

@Override
public memo getItem(int position) {
    // TODO Auto-generated method stub
    return MemoArray.get(position);
}

@Override
public long getItemId(int arg0) {
    // TODO Auto-generated method stub
    return 0;
}

public class viewHolder {
    TextView title;
    // TextView description;
    CheckBox chkstatus;
}

viewHolder it;

@Override
public View getView(int position, View convertView, ViewGroup parent) {
    pos = position;
    LayoutInflater in = ((Activity) act).getLayoutInflater();
    if (convertView == null) {
        convertView = in.inflate(R.layout.list_item, null);

        it = new viewHolder();
        it.title = (TextView) convertView.findViewById(R.id.txt_list_title);
        it.chkstatus = (CheckBox) convertView
                .findViewById(R.id.chkStatusid);

        convertView.setTag(it);
    } else {
        it = (viewHolder) convertView.getTag();

    }

    it.title.setText(MemoArray.get(position).GetTitle());
    it.chkstatus.setChecked(MemoArray.get(position).GetSattus());
    it.chkstatus.setOnCheckedChangeListener(this);
    it.chkstatus.setTag(String.valueOf(MemoArray.get(position).GetID()));
    return convertView;
}

@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {

    mcheck.put(Integer.valueOf((String) buttonView.getTag()), isChecked);
    helper.updateStatusByID(Integer.valueOf((String) buttonView.getTag()),
            (isChecked));
    helper.close();
   //after db updatedt ,call method in fragment to notifydatsetchanged!
    UrgentImportant_frg.notifyAdapter();

}

}
adapter must notify data changed ,and list don't show done memo.i don't how to do it !
my first fragment :
public class UrgentImportant_frg extends Fragment {
static listAdapter myadp;
ListView list;
// memo selectedmemo;
long[] checkid;
AsyncTaskDB asyn;
ArrayList<memo> selectedMemoArray;
final static int RQS_MoveTo = 10;

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState) {
    View rootview = inflater.inflate(R.layout.urgentimportant_layout,
            container, false);
    return rootview;
}

@Override
public void onActivityCreated(Bundle savedInstanceState) {

    super.onActivityCreated(savedInstanceState);
    list.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE_MODAL);
    selectedMemoArray = new ArrayList<memo>();
    list.setMultiChoiceModeListener(new MultiChoiceModeListener() {

        @Override
        public boolean onPrepareActionMode(ActionMode mode, Menu menu) {

            return true;
        }

        @Override
        public void onDestroyActionMode(ActionMode mode) {

            // list.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE_MODAL);

        }

        @Override
        public boolean onCreateActionMode(ActionMode mode, Menu menu) {

            mode.getMenuInflater().inflate(R.menu.list_select_menu, menu);
            /*
             * MenuInflater inflater = getActivity().getMenuInflater();
             * inflater.inflate(R.menu.list_select_menu, menu);
             */

            mode.setTitle("Select Items");
            return true;
        }

        @Override
        public boolean onActionItemClicked(final ActionMode mode,
                MenuItem item) {

            switch (item.getItemId()) {
            case R.id.deletemenu:

                final int[] myitemsid = getSelectedID();
                final MemoDBHelper helper = new MemoDBHelper(getActivity());
                AlertDialog.Builder myAlert = new AlertDialog.Builder(
                        getActivity());
                myAlert.setMessage(
                        "Are you sure to delete " + myitemsid.length
                                + " memo ?")
                        .setPositiveButton("yes", new OnClickListener() {

                            @Override
                            public void onClick(DialogInterface dialog,
                                    int which) {

                                for (int j = 0; j < myitemsid.length; j++) {
                                    helper.deleteRow(myitemsid[j]);
                                    /*
                                     * if (j == myitemsid.length - 1) {
                                     * strid[j] = String
                                     * .valueOf(myitemsid[j]); } else {
                                     * strid[j] = String
                                     * .valueOf(myitemsid[j]) + ","; }
                                     */
                                }

                                mode.finish();
                                onResume();
                            }
                        }).setNegativeButton("no", new OnClickListener() {

                            @Override
                            public void onClick(DialogInterface dialog,
                                    int which) {
                                mode.finish();

                            }
                        });
                AlertDialog alert = myAlert.create();
                alert.show();
                // mode.finish();

                break;
            case R.id.MoveTomenu:

                // myadp.getItem(position);
                Intent i = new Intent(getActivity(),
                        MoveToCategory_act.class);
                i.putExtra("categoryid", CategoryID.Urgent_Imprtant_ID);
                startActivityForResult(i, RQS_MoveTo);
                mode.finish();
                break;
            }
            return true;
        }

        // get selected id to delete and move category

        @Override
        public void onItemCheckedStateChanged(ActionMode mode,
                int position, long id, boolean checked) {
            if (myadp == null) {
                myadp = asyn.getlistAdapter();
            }

            int p = ifMemoSelectedBefore(myadp.getItem(position));
            if (p != -1) {

                selectedMemoArray.remove(p);

            } else if (checked) {
                selectedMemoArray.add(myadp.getItem(position));

            }
            final int checkedCount = list.getCheckedItemCount();
            switch (checkedCount) {
            case 0:
                mode.setSubtitle(null);
                break;

            case 1:
                mode.setSubtitle("One Item Selected");
                break;
            default:
                mode.setSubtitle(checkedCount + " Item Selected");
                break;
            }
        }
    });

    getActivity().getActionBar().setSubtitle("subtitle");
}

public int ifMemoSelectedBefore(memo m) {
    return selectedMemoArray.indexOf(m);

}

@Override
public void onViewCreated(View view, Bundle savedInstanceState) {
    // TODO Auto-generated method stub
    super.onViewCreated(view, savedInstanceState);

    list = (ListView) view.findViewById(R.id.Urgent_Important_list);

    // -------------click item
    list.setOnItemClickListener(new OnItemClickListener() {

        @Override
        public void onItemClick(AdapterView<?> arg0, View arg1,
                int position, long arg3) {
            if (myadp == null) {
                myadp = asyn.getlistAdapter();
            }
            // Log.d("tag", myadp.getItem(position).GetTitle() + "");
            Intent nextintent = new Intent(getActivity(),
                    EditMemo_act.class);
            memo g = myadp.getItem(position);
            /*
             * MemoDBHelper helper = new MemoDBHelper(getActivity());
             * helper.updateStatusByID(g.GetID(), true);
             */
            nextintent.putExtra("editmemo", g);
            startActivity(nextintent);

        }
    });

}

@Override
public void onResume() {
    asyn = new AsyncTaskDB(getActivity(), CategoryID.Urgent_Imprtant_ID);
    asyn.execute();
    super.onResume();
}

public int[] getSelectedID() {
    int[] SelectedArray_ID = new int[selectedMemoArray.size()];
    for (int j = 0; j < selectedMemoArray.size(); j++) {

        SelectedArray_ID[j] = selectedMemoArray.get(j).GetID();
        // Log.d("id", selectedMemoArray.get(j).GetID() + "");

    }
    return SelectedArray_ID;
}

//-------------a method to notifymyadpter
    public static void notifyAdapter() {
        if (myadp != null) {
            myadp.notifyDataSetChanged();
            Log.d("notify", "here");
        }
}

@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    if (requestCode == RQS_MoveTo) {
        if (resultCode == Result.RESULT_OK) {

            int id = data.getExtras().getInt("NEWCategoryID");
            MemoDBHelper helper = new MemoDBHelper(getActivity());
            final int[] myitemsid = getSelectedID();
            for (int j = 0; j < myitemsid.length; j++) {
                helper.updateCategory(myitemsid[j], id);

            }

            onResume();

        }
    }
}

}
is there any method in fragment to run after adapter changed?or in myadapter ,after db updated i call a method in fragment to notify data changed ? i think the second solution isn't right >_<
p.s:notifyAdapter() doesn't work,is it because my adapter fill in asyntask ?

A: When the adapter changed, try to call below method.
Once you use FragmentPagerAdapter or ListView, when you change the data, you should call this.
notifyDataSetChanged();

read about it : notifyDataSetChanged


text:
Q: How can I add a running total of one column to an Access query? I have a query that contains in one field the percentage of total sales corresponding to a specific product in the past 12 months. For example:
Product 1 - 38%
Product 2 - 25%
Product 3 - 16%
(...)
The records are sorted in descending order by the percentage column, and the sum of that has to be 100%. I want to create a new column that adds the previous percentages as a running total, like this:
Product 1 - 38% - 38%
Product 2 - 25% - 63%
Product 3 - 16% - 79%
(... until it reaches the last product and a 100% sub-total)
How could I do this?

A: If you have an ID field, or a date field, you can use a variation of this correlated subquery.
SELECT t.*,
     t.productpct+[prev_value] AS RunningSum,

 (select sum([ProductPct])
 from test AS t2
  WHERE
  t2.ID < t.ID
 ) AS Prev_Value

FROM test AS t;

There are people who are way better at SQL than I, however if this helps or gives you your answer then great.


text:
Q: "Software update" appears empty in Debian, but there are upgrades available I'm running Debian 7 on vmware workstation. When I run Applications - System Tool - Software Update I just get a blank window, nothing happens.
Updating the system works fine with "apt-get update && apt-get -u dist-upgrade".
But when I do this, I get a GUI window with "Could not get update, failed to process request - more details: Operation was cancelled".
I'm running gnome as a normal user (not root).
Not able to find anything interesting in /var/log/*
Anyone got any ideas what's causing this?

A: When I was having a similar issue with Debain 7.4 "Wheezy", it seemed to be with the gnupg setup.
When I ran apt-key update for the first time, it failed with errors about no central gpg skeleton, I think was the error (Sorry it escapes me now..)
So, I installed the gnupg2 package:

*

*su -c 'apt-get install gnupg2'
Then to generate all the necessary configuration in your ~/.gnupg directory, I manually started the gpg-agent:

*

*gpg-agent --daemon
I was then able to update the local APT keyring:

*

*su -c 'apt-key update'
Hopefully that will get you on your way, or at least give you a place to start. Good luck!

A: I saw the issue of Software Update not showing available updates.
It seems to be a bug:
https://bugs.debian.org/cgi-bin/bugreport.cgi?bug=702241
https://bugs.debian.org/cgi-bin/bugreport.cgi?bug=678340
As a workaround, I tried installing the package "update-notifier" for the package "update-manager-gnome".  I ran the Update Manager (Applications - System Tools Administration - Update Manager) and it let me find updates and install them.
I don't know about the "Could not get update, failed to process request - more details: Operation was cancelled" part of your question.


text:
Q: What exception type should I raise if my dictionary is missing required keys? I am testing that data (dictionary), used in Django's render(request, url, data), has some required keys. I will raise an exception if the required keys are missing. What exception type is best suited for this?
Is there a better way to think about this?

A: For consistency with regular dicts, I would think a KeyError would be appropriate
>>> d = {'foo': 'bar'}
>>> d[5]
Traceback (most recent call last):
  File "<pyshell#1>", line 1, in <module>
    d[5]
KeyError: 5

KeyError

Raised when a mapping (dictionary) key is not found in the set of existing keys.