text:
Q: python share thread-objects in manager.dict() between 2 processes I want to share a dict of thread-objects between 2 processes. I have also another dict of objects which seems to work at the moment.
The problem is that it raises an exception when I try to add key/value pairs to the dict (key is an integer and value is the thread-object):
Exception with manager.dict()
    TypeError: can't pickle _thread.lock objects

I try to switch from manager.dict() to manager.list(), it does not work either:
Exception with manager.list()
    TypeError: can't pickle _thread.lock objects

The readFiles() function is working correctly.
I use python 3.5.1 (Anaconda)
def startAlgorithm(fNameGraph, fNameEnergyDistribution, fNameRouteTables):
    global _manager, _allTiesets, _allNodes, _stopDistribution

    _manager = Manager()
    _allTiesets = _manager.dict()
    _allNodes = _manager.dict()

    _stopDistribution = Value(c_bool, False)

    readFiles(fNameGraph, fNameEnergyDistribution, fNameRouteTables)
    initializeAlgorithm()

    procTADiC = Process(target=TADiC, args=(_stopDistribution, _allNodes))
    procTA = Process(target=TIESET_AGENT, args=(_stopDistribution, _allNodes, _allTiesets))
    procTADiC.start()
    procTA.start()

    procTADiC.join()
    procTA.join()

def initializeAlgorithm():
    global _graphNX, _routingTable, _energyDistribution, _energyMeanValue

    #Init all Nodes
    allNodeIDs = _graphNX.nodes()
    energySum = 0
    for node in allNodeIDs:
        nodeEnergyLoad = float(_energyDistribution.get(str(node)))
        nodeObj = Node(node, nodeEnergyLoad)
        _allNodes[node] = nodeObj
        energySum = energySum + nodeEnergyLoad

    #Calculate the mean value from the whole energy in the graph
    _energyMeanValue = energySum / len(allNodeIDs)

    #Init all Tieset-Threads
    for tieset in _routingTable:
        tiesetID = int(tieset['TiesetID'])
        connNodes = list(tieset['Nodes'])
        connEdges = list(tieset['Edges'])
        adjTiesets = list(tieset['AdjTiesets'])
        tiesetThread = Tieset(tiesetID, connNodes, connEdges, adjTiesets)
        _allTiesets[tiesetID] = tiesetThread        # Raise Exception!!!!!!!!!!

class Node:
    'Node-Class that hold information about a node in a tieset'

    def __init__(self, nodeID, energyLoad):
        self.nodeID = nodeID
        self.energyLoad = energyLoad
        self.tiesetFlag = False

class Tieset(threading.Thread):
    'Tieset-Class as Thread to distribute the load within the tieset'

    def __init__(self, tiesetID, connectedNodes, connectedEdges, adjTiesets):
        threading.Thread.__init__(self)
        self.tiesetID = tiesetID
        self.connectedNodes = connectedNodes
        self.connectedEdges = connectedEdges
        self.adjTiesets = adjTiesets
        self.leaderNodeID = min(int(n) for n in connectedNodes)
        self.measureCnt = 0

    def run(self):
        print('start Thread')

A: What I can say that you can't share threads between processes, you can share arguments for those threads if you want to start them in different processes, or you can share some results. The problem you are seeing caused by nature of that process creation, in python all the parameters will be serialized in your current process, then passed to a new one, and then python will deserialize them there to run the "target". Apparently, thread object is not serializable (you can check this interesting thread to understand serialization problem debugging pickle).


text:
Q: How to check login information against a db using PDO and Phpass I'm trying to check users hashed passwords against the ones I've saved in the database. It is almost the same issue as the this guy, but I'm trying to do it with PDO and I'm unsure how to get the hashed password from the database to check it against. Here is my code for the login page so far:
<?php
ini_set('display_errors', 1);
error_reporting(E_ALL); ini_set('display_errors', 1);

require_once "/home/carlton/public_html/PHPproject/includes/PasswordHash.php";

if ($_POST){
$form = $_POST;
$username = $form['username'];
$password = $form['password'];

try{
    $db = new PDO('mysql:host=localhost;dbname=phpproject', 'root', 'pdt1848!');
    $db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
    catch(PODException $e){
        echo "Can't connect to the database";
    }
$sql = "SELECT * FROM users WHERE username=:username";
$query = $db->prepare($sql);
$query->execute(array(':username'=>$username, ':password'=>$stored_hash));
$results = $query->fetchAll(PDO::FETCH_ASSOC);

$check = $hash_obj->CheckPassword($password, $stored_hash);
if($check){
    print_r("Registered user");
}
else{
    print_r("Not a registered user");
}

//login here
}
else{
?>
<form name="login" action="login.php" method="POST">
Username:
<input type="text" name="username"/>

Password:
<input type="password" name="password"/>

<button type="submit">Submit</button>
<button type="reset">Reset Form</button>
</form>
<?php
}
?>

A: That's simple.
You have to select stored password first and then verify it.

A: Pseudocode:
$q=$db->prepare('SELECT * FROM usertable WHERE username=? AND passwordhash=?');

$thehashvalue=calc_hash_of_password_according_to_your_agorithm($params);
$theusername=the_username_that_was_posted();

$q->execute(array($theusername, $thehashvalue));

$lastlogin=null;
while($r=$q->fetch(PDO::FETCH_ASSOC)) {
   # successfully authenticated
   $lastlogin=$r['lastlogin']; ## example. assumes a "lastlogin" column on "usertable"
}

if(!empty($lastlogin)) {
   # user is logged in
}else{
  # login failed
}

The hash calc function could be as simple as md5($posted_passwd) but it is good practise to salt the hash so the same password makes different hashes for different users and/or on different systems. Just make sure you use the same hash function when storing the password hash in the database.

A: You're really just comparing the hashed password you have in your DB matches the inputted password, once it too is similarly hashed.

*

*Firstly, don't use the root account to access your DB

*Try to avoid SELECT * - just select the columns you actually need.

*The number of tokens (:username) must equal the number of bound params (':username'=>$username) in your query. Otherwise PDO will throw an error.

*You have not posted the class that is handling the password verification itself, but it's basically just hashing the input and comparing the two, returning a bool.

*Incidentally, print_r is to echo out the values of variables, arrays in particular. If you're just echoing a string as a response, then just print or echo is fine.

A: Here is my working code for the login in case anyone else comes looking with a similar problem. The information I was looking for is at line 20, starting with $response. That allowed me to grab the password from the database, which I set equal to $stored_hash. I could then compare it using the CheckPassword function from PHPass.
<?php
session_start();
ini_set('display_errors', 1);
error_reporting(E_ALL); ini_set('display_errors', 1);

require "/home/carlton/public_html/PHPproject/includes/PasswordHash.php";

if ($_POST){
    $form = $_POST;
    $username = $form['username'];
    $password = $form['password'];
    $hash_obj = new PasswordHash(8, false);

    try{
        $db = new PDO('mysql:host=localhost;dbname=phpproject', 'carl', 'pdt1848?');
        $db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    }
        catch(PODException $e){
            echo "Can't connect to the database";
        }
    $response = $db->query("SELECT password FROM users WHERE username='$username'");
    $data=$response->fetch();
    $stored_hash = $data['password'];

    $check = $hash_obj->CheckPassword($password, $stored_hash);
    if($check){
        echo "Login successful!";
        $_SESSION['logged_in'] = true;
    }
    else{
        echo "Authentication failed. Please try again.";
    }

    //login here
}
else{
?>
<form name="login" action="login.php" method="POST">
    Username:
    <input type="text" name="username"/>

    Password:
    <input type="password" name="password"/>

    <button type="submit">Submit</button>
    <button type="reset">Reset Form</button>
</form>
<?php
}
?>

redpajama_set_name: RedPajamaStackExchange


text:
Q: Reading and writing to internal android xml file using DOM parser I am new to Android I am trying to read and write some information from and to xml file in Android. I thought it would be possible if I use DOM parser to do such stuff... I am reading file at the beggining of an application to get the data and trying to save before the application terminates to store configuration changes. I figured out how to read file from raw/xml but it seems to be a real pain (or even impossibility) to save modifyied xml back here...
Maybe I am taking wrong approach, but I believe it should be possible to somehow modify some internal xml file in Android. How to go about it?

A: You can not modify or update raw/xml file directory. Android /res directory is Read-Only. So you can only read file from it not write back allowed. (As Android .apk file has Read-Only permission).

A: u cant modify xml stored in xml folder of android app.u need to copy that file while installing app on device to sdcard/internal storage and modify it.In that case u may use Dom Parser for reading and writing xml file from sdcard/internal storage of device.

A: @user370305  is right!!
simply logic is that you cannot create a file at runtime internally in the storage (raw,asset,layout etc.) So you can create a different file externally by giving the permission "write_external_storage".  Then you can read or write.
Here is an example
   public void readXML() throws IOException{

         //get the xml file from the raw folder
        InputStream is = getResources().openRawResource(
                    R.raw. config );

        Resources r = getResources();
        AssetManager assetManager = r .getAssets();

         //then write the dummy file
        File f = new File(Environment.getExternalStorageDirectory(), "dummy.xml" );
        OutputStream os = new FileOutputStream(f , true);

         final int buffer_size = 1024 * 1024;
         try
        {
            byte [] bytes = new byte [buffer_size ];
            for (;;)
            {
                int count = is.read( bytes, 0, buffer_size );
                if (count == -1)
                    break ;
                os.write( bytes , 0, count );
            }
            is.close();
            os.close();
        }
         catch (Exception ex )
        {
            ex.printStackTrace();
        }

         //then parse it
                    parseConfigXML( f);

  }

   public String parseConfigXML(File configXML ) {

        XmlPullParser xpp = null ;
         String httpUrl= "";
        FileInputStream fis ;
        XmlPullParserFactory factory = null ;
         try {

               fis = new FileInputStream( configXML);
               factory = XmlPullParserFactory.newInstance();
               factory .setNamespaceAware( true);
               xpp = factory .newPullParser();
               xpp .setInput( new InputStreamReader( fis));

               int eventType = xpp.getEventType();
               while (eventType != XmlPullParser. END_DOCUMENT) {
                     if (eventType == XmlPullParser. START_DOCUMENT) {

                    } else if (eventType == XmlPullParser. START_TAG) {

                    } else if (eventType == XmlPullParser. END_TAG) {

                    } else if (eventType == XmlPullParser. TEXT) {

                           httpUrl += xpp .getText().replace( "\n", "" );

                    }
                     eventType = xpp .next();
              }
        } catch (FileNotFoundException e1 ) {
               // TODO Auto-generated catch block
               e1.printStackTrace();
        } catch (XmlPullParserException e ) {
               // TODO Auto-generated catch block
               e.printStackTrace();
        } catch (IOException e ) {
               // TODO Auto-generated catch block
               e.printStackTrace();
        }

         return httpUrl .trim().replace( "\n", "" );
  }


text:
Q: End to end example of CQRS implementation on top of AppEngine All of the infrastructure components required to implement a CQRS based application seem to be out of the box within AppEngine.
Unfortunately, I can't find anything related to this subject.
Few possible reasons

*

*It's a well kept secret beyond "Architecture Astronauts"

*It's a worthless overkill architecture because AppEngine scales out "by design"

*It's not mainstream yet

However, even if no complete code is available, provided anyone has hints, bits of targeted code, pros/cons regarding CQRS on top of AppEngine, I'd be greatly honored to benefit from your knowledge.
Thanks in advance.
Note 1: At least, a similar project exists in the .Net ecosystem (Lokad-CQRS which targets Windows Azure)
Note 2: Even if I'm rather python inclined, answers related to Java experience are welcome

A: Hi there, this is not on AppEngine, however it is generic enough to help you get started:

*

*Greg Young - Simplest Possible Thing The basic concepts

*Mark  Nijhof - Fohjin Really good sample, I found this one easier to follow first

Also, I think this dude http://www.harukizaemon.com/ was trying some CQRS with Ruby, again not Python. But this could work as a guideline if you decide to go the Python way.
BTW, the Google group DDD/CQRS is really active and might be of help.
Cheers


text:
Q: itextsharp paragraph chunk font being over written by list default font I'm using v5.2.1 of the open source iTextSharp.  I have a section of code that is behaving not as expected. For some reason when I stream the pdf to the browser the font is different.
Below is a representation of what I'm trying to do.
Font times_roman = new Font(Font.FONTFAMILY.TIMES_ROMAN, 9f);
float indent1 = 20f;

try
{

   foreach (var item in List)  {

        Chunk c1 = new Chunk(string.format("Item: {0}\n\n" item.Name, times_roman));
        Phrase ph1 = new Phrase(c1);
        Paragraph p1 = New Paragraph(ph1);
        doc.Add(p1);

        Chunk c2 = new Chunk(string.format("(1) Item  Category{0}:\n\n" item.Category, times_roman));
        Phrase ph2 = new Phrase(c2);
        Paragraph p2 = New Paragraph(ph2);
        p2.FirstLineIndent = indent1;
        doc.Add(p2);

  }
}
catch
{
}

I then stream the pdf so it will open automatically in IE8 or IE9.
No matter what I try I always get the following results, no matter what font setting I put on c2, ph2, p2
Item: MyWidget1 (this dislays Times Roman)

(1) Item Category:  Utility Tool (this displays as Helvetica 12)

It's as if iTextSharp considers it a ListItem because the of the (1) and is going to take control no matter what you do.
I cannot use Lists and ListItem because I only need to indent the first line and itextsharp lists will indent multiple lines and line them up automatically.  I have many items that have text that will wrap to half a page.
I really like the iTextSharp library (since it's free) but this feature is driving me nuts.


text:
Q: ClientKeyExchange does not happen after ServerHelloDone I have two laptops running the same project on them. Both instances are configured to use Java JDK 6 (same minor version). However one machine is not able to connect to a remote REST service. By running applications with -Djavax.net.debug=all option I came to the conclusion that the issue is with the ClientKeyExchange step as this step does not happen on the problematic laptop.
A post in the IBM developer community suggests that "hardware crypto device being used is not on the supported list". However I have no understanding about "hardware crypto devices".
What I can tell is that "enabled cipher suites", "excluded cipher suites", "cipher suites have been set to" lists printed by means of -Djavax.net.debug=all are the same on both machines.
Using JDK cacerts.

A: Found the solution. Project is using JAX-RS so calls to external service happened through that framework and because of that I could not dig to the problem since there were no errors. So I tried different approach: tried to access the service by using simple javax.net.ssl.HttpsURLConnection which showed me java.lang.NoClassDefFoundError: Could not initialize class javax.crypto.SunJCE_b and therefore I changed my local_policy.jar and US_export_policy.jar files (thanks to @Charlie Could not initialize class javax.crypto.SunJCE_b)
I think I had changed policy jars on first laptop and forgot to do this on the new laptop.


text:
Q: Access personal geodatabase using Java Following example through ESRI is to access the features of file geodatabase (GDB), I would like to know that is there a similar way to do this with personal geodatabase (MDB) using Java.
I am quite new to ArcObjects so if anybody could point me to right direction.

A: You can use the AccessWorkspaceFactory instead. There are (at least) 3 ways to connect to a personal geodatabase. The simplest is probably the IWorkspaceFactory.OpenFromFile method, e.g.:
//For example, pathToFile= "C:\\myData\\mypGDB.mdb".
static IWorkspace openFromFile_pGDB_Workspace(String pathToFile)throws Exception{
    IWorkspaceFactory workspaceFactory = new AccessWorkspaceFactory();
    return workspaceFactory.openFromFile(pathToFile, 0);
}

See How to connect to a geodatabase in the conceptual help for more information.
You might also look at the various IGPUtilities helper methods if you want to deal with opening workspaces, feature classes, tables, etc. in a more generic way.


text:
Q: ZSH: Output from stdout from within while read gets lost I ran into a weird ZSH issue. I have trimmed the script to the smallest form that still reproduces the issue.
What I'm simulating here, is monitoring a directory for changes via a subprocess (the actual script uses fswatch). Because I'm monitoring, it means I cannot run a command beforehand and save the output. A (working) example is the following:
(echo "text.txt"; echo "text.txt") | while read filepath; do scp "$filepath" "trip:~/tom/"; echo $?; done
text.txt                    100%  822    51.1KB/s   00:00
0
text.txt                    100%  822    99.1KB/s   00:00
0

Now, when I add a delay in the middle, seemingly any delay that is longer than the runtime of the scp command inside the while-loop, suddenly the second output and any subsequent command of scp will not visible:
(echo "text.txt"; sleep 2; echo "text.txt") | while read filepath; do scp "$filepath" "trip:~/tom/"; echo $?; done
text.txt                    100%  822    51.1KB/s   00:00
0
0

Interestingly enough, the echo still works and errors show up like you may expect.
(echo "doesnotexist.txt"; sleep 2; echo "doesnotexist.txt") | while read filepath; do scp "$filepath" "trip:~/tom/"; echo $?; done
doesnotexist.txt: No such file or directory
1
doesnotexist.txt: No such file or directory
1

What is going on here? I hope someone can help me clear this up. Thank you!
Edit:
After some more fiddling, it appears this has something to do with ZSH, as it works in a normal bash-shell.

A: Running the whole while loop in a subshell does not have the problem. This seems work:
(echo "text.txt"; sleep 2; echo "text.txt") | (while read filepath; do scp "$filepath" "trip:~/tom/"; echo $?; done)

Some digging in the scp source revealed that the non-output is caused by this check returning false: progressmeter.c#L81-L85
static int
can_output(void)
{
    return (getpgrp() == tcgetpgrp(STDOUT_FILENO));
}

(I.e. the process group id of the scp process suddenly being different from the "foreground process group on the terminal associated to stdout").
One difference between bash and zsh is that zsh runs while loops in the main shell process, while bash does not (which I gleaned from here). But this is as far as I am able to dig right now.


text:
Q: Program skips to end after first input hey guys so I have a pizza program that gathers weight name and size using a structure and allocates the memory dynamically. My problem comes after the user inputs a number for the diameter. My code looks like this
#include <iostream>
#include <cmath>
#include <cstring>
using namespace std;

int main()
{
  struct pizza
  {
    char name[15];
    float diameter;
    int weight;
  };
  pizza *user= new pizza{};

  cout << "Hello please enter some information about your pizza" << endl;
  cout << endl << "Diameter: ";

  cin >> user->diameter;
  cout << "company name: ";
  cin.get(user->name,15);
  cout << endl << "Weight: ";
  cin >> user->weight;

  cout << "here is the information that we have assembled about your pizza company" << endl;
  cout << "Company name: "<< user->name <<e ndl;
  cout << "diameter: " << user->diameter << endl;
  cout << "weight: " << user->weight << endl;
  return 0;
}

when I run the program it looks like this
Hello please enter some information about your pizza
Diameter: 40
company name:
Weight: here is the information that we have assembled about your pizza company
Company name:
diameter: 40
weight: 0

A: what appears is that you haven't used the code for clearing the buffer.
What is buffer?
Temporary storage area is called buffer. All standard input and output devices contain input and output buffer. In standard C/C++, streams are buffered, for example in case of standard input,when we press the key on keyboard,it isn't send to your program, rather it is buffered by operating system till the time is allotted to the program.
How does it effect Programming?
On various occasions you may need to clear the unwanted buffer so as to get the next input in the desired container and not in the buffer of previous variable.
cin.clear();
fflush(stdin);

This is the code you need to add in your program.
int main()
{
struct pizza
{
 char name[15];
 float diameter;
 int weight;

 };

 pizza*user= new pizza{
 };
 cout<<"Hello please enter some information about your pizza"<<endl;
 cout<<endl<<"Diameter: ";

 cin>>user->diameter;
 cout<<"company name: ";
 cin.clear();    //for clearing the input buffer
fflush(stdin);

cin.get(user->name,15);

cout<<endl<<"Weight: ";
cin.clear();
fflush(stdin);

cin>>user->weight;

cout<<"here is the information that we have assembled about your pizza
company"<<endl;
cout<<"Company name: "<<user->name<<endl;
cout<<"diameter: " <<user->diameter<<endl;
cout<<"weight: "<<user->weight<<endl;
return 0;

}

after encountering"cin" statement, we require to input a character array or a string , we require to clear the input buffer or else the desired input is occupied by buffer of previous variable, not by the desired container.On pressing "Enter" (carriage return) on output screen after the first input , as the buffer of previous variable was the space for new container(as we did'nt clear it) , the program skips the following input of container.


text:
Q: Changing value on a label with UISlider control in WePopoverControler I am in a process of implementing WePopovercontroller in my app and I have a question on how to implement uislider on it.  I am able to show the slider in the UIView and get the action when slider moved but not sure how to set the value of the label in that view. Here is the part of the code
-(void)popoverSliderMoved:(UISlider *) sender{
    NSLog(@"slider %f",sender.value);
}

-(IBAction)showSettingsMenu:(UIButton *)sender{

if(!self.popoverSettingsController) {
    // Create a label and button for the popover
    UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 100, 40)];
    [label setText:@"Bookmark it!"];
    [label setBackgroundColor:[UIColor clearColor]];
    [label setTextColor:[UIColor whiteColor]];
    [label setTextAlignment:UITextAlignmentCenter];
    UISlider *slider = [[UISlider alloc]initWithFrame:CGRectMake(0, 45, 100, 40)];
    [slider addTarget:self action:@selector(popoverSliderMoved:) forControlEvents:UIControlEventValueChanged];
    UIFont *font = [UIFont boldSystemFontOfSize:20];
    [label setFont:font];
    CGSize size = [label.text sizeWithFont:font];
    CGRect frame = CGRectMake(0, 0, size.width + 10, size.height + 10); // add a bit of a border around the text
    label.frame = frame;

    UIButton *button = [[UIButton alloc] initWithFrame:label.frame];
    [button addSubview:label];
    [button addTarget:self action:@selector(popoverButtonPressed:) forControlEvents:UIControlEventTouchUpInside];

    UIViewController *viewCon = [[UIViewController alloc] init];
    [viewCon.view addSubview:slider];
    [viewCon.view addSubview:button];
    CGRect popOverFrm = CGRectMake(0, 0, frame.size.width + slider.frame.size.width, frame.size.height + slider.frame.size.height);
    viewCon.contentSizeForViewInPopover = popOverFrm.size;//CGSizeMake(100, 36);

    NSLog(@"Label Frame: %@", NSStringFromCGRect(label.frame));
    NSLog(@"Popover size: %@", NSStringFromCGSize(viewCon.contentSizeForViewInPopover));
    NSLog(@"ViewCon: %@", NSStringFromCGRect(viewCon.view.frame));

    self.popoverSettingsController = [[WEPopoverController alloc] initWithContentViewController:viewCon];

    //[self.popoverSettingsController setDelegate:self];
}

if([self.popoverSettingsController isPopoverVisible]) {
    [self.popoverSettingsController dismissPopoverAnimated:YES];
   // [navPopover setDelegate:nil];
    self.popoverSettingsController = nil;
} else {

    [self.popoverSettingsController presentPopoverFromRect:CGRectMake(sender.frame.size.width, 0, 200, 57)
                                inView:self.navigationController.view
              permittedArrowDirections:UIPopoverArrowDirectionUp | UIPopoverArrowDirectionDown
                              animated:YES];
}
}

Would i need to use a delegate in this case or a property for this viewcontroller to set the label.
Thanks!!!

A: Yes using a property would be what I would do.


text:
Q: How can I install MinGW-w64 and MSYS2? I am trying to build some open source library. I need a package management system to easily download the dependencies. At first I am using MinGW and MSYS. But the included packages are limited. Someone told me to use Mingw-w64 and MSYS2.
I downloaded the mingw-w64-install from here. When running, it reports the following error. How can I fix it?

And by the way, from the Mingw-w64 download page, I see a lot of download links. Even Cygwin is listed. How are Cygwin and Mingw-w64 related?

My current understanding is, in the time of MinGW and MSYS, MSYS is just a nice addon to MinGW, while in Mingw-w64 + MSYS2, MSYS2 is stand-alone and Mingw-w64 is just a set of libraries it can work with. Just like Cygwin can download many different packages.

A: MSYS has not been updated a long time. MSYS2 is more active, and you can download it from MSYS2. It has both the mingw and cygwin fork package.
To install the MinGW-w64 toolchain (reference):

*

*Open the MSYS2 shell from the start menu

*Run pacman -Sy pacman to update the package database

*Reopen the shell, and run pacman -Syu to update the package database and core system packages

*Reopen the shell, and run pacman -Su to update the rest

*Install the compiler:

*

*For a 32-bit target, run pacman -S mingw-w64-i686-toolchain

*For a 64-bit target, run pacman -S mingw-w64-x86_64-toolchain

*Select which package to install; the default is all

*You may also need make. Run pacman -S make

A: Unfortunately, the MinGW-w64 installer you used sometimes has this issue. I myself am not sure about why this happens (I think it has something to do with Sourceforge URL redirection or whatever that the installer currently can't handle properly enough).
Anyways, if you're already planning on using MSYS2, there's no need for that installer.

*

*Download MSYS2 from this page.

*After the install completes, click on the MSYS2 UCRT64 in the Start menu (or C:\msys64\ucrt64.exe).
If done correctly, the terminal prompt will say UCRT64 in magenta letters, not MSYS.

*Update MSYS2 using pacman -Syuu. If it closes itself during the update, restart it and repeat the same command to finish the update.
You should routinely update your installation.

*Install the toolchain: (i.e. the compiler and some extra tools)
pacman -S mingw-w64-ucrt-x86_64-toolchain

*Install any libraries/tools you may need. You can search the repositories by doing
pacman -Ss name_of_something_i_want_to_install

e.g.
pacman -Ss gsl

and install using
pacman -S package_name_of_something_i_want_to_install

e.g.
pacman -S mingw-w64-ucrt-x86_64-gsl

and from then on the GSL library will be automatically found by your compiler!
Make sure any compilers and libraries you install have this package prefix: mingw-w64-ucrt-x86_64-. Only use unprefixed packages for misc command-line utilities (such as grep, sed, make, etc), unless you know what you're doing.

*Verify that the compiler is working by doing
gcc --version

If you want to use the toolchains (with installed libraries) outside of the MSYS2 environment, all you need to do is add C:/msys64/ucrt64/bin to your PATH.
MSYS2 provides several compiler flavors, UCRT64 being one of them. It should be a reasonable default.

A: You can now also get the stand-alone personal build of MinGW-w64 from https://winlibs.com/ which doesn't require any installation; just extract and its ready to use. This allow having multiple toolchains on the same system (e.g., one for Windows 32-bit and another for Windows 64-bit).

A: The most straightforward way, as far as I know, is to use Chocolatey to install MinGW:
choco install mingw

Then check with the command whereis gcc. It is going to be installed in C:\ProgramData\chocolatey\bin.
one more thing, to get make working, just copie (or rename if you wish)
with copy mingw32-make.exe make.exe in C:\ProgramData\chocolatey\bin.


text:
Q: Can I use custom @font-face font with same name as built-in font? If I have a custom font and I call it 'verdana', will that conflict with the browser's built-in verdana font? When I do:
font-family: 'verdana';

will the browser use my custom font or the built-in one?

A: Yes, you can use a custom font name that may coincide with the name of an installed font. It might be confusing, though, and might look suspicious (using a font illegally) to use a name like Verdana, if someone peeks at your code.
The CSS3 Fonts draft says: "If the font family name [in @font-face] is the same as a font family available in a given user's environment, it effectively hides the underlying font for documents that use the stylesheet. This permits a web author to freely choose font-family names without worrying about conflicts with font family names present in a given user's environment."

A: You may find parts of this article interesting: http://www.practicalecommerce.com/articles/3080-How-Browsers-Manage-Fonts.
The short answer is that the browser should use whatever version of Verdana you have installed. The exception here is if you are using "src: url()", then it should load the font file from that URL. A good resource if that is the case: http://www.html5rocks.com/en/tutorials/webfonts/quick/.
If you're wanting to use your font and you worry that some browsers may just up and decide to use the local Verdana, you can rename the ttf or eot on your server and just use Verdana-Mine as the font-family and src as url('verdana-mine.ttf').


text:
Q: Turning JSON into dataframe with pandas I'm trying to get a data frame but keep running into various error messages depending on the arguments I specify in read.json after I specify my file.
I've run through many of the arguments in the pandas.read_json documentation, but haven't been able to identify a solution.
import pandas
json_file = "https://gis.fema.gov/arcgis/rest/services/NSS/OpenShelters/MapServer/0/query?where=1%3D1&outFields=*&returnGeometry=false&outSR=4326&f=json"
pandas.read_json(json_file)

I'm trying to get a data frame but keep running into various error messages depending on the arguments I specify in read.json after I specify my file.

A: Because the JSON is not directly convertible to DataFrame. read_json works only with a few formats defined by the orient parameter. Your JSON doesn't follow any of the allowed formats so you need to manipulate the JSON before converting it to a data frame.
Let's take a high level look at your JSON:
{
    "displayFieldName": ...,
    "fieldAliases": {...},
    "fields": {...},
    "features": [...]
}

I'm gonna fathom a guess and assume the features node is what you want. Let's div deeper into features:
"features": [
    {
        "attributes": {
            "OBJECTID": 1,
            "SHELTER_ID": 223259,
            ...
        }
    },
    {
        "attributes": {
            "OBJECTID": 2,
            "SHELTER_ID": 223331,
            ...
        }
    },
    ...
]

features contains a list of objects, each having an attributes node. The data contained in the attributes node is what you actually want.
Here's the code
import pandas as pd
import json
from urllib.request import urlopen

json_file = "https://gis.fema.gov/arcgis/rest/services/NSS/OpenShelters/MapServer/0/query?where=1%3D1&outFields=*&returnGeometry=false&outSR=4326&f=json"
data = urlopen(json_file).read()
raw_json = json.loads(data)
formatted_json = [feature['attributes'] for feature in raw_json['features']]

formatted_json is now a list of dictionaries containing the data we are after. It is no longer JSON. To create the data frame:
df = pd.DataFrame(formatted_json)


text:
Q: Cache ruining Jquery Code? My problem might be naive, but basically I have a simple Jquery script running on a site to determine the margin height of divs based on the contained image's height:
<script type="text/javascript">

 $('.artobject').css('margin-bottom',$('.img-wrap').height());

</script>

The problem is that it runs once, but after the page is reloaded the code begins working differently. I believe this is a cache issue, but honestly have no idea. i've tried various different cache clearing codes, but to no avail.
The site where this code is applied is http://jessiama.com/elzie/index.html.

A: It could be your images aren't loaded by the time your code runs.  Try putting your code in a window.load function and see if that works.

$(window).load(function()
{
    $('.artobject').css('margin-bottom',$('.img-wrap').height());
});

</script>

Updated after Terry reminded me it wasn't document.ready.


text:
Q: Distinguish multiple requests in Jersey Request Filter I have a class which implements ContainerRequestFilter and ContainerResponseFilter. I am using this class to log the request and the corresponding response to it.I note the start_time in request filter and propagate this to the response filter using MDC.put("start-time",start_time).
I can see that since the response filter takes the ContainerRequestContext as the argument , it is able to map the response to the correct request.
But I am not able to see how the logging filter class is able to distinguish between multiple request calls which would be coming simultaneously. Does each request make a different instance of the logging filter class ?

A:
Does each request make a different instance of the logging filter class ?

No. So trying to store member state is not an option. What you should do is use the ContainerRequestContext to set a property on the request side. On the response side just get the property from the same context.
// request filter
filter(ContainerRequestContext request) {
  request.setProperty("key", value);
}

// response filter
filter(ContainerRequestContext request, ContainerResponseContext response) {
    Object value = request.getProperty("key");
}

Each request will get its own Container(Request|Response)Context.


text:
Q: Creation of comprehensive flowchart for using English articles I am trying to create a comprehensive flowchart for using the English articles - the, a, an. Can you check it and give me some feedback about errors, inaccuracies, possible improvements? May be some branches can be simplified/generalized? Or some good examples can be added?

A flowchart is a type of diagram that represents a workflow or
process. A flowchart can also be defined as a diagrammatic
representation of an algorithm, a step-by-step approach to solving a
task.
From Wikipedia.

The purpose:
It is hard to memorizing all article's rules in an unordered, unconnected form, so I want to have the scheme, which I can use for learning grammar rules in a convenient form, as well as a cheat list for rapidly looking in confusing cases. Also, I want to have an algorithm which I can execute step by step to get the right result (mentally or by a computer program). The scheme should have short, illustrative  examples for each rule. In fact, I have used it for writing this paragraph, how many article's mistakes I did? :)
The flowchart for facilitation of determination necessity and a type of article. I created this flowchart using an online tool, so you can view the original in a resizable form and clone it for editing: link to the flowchart (doesn't work in Firefox today, use Google Chrome).

The sources I used:

*

*Grammar: Articles.

*When to use 'the' with country names (+ lakes, rivers, and more).

*Articles - when to use 'the' | English Grammar.
Some articles with similar approach:

*

*Articles: Choosing a/an, the, or nothing (ø) with proper nouns

*Articles: Choosing a/an, the, or nothing (ø) with common nouns

*"Using an articles chart with common nouns." - the chart in the form of pdf file.
The tool I used: Online flowchart editor.

A: I think that while this chart will in many cases produce a correct answer, there are edge cases it does not catch. For example, in country names, until 1870 (Bismark's unification) the country now known as Germany was normally called "The Germanies". Cases such as "The Holy Land" do not seem properly handled. It also doesn't seem to catch when a plural countable noun should take an article:

John walked onto the lot. The cars there were all painted green.

There are no doubt other edge cases not currently covered. But more importantly, formatting this as a flowchart implies that there is always one correct answer to the question "is an article required". Often a noun or noun phrase may use or not use an article, perhaps with a change in meaning. And which nouns take articles changes over time, sometimes rather quickly, and may differ between varieties of English. Indian English, in particular, may differ from US English.
English in general has fewer rigid rules than learners used of other languages often suppose.

A: Good job, Max!
I analysed your chart and few more sources, and created another one - https://viewer.diagrams.net/?highlight=0000ff&edit=_blank&layers=1&nav=1&title=Articles+Flowchart#Uhttps%3A%2F%2Fdrive.google.com%2Fuc%3Fid%3D14ZL-2HyVhIRfkMBMP6ayLIiU7UTU_6jM%26export%3Ddownload


text:
Q: Visual Studio "Start Debugging" vs. "Attach to Process" I have a client/server application using the .Net 2.0 Framework. I'm using Visual Studio 2008 to build and manage code.
When I run either a Debug or Release version of the application simply by starting the .exe, I get an insert statement on the database that tries to insert a "0" for the foreign key of a table, triggering an error because the primary key of the other table is not 0.
When I run the application by hitting the play buttton ("Start Debugging"), the insert statement uses the correct foreign key.
In the first case, this happens even when I "Attach to Process" to the Debug version after it's started.

My question: what's the difference between attaching to the debug version of the application after it has started and starting the application from the debugger?

A: If you "Start Debugging", you'll run under the vshost.exe hosting process. This recycles the AppDomain creation, lets you debug partial trust apps, and can sandbox ClickOnce apps.
None of these features are likely causes for your bug (and vshost hasn't been much of an issue for most) - so I think this is probably a red herring.
You should probably be looking at multithreaded and timing issues related to getting the FK value instead.

A: Without more detail, it's hard to say. However, to hazard an underinformed guess, I'd bet you're seeing a timing issue (race condition or some such). For whatever reason, your server (I presume) is getting spurious data when started 'normally'. Starting it up through the IDE/debugger causes a delay that allows the client process (again, an assumption) time to get correct data to the server.

A: I know it sounds silly, but a good idea would be to check if you have the correct parameters, it is easy to forget that we add them to the debugger but not release.


text:
Q: Application of calculus to physics I am currently a 3rd year undergraduate electronic engineering student. I have completed a course in dynamics, calculus I, calculus II and calculus III.
I am very interested in mathematics and physics, however there is some clarification that I need regarding these matters as I am confused as to why we study functions, calculus and physics.
I know that mathematics is required in order to describe physics, but in many cases we require a function that describes the phenomena at hand. The major question I have is, how do we know what these functions are? I know that we make use of differential equations in order to obtain a function that represents the desired system, but this is not always the case.
For the sake of clarity I will provide a few examples that I have in mind:
(a) Take for instance Maxwell's equations, in order to apply Faraday's law we need the function describing the electric field, for Gauss' law we need a function for the magnetic flux density &/or electric displacement field etc.
(b) For Green's theorem, if we wanted to determine the flux of a vector force field within a given region we would first need the vector function of this force field.
(c) In the subject of sequences and series, how do we determine an explicit formula for the pattern describing these discrete systems, if there exists any at all and why would we need this?
In real life how do we find these functions on our own? In a calculus and physics class, we are given these functions and are required to compute the quantities at question using the appropriate theorems/formulas.
The thought of these subjects requiring us to poses a function, which we in real life do not know is causing me discomfort as I am uneasy with the idea that we first need to obtain a mathematical object, which is non trivial - we can't see a magnetic field nor can we see the function that governs it - in order to make use of these beautiful theorems. This is discouraging me from wanting to pursue further studies in the field of mathematics and physics. Where's the machine which generates these function that I need? :(

A: You are very right; expressions, formulae and laws are not given. We can derive many equations from others, but the fundamental ones - like the laws of nature - are not derived, but found or formulated.
This is the bread of a physicist.
They look out into the world and try to see patterns. When something could look like a pattern, it is tried in numerous experiments. If all results show the same pattern - then they believe this pattern to be true.
Consider Newton's 2nd law for example.
$$\sum \vec F=m\vec a$$
Someone (Newton) got the idea or observed that when something changes it's velocity (accelerates), it requires an "effort". This "effort" could we then call force and give a symbol $F$. By doing many experiments, there seems to appear a pattern - a connection between acceleration and force. If you push on an object, it accelerates, but if you push double as hard, it accelerates double as much!
Okay, so they are proportional, $\vec F \propto \vec a$. The proportionality constant is then something that causes more or less acceleration for the same force. It is some kind of a "resistance" against acceleration. Let's call that inertia or mass.
Newton didn't think exactly like this; he actually made his law as the version $\sum \vec F=\frac{d\vec p}{d t}$. But I hope this illustrates the simple one-step-at-a-time way of thinking when finding connections and patterns that will end out as laws and formulae.
Same method goes for other formulae, like for instance Coulombs law:
$$F=k\frac{q_1q_2}{r^2}$$
He had to first find out that there are two kinds of charges. That would require many tests, and eventually he would believe that there are no others, because all charges he could find behaved like one of the two. He could then call them positive and negative, just for having names for them.
He could see that they attract or repel and he would then, as Newton, have to find out how large this attracting or repelling force is compared to the two charges. He might eventually have found out that the force is proportional to each of the charges but reversely proportional to the square of the distance. And then he is close to writing it as math.
Math is here just a tool that makes it much easier to talk about the physical world. The tools that mathematicians find/develop can namely then be used on the physical formulae, when these are written as mathematical expressions.

A: In nature we can observe phenomena and measure quantities: I can measure the magnetic field of an object at different points in space and if I wait a bit also in time. With such an experiment I get a discrete set of points and now we want to understand, explain and eventually predict this distribution.
In order to do so I need a theory for the given phenomena. For electro magnetism that would be Maxwell's theorie and his equations for electro magnetism. He developed this formulars in order to describe the phenomenon of electro magnetism which we can observe in the experiment. The goal of a theory is to describe nature as we see it using as much symmetries and as less degrees of freedom as possible. We know today that in order to describe elector magnetism as compact as possible that the magnetic field (3 components) and the electric field (3 components) are not the best way to do so, because this six components are not indipendent. They may be accessable in the experiment but behind this 6 components lies a deeper meaning: We can descibe this 6 components using only 4 indipendent components (scalar+vector potential) using maxwells equations. So introducing more abstract objects or if you want to call them functions makes describing nature, as we see it, easier.
The aim of theoretical physics is to describe nature mathematically as "easy"/compact as possible making extensive use of the obvious and at first sight hidden symmetries of nature. So this sometimes means introducing new quantities which are not directly accessable in experiment. But it makes solving problems easier and sometimes it is even the only way to solve some problems.
I can give you another nice, but mathematical, example that sometimes using more abstract objects is even a necessity to solve "real life" problems. Imagine a polynomial of order 3: This is an object I can imagine in nature; I can draw its graph on a real sheet of paper. Now I want to find its roots. On a sheet of paper in "nature" I can find those just by looking on my drawn graph. But now if I want to calculate them using math I will come across a problem: It is impossible to find the roots of an abitrary polynomial of order 3 using the real numbers.  During my calculations I will come across $...\sqrt{-1}...$ and now I have a problem. I do not know what to do with that this expression $\sqrt{-1}$ is not something I can see and construct on a sheet of paper. The only way to sovle my problem is to find a mathematical formalism to deal with such an expression. I need to introduce complex numbers to solve a problem based on real numbers: My polynomial is defined on the real numbers and has real roots but in order to find those I need to work with complex numbers.
There are countless examples of that in physics to. Quantum mechanics (QM) would be one for example: In QM we calculate most of the time using abstract objects which can not be measured in nature but at the end we can use those objects to predict nature and our experiments.


text:
Q: Overloading rules for inheritance in C++ The following does not compile (Apple LLVM version 4.2 (clang-425.0.28)):
class A {
public:
    virtual void foo() {};
    virtual void foo( int i ) {};
};

class B : public A {
public:
    virtual void foo( int i ) override { foo(); }
};

The compiler error is "Too few arguments" for the call to foo() inside B::foo(int). The compiler apparently thinks that I want to recursively call B::foo(int) and does not recognize that I want to call A::foo(void).
The error goes away if I replace the call to foo() by A::foo().
But:
1) Why is this happening? It seems obvious to just resolve to A::foo() in this case (or an overridden function down the class hierarchy).
2) More importantly, if I want to use polymorphic late binding for foo(void) as well, specifying A::foo() is not what I want, B::foo() of course produces a compiler error as well.
Thanks in advance for any enlightenment!

A: A name in a derived class hides the same name in base classes. In other words, when resolving foo in the context of B, name lookup finds B::foo and stops there. A::foo is never found.
Add using A::foo; within B's definition.


text:
Q: API using youtube.googleapis.com seems broken Since couple of days, youtube.googleapis.com seems completely broken.
Until that moment, embedding video, like https://youtube.googleapis.com/v/dQw4w9WgXcQ worked with no problem. Right now, Player seems to be completely broken on chrome, firefox, and any device I can put my hands on.
Is there something I'm not knowning that is obvious, or is there some great conspiracy on the subject?

A: I am having the same issue. It seems that to embed videos, we have to use this format, with "embed".
<iframe width="560" height="315" src="https://www.youtube.com/embed/We1o204XYGw?rel=0" frameborder="0" allowfullscreen></iframe>

I think they may have depreciated the other format.
Which leaves me with hundreds of misformed videos on my site!


text:
Q: Image options to customize the visibility of tabs Expected behaviour: With respect to my use case, when the user clicks on image button, I must allow the user to only upload the image and hence I have to hide the URL tab.
Actual behaviour:   Currently there is no such option to hide the URL and to display only upload tab.


text:
Q: Apache Calcite: Convert a SQL parse tree into a tree of relational expressions WITHOUT validation I'm currently working on a project in which I want to parse an SQL-Query and create the tree of relational expressions for it.
The main goal is to identify the join partners in the Queries.
So I'd like to push the join-expressions down to the leafs of the tree.
To achieve this, I decided to use Apache Calcite.
My code looks roughly like this at the moment:
Planner planner = Frameworks.getPlanner(Frameworks.newConfigBuilder().defaultSchema(Frameworks.createRootSchema(false)).build());

SqlNode parsed = planner.parse("SELECT s.dnasamplename, e.Total_expression_level, e.Soluble_expression_level, s.id " +
            "FROM table1 e" +
            "JOIN table2 s on s.constructname = e.Clone_name" +
            "WHERE e.Total_expression_level like '0:%'");

planner.validate(parsed);

RelRoot relRoot = planner.rel(parsed);

If I try to execute the rel-Method of Planner directly, I get the error that I have to validate the query first. And that`s the point where I face troubles. I don't have a valid Schema. I just want to convert the query to a relational query plan. Is there a way to kind of skip the validation process?

A: It's not possible to skip the validation process. The sql-to-relational converter relies on state that has previously been created by the validator.
People see that the validator throws an exception if the SQL is invalid and imagine that this is its only purpose; but building the state is equally important. The state includes of a map of the type of each SqlNode, expansions of "*" and "tableAlias.*" in SELECT clauses, and fully-qualified identifiers.
If your schema is missing or incomplete, you might try a similar approach to Apache Drill. If the validator asks for a particular column of a table, and the table does not have that column, the Calcite namespace for that table says "yes, I have that column!" and adds it. Thus, the validation process succeeds, and each namespace has a list of the extra columns needed by the query.


text:
Q: Iterating over drawables in Android In Android, I have only found answers as to how to open a single specific Drawable from MainActivity.java, but not how to iterate over each Drawable from res/drawables. The Drawables names do not follow any patterns (e.g. being numbered from 0 to 25), so the answer suggested here sadly doesn't solve my problem. Does anyone know how to do the latter?
Thank you in advance :)

A: First, put your drawables into an arrays
<array name="dashboard_item_menu_drawable">
    <item>@drawable/ic_file_green</item>
    <item>@drawable/ic_email_green</item>
    <item>@drawable/ic_linear_scale_green</item>
    <item>@drawable/ic_undo_green</item>
    <item>@drawable/ic_check_circle_green</item>
    <item>@drawable/ic_archive_green</item>
</array>

Then, iterate your array drawables
val icons = ArrayList<Int>()
val arr = resources.obtainTypedArray(R.array.dashboard_item_menu_drawable)
(0 until arr.length()).forEach {
    // get resource id of each drawable
    val icon = arr.getResourceId(it, -1)
    icons.add(icon)
}

Next, recycles resource
arr.recycle()

Then you can use your drawable
iconView.setImageDrawable(ContextCompat.getDrawable(this, icons[index]))

A: If you want to iterate through drawables that have similar names like: image1, image2, ..., image10 you can do it like this:
    for (int i = 0; i < 10; i++) {
        int id = getResources().getIdentifier("image" + i, "drawable", getPackageName());
        Drawable d = ContextCompat.getDrawable(this, id);
        // your code here
    }

A: The easiest way to do it is to put the names of your drawables in a String array:
String[] symbols = {"first_img", "second_img", "third_img", "fourth_img"};

Then iterate over them like this (I put the images into a GridLayout):
for(String symbol : symbols) {
    int id = getResources().getIdentifier(symbol, "drawable", getPackageName());

    ImageView img = new ImageView(this);
    LinearLayout.LayoutParams imgParams = new LinearLayout.LayoutParams(300, 300);
    imgParams.setMargins(30, 30, 30, 30);
    img.setLayoutParams(imgParams);
    img.setBackgroundResource(id);
    symbolGrid.addView(img);
}


text:
Q: Compare a dateRange with other continous dates in another list to get adjacent ranges relative to the list compared e.g.
There is a date range from Feb9 thru May 19 in an interval. There is another list of effective dates in a Map for key values like  as of this date this object is returned (Jan 1, Object x), (Feb 1, Object y), (March 1, Object z) (April 1, Object a) (May 1, Object u), (June1, Object n) etc.
The algorithm need is to take the date range of Feb1 thru June19 and to get adjacent dates for the effective date ranges e.g.
the method would be
TreeMapreturnTemporalAdjacentInterval(Interval when)
result should be Treemap sorted by adjacent interval with (Feb9-March1, Object y) (March1-April1, Object z) (April1-May1, Object a) (May1-May19, Object u)
This is like martin fowlers temporal collection however more of a temporal adjacent interval retrieval. Language is Java joda-time Interval is suggested use for the returned intervals.

A: Here is a sample class inspired by Martin Fowlers temporal object with the method implementation for returning the adjacent intervals.
public HashMap<Interval, Object> getAdjacentIntervals(Interval when)

This shows an algorithm with a certain complexity. Any input on a faster version. Unit tests are below to show the tests for the object and document better context
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.joda.time.DateTime;
import org.joda.time.Duration;
import org.joda.time.Interval;

public class TemporalCollection {

private Map<DateTime, Object> contents = new HashMap<DateTime, Object>();

private List<DateTime> _milestoneCache;

public Object get(DateTime when) {
    /** returns the value that was effective on the given date */
    Iterator<DateTime> it = milestones().iterator();
    while (it.hasNext()) {
        DateTime thisDate = it.next();
        if (thisDate.isBefore(when) || thisDate.equals(when))
            return contents.get(thisDate);
    }
    throw new IllegalArgumentException("no records that early");
}

public HashMap<Interval, Object> getAdjacentIntervals(Interval when) {
    // start to get the start date object
    DateTime startDate = when.getStart();
    DateTime endDate = when.getEnd();
    HashMap<Interval, Object> result = new HashMap<Interval, Object>();
    Iterator<DateTime> it = milestones().iterator();

    DateTime endDateToCompare = endDate;
    DateTime startDateToCompare = startDate;
    while (it.hasNext()) {
        DateTime thisDate = it.next();
        if (thisDate.isBefore(endDateToCompare)
                || thisDate.equals(endDateToCompare)) {
            Interval adjacentIntervalPart;
            if (thisDate.isAfter(startDateToCompare) &&  !thisDate.equals(endDateToCompare)) {
                // we have hit upper end of the range
                // upper end of the adjacent interval is as follows
                adjacentIntervalPart = new Interval(thisDate,
                        endDateToCompare);

                result.put(adjacentIntervalPart, contents.get(thisDate));

                endDateToCompare = endDateToCompare.minus(new Duration(
                        thisDate, endDateToCompare));

            } else {

                // we have reached the last range
               adjacentIntervalPart = new Interval(startDate, endDateToCompare);
               result.put(adjacentIntervalPart, contents.get(thisDate));

               return result;
            }
        }

    }
    throw new IllegalArgumentException("no records that early for an Interval");

}

public void put(DateTime at, Object item) {
    /** the item is valid and effective from the supplied date onwards */
    contents.put(at, item);
    clearMilestoneCache();
}

private List<DateTime> milestones() {
    /**
     * a list of all the dates where the value changed, returned in order
     * latest first
     */
    if (_milestoneCache == null)
        calculateMilestones();
    return _milestoneCache;
}

private void calculateMilestones() {
    _milestoneCache = new ArrayList<DateTime>(contents.size());
    _milestoneCache.addAll(contents.keySet());
    Collections.sort(_milestoneCache, Collections.reverseOrder());
}

private void clearMilestoneCache() {
    _milestoneCache = null;
}

}

The Unit test class is as follows
import java.util.HashMap;
import java.util.Iterator;

import org.joda.money.Money;
import org.joda.time.DateMidnight;
import org.joda.time.Days;
import org.joda.time.Interval;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;

import com.vrntmgr.server.utils.StringUtils;

public class TemporalCollectionTest {

TemporalCollection rates;

@Before
public void setup() {
    rates = new TemporalCollection();
    rates.put(new DateMidnight(2010, 1, 1).toDateTime(),
            Money.parse("USD 900"));
    rates.put(new DateMidnight(2010, 2, 1).toDateTime(),
            Money.parse("USD 1000"));
    rates.put(new DateMidnight(2010, 3, 1).toDateTime(),
            Money.parse("USD 2000"));
}

@Test
public void testTemporalRetreival() {
    Interval intrvl = new Interval(new DateMidnight(2010, 1, 15),
            new DateMidnight(2010, 3, 15));

    HashMap<Interval, Object> myMap = rates.getAdjacentIntervals(intrvl);
    // System.out.println(StringUtils.toString(myMap.keySet()));

    Iterator<Interval> it = myMap.keySet().iterator();
    Assert.assertEquals(it.next(),new Interval(new DateMidnight(2010,3,1), new DateMidnight(2010,3,15)));
    Assert.assertEquals(it.next(),new Interval(new DateMidnight(2010,2,1), new DateMidnight(2010,3,1)));
    Assert.assertEquals(it.next(),new Interval(new DateMidnight(2010,1,15), new DateMidnight(2010,2,1)));
}

@Test
public void testEndDayAfterRange() {

    Interval intrvl = new Interval(new DateMidnight(2010,1,15), new DateMidnight(2010, 2, 1));

    HashMap<Interval, Object> myMap =  rates.getAdjacentIntervals(intrvl);

    Iterator<Interval> it = myMap.keySet().iterator();
    Interval res = it.next();
    Assert.assertEquals(res,new Interval(new DateMidnight(2010,1,15), new DateMidnight(2010,2,1)));

    System.out.println("days are" + Days.daysIn(res));

}

}


text:
Q: Upgraded HP Pavilion G7 1317cl with Bios vers F45 to 8GB only 3.3GB recognised in Ubuntu 12.04 X64 Bios and hardware probes indicate 8GB installed. Swapped chip slots with no difference in behavior. DMESG E820 map as follows:
BIOS-provided physical RAM map:
[    0.000000]  BIOS-e820: 0000000000000000 - 000000000009f800 (usable)
[    0.000000]  BIOS-e820: 000000000009f800 - 00000000000a0000 (reserved)
[    0.000000]  BIOS-e820: 00000000000e0000 - 0000000000100000 (reserved)
[    0.000000]  BIOS-e820: 0000000000100000 - 00000000bf9bf000 (usable)
[    0.000000]  BIOS-e820: 00000000bf9bf000 - 00000000bfabf000 (reserved)
[    0.000000]  BIOS-e820: 00000000bfabf000 - 00000000bfbbf000 (ACPI NVS)
[    0.000000]  BIOS-e820: 00000000bfbbf000 - 00000000bfbf5000 (ACPI data)
[    0.000000]  BIOS-e820: 00000000bfbf5000 - 00000000bfc00000 (usable)
[    0.000000]  BIOS-e820: 00000000bfc00000 - 00000000e0000000 (reserved)
[    0.000000]  BIOS-e820: 00000000f8000000 - 00000000fc000000 (reserved)
[    0.000000]  BIOS-e820: 00000000fec00000 - 00000000fec01000 (reserved)
[    0.000000]  BIOS-e820: 00000000fec10000 - 00000000fec11000 (reserved)
[    0.000000]  BIOS-e820: 00000000fed80000 - 00000000fed81000 (reserved)
[    0.000000]  BIOS-e820: 00000000fee00000 - 00000000fee01000 (reserved)
[    0.000000]  BIOS-e820: 00000000ffe00000 - 0000000100000000 (reserved)
[    0.000000]  BIOS-e820: 0000000100000000 - 000000011f000000 (usable)
[    0.000000] NX (Execute Disable) protection: active
[    0.000000] DMI 2.7 present.
[    0.000000] DMI: Hewlett-Packard HP Pavilion g7 Notebook PC/3568, BIOS F.45 01/17/2012
[    0.000000] e820 update range: 0000000000000000 - 0000000000010000 (usable) ==> (reserved)
[    0.000000] e820 remove range: 00000000000a0000 - 0000000000100000 (usable)

A: Upgraded Bios to ver F.52 - no help. Re-installed Windows 7 with same symptoms. Returned laptop as bad system memory slot 2. As an aside, HP was incredibly not helpful and the 90 day return policy from the retailer was my best option for resolving the issue with an entirely new laptop.


text:
Q: Can a real symmetric matrix have 0 (Zero) as one of the eigen values? From what I know (correct me if I am wrong):

$0$ as an eigen value of a real symmetric matrix implies it is Singular (Non- invertible).

I am not aware of any such property with reference to real symmetric matrices.
Also, I wish to know if the following statements are correct or not.

a)  If two matrices have the same eigenvalues, they have the same eigenvectors.  (I think it's false)
b)  If two matrices have the same eigen vectors, they have the same eigen values.  (I think that's true)

Correct me.

A: Identify  each of the following functions from $R^2$ to $R^2$ with their matrix representations : $f(x,y)=(x,0)$ , $g(x,y)=(2 x,0)$ , $h(x,y)=(0,y)$ , $i(x,y)=((x+y)/ 2,(x+y)/2)$. Now $f,g$ have the same eigenvectors but different eigenvalues. And $h,i$ have the same eigenvalues but different eigenvectors.


text:
Q: Projections onto subgradients of convex functions While investigating a form of the Euler-Lagrange equation for convex but nondifferentiable lagrangians, my professor makes the following two assumptions for a Generalized Riesz Theorem:

*

*$x\mapsto\|D(x)\|=\sup_{z\in D(x)}\|z\|$ is $L^\infty$;

*$x\mapsto m_{D(x)-v(x)}$ is measurable for every $v\in L^\infty$, $m_{\dots}$ being the projection of minimal distance of the origin onto the set $\dots$.

With these hypotheses, plus that $T$ is a functional on $L^1$ with:
$$T\xi\leq\int_\Omega I_{D(x)}^\ast(\xi(x))dx,$$
where $I_{D(x)}^\ast$ is the Legendre transform of the indicator of $D(x)$, and the indicator is the one from convex analysis, i.e.:
$$I_{D(x)}(p)=\begin{cases}
0 & p\in D(x) \\
+\infty & p\notin D(x)
\end{cases},$$
not the characteristic function, which gives us:
$$I_{D(x)}^\ast(p)=\sup_{d\in D(x)}\langle d,p\rangle,$$
then $T$ is represented as an integral against a function.
Then he wants to apply this to $D(x)=\partial L(\nabla u(x))$ with $L$ a convex not necessarily differentiable Lagrangian, and $u$ is a solution to the minimization problem:
$$\min\int_\Omega[L(\nabla u(x))+u(x)]dx\qquad\text{on}\qquad u^0+W_0^{1,1}(\Omega),$$
$u^0$ being any boundary datum.
He will deal with the assumption on $T$, and also the $L^\infty$ assumption (actually, he assumes measurability, which seems unnecessary in the proof of said theorem, and gets boundedness by normalization), but he takes the other one (the one on the projections) for granted, and I cannot find them in Dacorogna.
The projection of minimal distance $m_{\partial L(\nabla u(x))}$ is well-defined since, as Dacorogna proves, $\partial L(\nabla u(x))$ is convex (and compact, as well). Hence, my question is:

How do I prove that, given $\Omega\subseteq\mathbb{R}^n$ an open set and $L:\mathbb{R}^n\to\mathbb{R}$ a convex but not necessarily differentiable function, for any $v:\mathbb{R}^n\to\mathbb{R}^n$ measurable, with $u$ as above, we have that $x\mapsto m_{\partial L(\nabla u(x))}$ is measurable, $m_K$ being the projection of minimal distance of the origin onto $K$?

Since he assumed this seemingly superfluous hypothesis, we have a bonus question:

Can I prove that $x\mapsto\|\partial L(\nabla u(x))\|$ is also measurable?

Update
The bonus question is now a needed point, since, though that measurability is not needed to apply Riesz, it is needed in the normalization process.


text:
Q: can not Enable Migrations That error show when i run Enable Migration ! iam did the reverse engineering the SQLServer and i want to do some changers on my Data  i see this erroe whoch guide me to the line 10 on config.cs which is the constructor generated by visual studio (iam using Visual 2015) , sql connector 6.9.4
Checking if the context targets an existing database...
System.TypeInitializationException: The type initializer for 'System.Data.Entity.Migrations.DbMigrationsConfiguration`1' threw an exception. ---> System.TypeLoadException: Inheritance security rules violated by type: 'MySql.Data.Entity.MySqlEFConfiguration'. Derived types must either match the security accessibility of the base type or be less accessible.
   at System.Reflection.CustomAttribute._CreateCaObject(RuntimeModule pModule, IRuntimeMethodInfo pCtor, Byte** ppBlob, Byte* pEndBlob, Int32* pcNamedArgs)
   at System.Reflection.CustomAttribute.CreateCaObject(RuntimeModule module, IRuntimeMethodInfo ctor, IntPtr& blob, IntPtr blobEnd, Int32& namedArgs)
   at System.Reflection.CustomAttribute.GetCustomAttributes(RuntimeModule decoratedModule, Int32 decoratedMetadataToken, Int32 pcaCount, RuntimeType attributeFilterType, Boolean mustBeInheritable, IList derivedAttributes, Boolean isDecoratedTargetSecurityTransparent)
   at System.Reflection.CustomAttribute.GetCustomAttributes(RuntimeType type, RuntimeType caType, Boolean inherit)
   at System.RuntimeType.GetCustomAttributes(Type attributeType, Boolean inherit)
   at System.Attribute.GetCustomAttributes(MemberInfo element, Type type, Boolean inherit)
   at System.Reflection.CustomAttributeExtensions.GetCustomAttributes[T](MemberInfo element, Boolean inherit)
   at System.Data.Entity.Infrastructure.DependencyResolution.DbConfigurationFinder.TryFindConfigurationType(Assembly assemblyHint, Type contextTypeHint, IEnumerable`1 typesToSearch)
   at System.Data.Entity.Infrastructure.DependencyResolution.DbConfigurationManager.EnsureLoadedForAssembly(Assembly assemblyHint, Type contextTypeHint)
   at System.Data.Entity.Infrastructure.DependencyResolution.DbConfigurationManager.EnsureLoadedForContext(Type contextType)
   at System.Data.Entity.Migrations.DbMigrationsConfiguration`1..cctor()
   --- End of inner exception stack trace ---
   at System.Data.Entity.Migrations.DbMigrationsConfiguration`1..ctor()
   at Data.Migrations.Configuration..ctor() in C:\Users\saif kouti\Desktop\piski[pi_kouti]\piski\Data\Migrations\Configuration.cs:line 10
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Data.Entity.Migrations.Utilities.MigrationsConfigurationFinder.FindMigrationsConfiguration(Type contextType, String configurationTypeName, Func`2 noType, Func`3 multipleTypes, Func`3 noTypeWithName, Func`3 multipleTypesWithName)
   at System.Data.Entity.Migrations.Design.ToolingFacade.BaseRunner.FindConfiguration()
   at System.Data.Entity.Migrations.Design.ToolingFacade.ScaffoldRunner.RunCore()
   at System.Data.Entity.Migrations.Design.ToolingFacade.BaseRunner.Run()
The type initializer for 'System.Data.Entity.Migrations.DbMigrationsConfiguration`1' threw an exception.

here my configuation.cs
namespace Data.Migrations
{
    using System;
    using System.Data.Entity;
    using System.Data.Entity.Migrations;
    using System.Linq;

    internal sealed class Configuration : DbMigrationsConfiguration<iskiContext>
    {
        public Configuration()
        {
            AutomaticMigrationsEnabled = false;
        }

        protected override void Seed(Data.iskiContext context)
        {
            //  This method will be called after migrating to the latest version.

            //  You can use the DbSet<T>.AddOrUpdate() helper extension method
            //  to avoid creating duplicate seed data.
        }
    }
}

and here my context
using System.Data.Entity;
using Domain.Models.Mapping;
using Domain.Models;
namespace Data
{
    [DbConfigurationType(typeof(MySql.Data.Entity.MySqlEFConfiguration))]

    public partial class iskiContext : DbContext
    {
        static iskiContext()
        {
            Database.SetInitializer<iskiContext>(null);
        }

        public iskiContext()
            : base("Name=iskiContext")
        {
        }

        public DbSet<accomodation> accomodations { get; set; }
        public DbSet<company> companies { get; set; }
        public DbSet<contract> contracts { get; set; }
        public DbSet<Event> events { get; set; }
        public DbSet<event_user> event_user { get; set; }
        public DbSet<organizerrequest> organizerrequests { get; set; }
        public DbSet<product> products { get; set; }
        public DbSet<products_user> products_user { get; set; }
        public DbSet<user> users { get; set; }
        public DbSet<user_company> user_company { get; set; }
        public DbSet<winner> winners { get; set; }

        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            modelBuilder.Configurations.Add(new accomodationMap());
            modelBuilder.Configurations.Add(new companyMap());
            modelBuilder.Configurations.Add(new contractMap());
            modelBuilder.Configurations.Add(new eventMap());
            modelBuilder.Configurations.Add(new event_userMap());
            modelBuilder.Configurations.Add(new organizerrequestMap());
            modelBuilder.Configurations.Add(new productMap());
            modelBuilder.Configurations.Add(new products_userMap());
            modelBuilder.Configurations.Add(new userMap());
            modelBuilder.Configurations.Add(new user_companyMap());
            modelBuilder.Configurations.Add(new winnerMap());
        }
    }
}

A: check the up() and down() methods in your migration file. Your changes will be submitted after update-databasecommand according to this up and down function.
otherwise make your AutomaticMigrationsEnabled = true


text:
Q: View or log to see who has run a report The client has SP 2013 with SSRS reporting integrated. I have built some reports for them and they work great. On one of the reports, the client would like to be able to see who has run the report as it is mandatory.
Is there a view I can set up that will display who has run this report? If not, can I use the Usage DB to create a log of who runs the report?

A: Please make sure that you have enabled auditing at the list/library level from settings page
Information management policy settings  -> Enable Auditing -> Opening or downloading documents, viewing items in lists, or viewing item properties
If you have enabled this settings then go to Audit Log reports from the site collection site settings and then
Run a custom report --> Opening or downloading documents, viewing items in lists or viewing item properties.

A: The way I do this is to use the statistics that SSRS keeps. SharePoint's usage analytics are awful.
You can find usage stats using SQL Server queries by connecting to the SQL Server that hosts the ReportServer database (probably your SharePoint SQL Server in integrated mode) and query the table ExecutionLog or the views ExecutionLog2 or ExecutionLog3.
There are several sites and blogs on the web that provide various queries on how to get information from these in different forms. The most basic way is (obviously) using SSMS:
USE ReportServer
GO

SELECT * FROM ExecutionLog3

By default it keeps 60 days worth of stats but you can use Central Admin to keep them longer.
See:
https://docs.microsoft.com/en-us/sql/reporting-services/report-server/report-server-executionlog-and-the-executionlog3-view


text:
Q: why does my app.get not return a response? On node js, I'm trying to do a post request, before that though I want to test if a get request can give me a response.
On my browser, I have the following URL:
http://127.0.0.1:3000/home/finishpage/client/index.html

Now when I set up a get request, nothing comes back, e.g.
app.get("/home/finishpage/client/index.html", (req,res)=>{
  console.log("testing get request")
  res.sendFile(path.join(__dirname,"/index.html")) //dont mind this
})

The console.log doesn't print in this instance, which means I'm not getting the res I want.
Now if I add a fake rout like this:
app.get("/home/finishpage/client/index.html/fake", (req,res)=>{
  console.log("testing")
  res.sendFile("test")
})

and go to my browser and search:
http://127.0.0.1:3000/home/finishpage/client/index.html/fake

This give me a response, and excutes the console.log("testing") command.
What am I not understanding.

A: you need to serve static files for express app
app.use(express.static({folderPath}));


text:
Q: Protect my java application from being copied How do I stop someone from copying and duplicating the application i am making in java ? I am using mysql as back-end for my application and the platform is Linux. Is there a way to provide this security ?
EDIT  :
Is there a way like in windows where some applications even if we copy the folder and past it into other system it wont work. I don't know how they are doing it. Is there any similar thing that I can do here ?

A: Alright, here is an alternate answer to my comment.

*

*Don't sell software, sell support.

*Implement a simple licensing system tied to an email address.

*Only provide support for users with registered email addresses.

For tips on creating that, see Software Licensing System  at the OTN.  The solutions shown there are crackable, but not by the casual end user.

A: There is really nothing you can do to stop piracy, as a user must be able to run code on their computer.  Some companies have used hardware tokens, but this is expensive for a small developer.
A small step would be to only deliver the class files, and possibly run them through an obfuscator.
Here in an example obfuscater.
http://proguard.sourceforge.net/
Here is a good page on securing java code.
http://www.cs.arizona.edu/~collberg/Research/Students/DouglasLow/obfuscation.html

A: Is your project open source? If so, then you'll want to use the appropriate licensing. If not, read up on EULAs and consult a lawyer.

A: There is no way we can prevent users to copy the way you have mentioned.
This is the biggest challenge that all the medium sized product based companies are facing and they are spending quite a lot of time on preventing this.
I aggree with @Milhous & @Andrew Thompson replies

A: There are several commercial Java licensing systems that do exactly what you need (but you should dig into the details as not all of them are actually multiplatform Java, but have just wrapped a C library).
The standard technique for preventing simple replication of an application on other machines is node-locking, where the application checks at runtime that certain system parameters match the encrypted values on its license. The MAC address is commonly used, but this is not a good choice as it can be set by admins on many systems. I'd recommend using a combination of parameters, such as login name, host name, installation directory and so forth.
The licensing process can be manual for low-volume sales, or automated for higher volume licensing. In the automated approach the license is automatically locked to its host during product activation, transparently to the user. As well as being simple and familiar for the user, modern [product activation][2] systems can both meet your goal of preventing copying, and allowing users to relocate their license to another machine if they wish (whether or not their systems have an Internet connection.

A: I'm in the middle of trying this myself, but maybe you can configure your program to get the mac address of the computer (that you want it to run on) on first-run. Then have it save it to the registry. Then, in your main method have it get your mac address and match it against that of the registry. (The registry tends to put forward slashes where there are spaces but removing the slashes should get you a match).


text:
Q: How to check code style formatting in IDEA? How to check code style in the whole project or some part of it in IDEA? Let me make an accent here on a word "check". I don't need to fix code style I just want to see how big is the problem of not following code style in the project. So I want to see list of lines or cases where code formatting is not inline with what I have set in the File -> Settings -> Code Style -> Java. I thought that Code Inspection does this but when I checked File -> Settings -> Inspections -> Code style issues it seemed to me that these issues are not about code style formatting.
What I would like to use is: I start some inspection on some part of code or the whole project and as a result of inspection I want to see list of issues/lines where code formatting is broken.
I know I might just reformat the whole project and then run source control diff but I don't think that this is really good. I would like to see some categorization of code style issues with statistics, etc... Is there any way to get this in IDEA?

A: You should consider CheckStyle. It analyses the code and shows summary similar to error or warning message in the IDE. In addition you could customize the check style or use existing one. There should be a plugin for IDEA as well.

A: Try out maven-checkstyle-plugin. It's based on the Checkstyle. You can create configuration to run it under IntelliJ IDEA.
The output looks like:
C:\src\ClassPathTldsLoader.java:8:8: Unused import - java.util.Collections.
C:\src\model\Class1.java:64: 'if' construct must use '{}'s.
C:\src\model\Class2.java:55: 'if' construct must use '{}'s.
C:\src\Class3.java:4:1: Redundant import from the same package - java.util.Collections
...


text:
Q: How to use TryUpdateModel to pick form values in asp.net website using MasterPage Recently I tried to use the TryUpdateModel to get the value of the control in a form, but the trouble is that I use the MasterPage in my asp.net website, I found that although I can set the "ClinetIDMode" to Static to ensure that the control ID will not become MainContent_USER_NAME.But I found FormValueProvider match the name of control rather than id, and there is no such a "ClientNameMode"  attribute can be set to Static, so the name of the control can only be something like "ctl00$MainContent$USER_NAME".
How to solve this problem?Please help me.And my aspx and cs file:
Test.aspx:
<%@ Page Title="" Language="C#" MasterPageFile="~/Site.master" AutoEventWireup="true" CodeFile="Test.aspx.cs" Inherits="Test" %>
<asp:Content ID="Content1" ContentPlaceHolderID="MainContent" Runat="Server">
<div>
    UserName:<asp:TextBox ID="USER_NAME" runat="server" ></asp:TextBox>
    <asp:Button ID="Button1" runat="server" Text="Add a user" OnClick="Button1_Click" />
</div>
</asp:Content>

Test.aspx.cs:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.ModelBinding;

public partial class Test : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {

    }

    protected void Button1_Click(object sender, EventArgs e)
    {
        Entities db = new Entities();
        USER_INFO u = new USER_INFO();

        IValueProvider p = new FormValueProvider(ModelBindingExecutionContext);

        if (TryUpdateModel(u, p))
        {
            String name = u.USER_NAME;//can't pick the value
            db.USER_INFO.Add(u);
            db.SaveChanges();
        }
        else
        {
            //do nothing.
        }
    }
}

A: Finally I found a solution.I can write a little front-end code to set the name equal to id.
 <script>
     $("input[type=text]").each(function () {
         var id = $(this).attr("id");
         $(this).attr("name", id);
     });
 </script>

And don't forget to set Page's ClientIDMode to Static.
<%@ Page Title="" Language="C#" MasterPageFile="~/Site.master" AutoEventWireup="true" CodeFile="Test.aspx.cs" Inherits="Test" ClientIDMode="Static" %>


text:
Q: Microsoft Access 2003 simple inserting in Database failed using VB.net I am trying to insert into Microsoft Access database from VB.net.
I can read from the Data Base(can see in Grid View) but cannot insert into Database.I don't know where the problem is.
This is what i am doing:
Imports System.Data
Imports System.Data.OleDb

Public Class Form1
Public ctr As Integer
Dim bm As BindingManagerBase
Dim dr As DataRow, dt As DataTable
Dim flag As Integer, tid As Integer, tname As String
Dim totalrow As Integer, currentrow As Integer

Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
    'TODO: This line of code loads data into the 'ShowroomDataSet.customer' table. You can move, or remove it, as needed.
    bm = Me.BindingContext(ShowroomDataSet, "customer")
    bm.Position = 0
    Me.CustomerTableAdapter.Fill(Me.ShowroomDataSet.customer)

 End Sub

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
    Dim x As Integer
    Dim y As String
    bm.Position = bm.Count - 1
    x = ShowroomDataSet.customer(bm.Position).cid
    y = ShowroomDataSet.customer(bm.Position).cname
    TextBox1.Text = x
    TextBox2.Text = y

  End Sub

Private Sub Button4_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button4.Click
    Close()
End Sub

Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
    'save
    'enable all buttons except save
    If flag = 1 Then
        dt = ShowroomDataSet.Tables("customer")
        dr = dt.NewRow()
        dr!cid = Val(TextBox1.Text)
        dr!cname = TextBox2.Text
        dt.Rows.Add(dr)

    End If
    If flag = 2 Then
        dr.Delete()
    End If
    If flag = 3 Then
        dt = ShowroomDataSet.Tables("customer")
        dr = dt.Rows.Find(tid)
        dr.BeginEdit()
        dr!cid = Val(TextBox1.Text)
        dr!name = TextBox2.Text
        dr.EndEdit()
    End If
    'Me.CustomerTableAdapter.Update(Me.ShowroomDataSet.customer)
    'Me.CustomerTableAdapter.Fill(Me.ShowroomDataSet.customer)
    flag = 0
    Button1.Enabled = True
    Button2.Enabled = False
    Button3.Enabled = True
    Button4.Enabled = True

End Sub

Private Sub Button3_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button3.Click
    'add
    'disable all buttons except save
    Dim len As Integer
    TextBox1.Text = " "
    TextBox2.Text = " "
    flag = 1
    TextBox1.Focus()
    Button1.Enabled = False
    Button2.Enabled = True
    Button3.Enabled = False
    Button4.Enabled = False
    dt = ShowroomDataSet.Tables("customer")
    len = dt.Rows.Count - 1
    dr = dt.Rows(len)
  End Sub
  End Class

No errors or faults.
Please help.

A: If you are just looking to insert data into an access database use the database table adapter insert method, followed by the fill method of the table adapter to fill the a table in the dataset. See following example
me.tableadapter.insert(me.1stFieldTextbox.text, me.2ndFieldTextBox.Text....)
me.tableadapter.fill(me.Dataset.Table)
If you get an error, it could be because your data types do not match, you try to insert data into an auto increament field or one which has a calculated data type.


text:
Q: Setting Authentication Header in Servlet via Filter Preface
This is my first attempt at a Filter, be gentle.
Project Description
I am trying to finalize a build for a SSO for several of our applications and I seem to be hitting a wall. The webapp I am attempting to connect to uses the "Authentication" header to determine user credentials within the application. I have built a Filter with hopes of setting the header before it is passed on to the webapp.
The Problem
The code passes eclipse validation, compiles, loads to Tomcat, and passes through to the webapp. The only thing that is missing is the Authentication header.
What am I missing/doing wrong?
AuthenticationFilter source
package xxx.xxx.xxx.xxx.filters;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import xxx.xxx.xxx.ConfigFile;
import xxx.xxx.xxx.Console;
import xxx.xxx.xxx.FalseException;

import xxx.xxx.activity.EncryptUtil;

public class AuthenticationFilter implements Filter {
  public ConfigFile config;

  public void init(FilterConfig arg0) throws ServletException {
    config = new ConfigFile("C:/config.properties");
  }

  public void doFilter(ServletRequest sRequest, ServletResponse sResponse, FilterChain filterChain) throws IOException, ServletException {
    Console.debug("AuthenticationFilter.doFilter() triggered.");
    ServletRequestWrapper request = new ServletRequestWrapper((HttpServletRequest) sRequest);
    HttpServletResponse response = (HttpServletResponse) sResponse;
    HttpSession session = request.getSession();
    Cookie cookie = null;
    try {
      if (request.getParameter("logout") != null) {
        session.invalidate();
        throw new FalseException("Logout recieved");
      }
      String auth = request.getHeader("Authorization");
      if (auth == null) {
        Console.debug("Authorization Header not found.");
        // get cookie --COOKIE NAME--
        Cookie[] cookies = request.getCookies();
        if (cookies == null) {
          throw new FalseException("Cookies not set.");
        }
        for (int i = 0; i < cookies.length; i++) {
          if (cookies[i].getName().equals(config.getProperty("authentication.cookie.name"))) {
            cookie = cookies[i];
          }
        }
        if (cookie == null) {
          throw new FalseException("Cannot find Cookie (" + config.getProperty("authentication.cookie.name") + ") on Client");
        }
        Console.debug("Cookie (" + config.getProperty("authentication.cookie.name") + ") found on Client. value="+cookie.getValue());
        String decToken = decryptToken(cookie.getValue());
        Console.debug("Decrypted Token: "+decToken);

        Console.debug("Setting Authorization Header...");
        request.setAttribute("Authorization", decToken);
        request.addHeader("Authorization", decryptToken(cookie.getValue()));
        Console.debug("Authorization Header set.");
        Console.debug("Validating Authorization Header value: "+request.getHeader("Authorization"));
      }
    }catch (FalseException e) {
      Console.msg(e.getMessage() + ", giving the boot.");
      response.sendRedirect(config.getProperty("application.login.url"));
    } catch (Exception e) {
      Console.error(e);
    }
    Console.debug("AuthenticationFilter.doFilter() finished.");
    filterChain.doFilter(request, response);
  }

  public void destroy() {

  }

  private String decryptToken(String encToken) {
    String token = null;
    token = EncryptUtil.decryptFromString(encToken);
    return token;
  }
}

web.xml source
<web-app>
  <filter>
    <filter-name>AuthenticationFilter</filter-name>
    <display-name>AuthenticationFilter</display-name>
    <description></description>
    <filter-class>com.xxx.xxx.xxx.filters.AuthenticationFilter</filter-class>
  </filter>
  <filter-mapping>
    <filter-name>AuthenticationFilter</filter-name>
    <url-pattern>/*</url-pattern>
  </filter-mapping>
  ...
</web-app>

ServletRequestWrapper Source
package com.xxx.xxx.xxx.filters;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

public class ServletRequestWrapper extends javax.servlet.http.HttpServletRequestWrapper {

  public ServletRequestWrapper(HttpServletRequest request) {
    super(request);
    headerMap = new HashMap();
  }

  private Map headerMap;

  public void addHeader(String name, String value) {
    headerMap.put(name, new String(value));
  }

  public Enumeration getHeaderNames() {
    HttpServletRequest request = (HttpServletRequest) getRequest();
    List list = new ArrayList();
    for (Enumeration e = request.getHeaderNames(); e.hasMoreElements();) {
      list.add(e.nextElement().toString());
    }

    for (Iterator i = headerMap.keySet().iterator(); i.hasNext();) {
      list.add(i.next());
    }
    return Collections.enumeration(list);
  }

  public String getHeader(String name) {
    Object value;
    if ((value = headerMap.get("" + name)) != null)
      return value.toString();
    else
      return ((HttpServletRequest) getRequest()).getHeader(name);
  }

}

Debug Log
LoginServlet.doGet() triggered.
[DEBUG] : Authenticate.isClientLoggedIn() triggered.
xxx url : https://xxx.xxx.xxx/xxx/home.action
[DEBUG] : Authenticate.isClientLoggedIn() status code: 401
Unauthorized User.
Client IS NOT logged in.

-- Fill out Login Form, submit --

LoginServlet.doPost() triggered.
[DEBUG] : Authenticate.isClientLoggedIn() triggered.
xxx url : https://xxx.xxx.xxx./xxx/home.action
[DEBUG] : Authenticate.isClientLoggedIn() status code: 401
Unauthorized User.
Client IS NOT logged in.
Client (--USERID--) attempting basic authentication with password(--PASSWORD--).
[DEBUG] : BasicAuthentication.touch(http://localhost:PORT/vu/loginCheck.html, --USERID--, --PASSWORD--) triggered.
[DEBUG] : BasicAuthentication.touch() response code: 200
Client (--USERID--) has been logged IN.
Client (--USERID--) basic authentication finished, Client is logged in.
Client (--USERID--) logged in successfully.
[DEBUG] : Cookie (xxx_token) Set: 1e426f19ebdfef05dec6544307addc75401ecdc908a3c7e6df5336c744--SECRET--
[DEBUG] : Redirecting client to https://xxx.xxx.xxx/xxx/home.action

-- Redirected to webapp, filter recieves --

[DEBUG] : AuthenticationFilter.doFilter() triggered.
[DEBUG] : Authorization Header not found. << Initical check to see if user is already logged in to site
[DEBUG] : Cookie (xxx_token) found on Client. value=1e426f19ebdfef05dec6544307addc75401ecdc908a3c7e6df5336c744--SECRET--
[DEBUG] : Decrypted Token: Basic --SECRET--
[DEBUG] : Setting Authorization Header...
[DEBUG] : Authorization Header set.
[DEBUG] : Validating Authorization Header value: Basic --SECRET-- << Value matches Decrypted Token
[DEBUG] : AuthenticationFilter.doFilter() finished.

-- Web Application errors out, unable to find Authorization header

Thanks for your help.

A: I'm adding a new answer, since it's completely different.
I did a test on my system. I copied your code, dumped the cookie test, and wrote a simple Servlet to dump things out for me.
And it worked fine, save for one caveat.
I don't know how your app is using this. But your ServletRequestWrapper implements getHeaderNames, and getHeader, but it does NOT implement getHeaders. I ran in to that problem as I used getHeaders to try and dump the request, and, of course, Authorization was missing.
So, you may want to look at your code closer to see if it is indeed not using getHeaders. If it is, it will "work fine", but completely skip the work you've done, and thus miss your Authorization header.
Here's my implementation, and it worked for me.
    @Override
    public Enumeration getHeaders(String name) {
        Enumeration e = super.getHeaders(name);
        if (e != null && e.hasMoreElements()) {
            return e;
        } else {
            List l = new ArrayList();
            if (headerMap.get(name) != null) {
                l.add(headerMap.get(name));
            }
            return Collections.enumeration(l);
        }
    }

A: First, the most basic question (kind of an "is this plugged in" question), I assume that your cookies are all rooted in the same domain, and that you're not trying to get cross domain behavior here. Because cookies won't do that.
Beyond the cookie test, this looks fine. But it all hinges on the cookie test.
If you want to test the Authorization header, then you can simply short circuit the cookie test (i.e. it always passes) and populate the Authorization header with some valid value. This will, in the short term, test your whole Authorization scheme.
Once that's done/fixed, then you can focus on the cookie setting and delivery.
I also assume that you're not using Java EE Container based authentication, with Tomcat doing this check for you. In that case, a filter is simply "too late". The container will have already made it's decisions before your filter even gets called.
If you are using container based authentication, and your apps are on the same container, I would imagine Tomcat (or someone) has an SSO option at the container level. I know that Glassfish will do this for you out of the box. It should be straightforward to modify Tomcat artifacts (i.e. not portable Java EE/Servlet mechanisms) to implement this if that is the case.


text:
Q: How to insert entity over WCF-RIA-Services JSON endpoint My WCF-RIA DomainService has an insert method that looks like this:
public void InsertWidget(WidgetDef widgetDef)

class WidgetDef
{
    [Key]
    int widgetID;
    string title;
    int x;
    int x;
    // there are more properties, but I think you get the idea...
}

To access this through the JSON endpoint, I think I need to POST a changeset to the url:
[serverURL][namespace]WidgetService.svc/json/SubmitChanges.
I'm pretty sure I got the URL correct, because my request reaches the WidgetService.Initialize method, but then I get an exception in the server - which is no surprise because I don't know what the content of the request should look like.
My Question: What is the (JSON) format of a HTTP request's content for an insert operation?

A: Insert changeset for the example given would look like this:
{"changeSet":[
        {"Id":0,
         "Entity":{"__type":"WidgetDef:#widgetDefNamespace",
                    "widgetId":0,
                    "title":"the new title",
                    "x":10,
                    "y":10,
                },
            "Operation":2    // '2' for insert, '3' for update, '4' for delete
        }
    ]
}

Thanks to following blog post: http://www.joseph-connolly.com/blog/post/WCF-RIA-Services-jQuery-and-JSON-endpoint-Part-2.aspx

A: This is a very late answer, but just in case someone else runs into these issues again; it is important that the __type is the first key in the entity.
I ran into exceptions like:
This DomainService does not support operation 'Update' for entity 'Object'
which indicate that Domain Service was unable to resolve the type of the entity, and therefor unable to find the appropriate handler.
Research turned up this blogpost on the subject http://www.blog.yumasoft.com/node/108 which contains the solution.
I'd like to point out that this behavior goes against the JSON specification (see: https://stackoverflow.com/a/5525820/1395343).
One possible workaround is to use replace to ensure that the __type ends up in the correct location. I'm not convinced that this is a good idea, but it does work.
var entityChange = {};
entityChange.Id = 0;
entityChange.Operation = 3;
entityChange.Entity = {'key': 'Something that changed'};

var payload = JSON.stringify({ changeSet: [entityChange]});

// This is not an ideal way of doing this.
payload = payload.replace('"Entity":{', '"Entity":{"__type":"TypeName:#Namespace.Stuff",');
return $.ajax({
    url: "...Web.svc/JSON/SubmitChanges",
    method: "POST",
    data: payload,
    contentType: "application/json",
    dataType: "json",
    processData: false,
});