text:
Q: Problem in flashing and running STM32 bluepill in linux environment I am new to STM32 programming. I have bluepill hardware with me. My goal is to flash a simple program (such as blink an led in bluepill) using opensource tools and ubuntu OS.
I am currently following the book "Beginning STM32 developing with freeRTOS libopencm3 and GCC" for the same.
As per the book
I have downloaded the book software using git clone https://github.com/ve3wwg/stm32f103c8t6.git
I have downloaded the libopencm3 in stm32f103c8t6 folder using git clone https://github.com/libopencm3/libopencm3.git
I have downloaded freertos (version FreeRTOSv10.2.1.zip) from sourceforge and unzip in location /stm32f103c8t62/rtos/
I have made required changes in /stm32f103c8t6/rtos/Project.mk file "FREERTOS        ?= FreeRTOSv10.2.1"
I have installed ARM cross compiler using sudo apt install gcc-arm-none-eabi
I have build the software using following command "$ cd ~/stm32f103c8t6" and "$ make"
Then i have installed st-flash tool
There is pre written code named as miniblink.c in miniblink folder
code is as follows:
#include <libopencm3/stm32/rcc.h>
#include <libopencm3/stm32/gpio.h>

static void
gpio_setup(void) {

    /* Enable GPIOC clock. */
    rcc_periph_clock_enable(RCC_GPIOC);

    /* Set GPIO8 (in GPIO port C) to 'output push-pull'. */
    gpio_set_mode(GPIOC,GPIO_MODE_OUTPUT_2_MHZ,
              GPIO_CNF_OUTPUT_PUSHPULL,GPIO13);
}

int
main(void) {
    int i;

    gpio_setup();

    for (;;) {
        gpio_clear(GPIOC,GPIO13);   /* LED on */
        for (i = 0; i < 1500000; i++)   /* Wait a bit. */
            __asm__("nop");

        gpio_set(GPIOC,GPIO13);     /* LED off */
        for (i = 0; i < 500000; i++)    /* Wait a bit. */
            __asm__("nop");
    }

    return 0;
}

I have connected my bluepill using st-link v2 to my computer.
I have used following commands in terminal from miniblink folder "$ make clobber" followed by "$ make" followed by "$ make flash" as given in textbook.
it shows following output in terminal:
 /usr/bin/st-flash  write miniblink.bin 0x8000000
st-flash 1.6.0
2022-04-07T21:44:50 INFO common.c: Loading device parameters....
2022-04-07T21:44:50 INFO common.c: Device connected is: F1 Low-density device, id 0x10006412
2022-04-07T21:44:50 INFO common.c: SRAM size: 0x2800 bytes (10 KiB), Flash: 0x8000 bytes (32 KiB) in pages of 1024 bytes
2022-04-07T21:44:50 INFO common.c: Attempting to write 688 (0x2b0) bytes to stm32 address: 134217728 (0x8000000)
Flash page at addr: 0x08000000 erased
2022-04-07T21:44:50 INFO common.c: Finished erasing 1 pages of 1024 (0x400) bytes
2022-04-07T21:44:50 INFO common.c: Starting Flash write for VL/F0/F3/F1_XL core id
2022-04-07T21:44:50 INFO flash_loader.c: Successfully loaded flash loader in sram
  1/1 pages written
2022-04-07T21:44:50 INFO common.c: Starting verification of write complete
2022-04-07T21:44:50 INFO common.c: Flash written and verified! jolly good!

Also the book doesn't mention about whether BOOT0 is HIGH or LOW during flashing.
I tried flashing bluepill with both settings BOOT0 HIGH and BOOT0 LOW
But in either case I don't see PC13 green LED blink in the bluepill after flashing.
Where am I going wrong. How to check whether the code is getting flashed to the bluepill?
What should I do to get the green led blink in the bluepill?

A: You are programming with JTAG or SWD.  The state of BOOT0 does not matter while you are programming.
The level of BOOT0 only matters during the rising edge of nRST (for example after you have finished programming).  If BOOT0 is high and BOOT1 is low the embedded serial bootloader will run instead of your program, which is probably not what you want.  See AN2606 for details.


text:
Q: How to fix 'show permission dialog ' every time when I send sms? I want to send SMS by android-app, but the permission dialog show before the send a message every time, I supposed to send a message without dialog show after the first permission asked.
My android app is run on mi-8, target SDK-version is 29.
if (ContextCompat.checkSelfPermission(MainActivity.this, Manifest.permission.SEND_SMS) != PackageManager.PERMISSION_GRANTED) {
    ActivityCompat.requestPermissions(MainActivity.this, new String[]{Manifest.permission.SEND_SMS}, 3);
} else if (ContextCompat.checkSelfPermission(MainActivity.this, Manifest.permission.READ_PHONE_STATE) != PackageManager.PERMISSION_GRANTED) {
    ActivityCompat.requestPermissions(MainActivity.this, new String[]{Manifest.permission.READ_PHONE_STATE}, 4);
} else {
    sendMsg();
}

I expect the permission dialog did not show when I send a message after the first asked permission, but actual every time show dialog when I send a message .

A: use this function to check whether you have given the permission if say so you have given as required persmission it will return true flag
check by this way
   private boolean checkAndRequestPermissions(){

        //add as much as permission you need
        int readSMS = ContextCompat.checkSelfPermission(this, Manifest.permission.READ_SMS);
        int sendSms = ContextCompat.checkSelfPermission(this, Manifest.permission.SEND_SMS);

        List<String> listPermissionsNeeded = new ArrayList<>();

        if (readSMS != PackageManager.PERMISSION_GRANTED) {
            listPermissionsNeeded.add(Manifest.permission.READ_SMS);
        }
        if (receiveSms != PackageManager.PERMISSION_GRANTED) {
            listPermissionsNeeded.add(Manifest.permission.RECEIVE_SMS);
        }
        if (!listPermissionsNeeded.isEmpty()) {
            ActivityCompat.requestPermissions(this, listPermissionsNeeded.toArray(new String[listPermissionsNeeded.size()]),
                    REQUEST_ID_MULTIPLE_PERMISSIONS);
            return false;
        }
        return true;
    }

check by this way
 if (checkAndRequestPermissions()){
        sendMsg();
    }else{
      //do what you want
    }

no need to do this by hardcode way

redpajama_set_name: RedPajamaStackExchange


text:
Q: jquery.html() loads the codeigniter view - only one line file I'm loading a view, extra.php, into #extra div via jquery command:
$('#extra').html("<?php $this->load->view('extra'); ?>");

extra.php is a long file, and jquery.html() loads only a single line of code
for example, it loads fine:

but it doesn't load at all:

....

....

....

How to fix it?

A: Ok guys, I found some extra solution on codeigniter board, it's simply hilarious:
http://codeigniter.com/forums/viewthread/219780/
: )

A: You need to escape each line that is output from the view, that way you can pass a multi-line string to the function. To escape, you just need to append a \ to the end of each line so that you would have the following:
$('#extra').html("
\

....
\

....
\

....
\

");

You can see it working on jsfiddle.


text:
Q: User text in Jquery Terminal I have question, how can i add value in Jquery Terminal? Something like this:
jQuery(function($, undefined) {
 $('#terminal').terminal(function(command) {
     if(command == 'test ' + value) { // Value (something a user wrote)
        alert(value);
     }else{
     alert("You don't wrote anything.");
     }

 }, {
 greetings: 'Hello.',
 name: 'Name',
 prompt: 'Terminal> ',
 color: 'some color'
 });
});

I mean something like this:
if(command == 'you type ' + userText) {
alert(userText);
} else {
alert("You don't wrote anything.");
}

A: You can do two things if value is previous command you can save it in variabe like this:
jQuery(function($, undefined) {
    var prev_command = '';
    $('#terminal').terminal(function(command) {
        if (command == 'test ' + prev_command) {
           alert(value);
        } else {
           alert("You don't wrote anything.");
        }
        prev_command = command;
    }, {
       greetings: 'Hello.',
       name: 'Name',
       prompt: 'Terminal> '
  });
});

or you can use push:
jQuery(function($, undefined) {
   $('#terminal').terminal(function(command) {
      var value = command;
      this.push(function(command) {
        if (command == 'test ' + value) {
           alert(value);
        } else {
           alert("You don't wrote anything.");
        }
        term.pop();
      });
   }, {
      greetings: 'Hello.',
      name: 'Name',
      prompt: 'Terminal> '
   });
});


text:
Q: media queries not working properly in a react app i am a complete begginer trying to make a responsive react app. My problem is that media queries don't work, and i can't figure out why.
$main-color: #b282ff;
$darker-main-color: #8A42FF;
$shadow-color: #d9c2ff;
$accent-color: #E8FFC2;
$main-font: "Libre Bakersville";
$secondary-font: "Bebas Neue";

* {
    margin: 0 auto;
    padding: 0;
    box-sizing: border-box;
  }

body {
    font-size: 2em;
    font-family: "Bebas Neue";
}

.navbar-container {
    display: flex;
    flex-direction: row;
    align-items: center;
    height: 10vw;
    width: auto;
    background: $main-color;
    padding: 16px;

    ul {
        display: flex;
        align-items: center;
        justify-content: space-between;
        flex-direction: row;
        font-size: 2rem;
        position: relative;
        height: 100%;
        li {
          padding: 0 60px 0 60px;
          list-style: none;
        }
      }

      a{
        color: white;
        text-decoration: none;
        &:visited {
          color: white;
        }
      }
}

.navbar-menu-toggle{
  display: none;
  position: absolute;
  padding: 10px;
  color: #fff;
}

.navbar-logo {
  font-size: 3rem;
  a{
    color: white;
    text-decoration: none;
    &:visited {
      color: white;
    }
  }
}

.sticky {
  position: -webkit-sticky;
    position: sticky;
    top: 0;
}

@media screen and (max-width:500px) {
    .navbar-container{
     flex-direction: column;
        height: auto;
  }
}

here is my scss. what i am trying to do is to make the list in the menu to display as a column istead of a row. While tdebugging i tried to switch the media queruies statements, just so it changes the background color, but it also did not work. What can i do?


text:
Q: windows 7 64bit rc with SSD saving problem I have this problem where, in any application, 95% of the time when i try to save it pops up with a "Save As" dialogue. And if i try to select the original file i get an error popup "The operation could not be completed".
I have Windows 7 RC 64bit with a X-25M SSD. I have upgraded the firmware for the SSD just in case and still the problem persists.
Has anyone come across this before or know the problem?
Or is there some indication i should be looking for in the event logs?
Thanks

A: In Windows 7, you may not be able to save to certain directories (such as C:\Windows, C:\Program Files, etc.) unless the application is run as an administrator.

A: You are saying that you are trying to save to a folder that you have created.

*

*But under which circumstances did you
create this folder?

*As an administrator?

*With which user account are you
running the applications?

*Have you tried to run the application as an
administrator?
If so, what is the result?

*Has somebody else saved the current
file with other permissions than your
current account?

My guess is that it is a permissions issue. When the Save As dialog pops up instead of saving the file, most certainly the current file can't be opened/saved. Probably because of permissions and/or the file is read only or locked.
Download and run SysInterals procmon, filter on your file name, and watch what the result is when saving the file.


text:
Q: can't find variable in <%=%> I added a new web form in asp.net application which named Home.
In Home.aspx.cs I used these following codes :
public partial class Home : System.Web.UI.Page
{
    protected string str = "Hello and welcome to c#";
    protected void Page_Load(object sender, EventArgs e)
    {

    }
}

Then I go to Home.aspx but unfortunately It won't find str variable.
These are the codes in Home.aspx :
    <body>
    <form id="form1" runat="server">
    <div>
    <%=str %>
    </div>
    </form>

A: It seems it's a problem with asp.net error. Because it shows me error but when I start without debugging it show me the string and won't show any error after that.
By the way there's no problem with protected.

A: your str variable should be public not protected, use like:
public partial class Home : System.Web.UI.Page
{
    public string str = "Hello and welcome to c#";
    protected void Page_Load(object sender, EventArgs e)
    {

    }
}


text:
Q: Creating simple pages through variables I'm trying to create a page that can allow users to customize there own specific pages, these pages will only have a few customization options such as text, color and layout of blocks. I haven't started a configuration page but i have began creating a template that the user will modify to suit their needs.
I would like to somehow get the information given by the user on the configuration page and then display it into parts of the other page. At the moment i don't know the best way to get that information and display in tags on the other page such as these tags.

  <?php  $GLOBALS['event1'] ?>

This is a snippet of code of a few ways I've tried to display the information sadly i haven't had any luck in getting the information and displaying it at the  same time.
I was thinking about trying to get information from the PHP configuration form and then turn it into a java script variable and display it into the page.
I would like your views on how to do this and whether there is a better way and how to do that.

A: Zahir,
First, you have to store the information...
assuming you have this information already stored and have written the code that fetches the user information from the database:
You will need to echo out the values like so:

<?php echo $cert; ?>

IF you have yet to write the code for storing the information:
On the page where user fills out the form, have the form go to some page (could be the same page)--this page is specified in form tag's ACTION attribute.
All form data will be in $_POST; prior to making the call to the database for storing the form data, you must sanitize/validate it! (otherwise, your application will be vulnerable to attacks such as SQL Injection.
And then follow the step above.
Just some pointers to get you going... if you get more stuck write back.
Hope this helps,
-Rush


text:
Q: Python script closes without even running I wrote a python script to run some simple tasks and this issue has been happening randomly at times.
Upon clicking on .py file, a cmd prompt window appears for a some microseconds and closes immediately without showing any text.
I thought this issue was because the code finished running too fast at first but the code doesnt actually run. I know this because the code involves sending a text message on discord through the requests module and I can see post-running that no text has been sent.
If it was the prior assumed issue, I would've just added some input for the program to recieve but my program has an infinite while loop in it which should be already enough to keep the cmd window open. Hence I dont understand what's causing this.
The last time it happened I somehow found a solution which I followed step by step and was able to resolve it but its happening again now and I cant find that solution again unfortunately. From vague memory, I recall the solution involved running some commands on windows terminal.

A: Are you double clicking the .py file? If so, it may not work in some situations. What you should do is open up your cmd and type the following.
C:\Users\Admin> python filename.py
You can replace filename with your file's name.
If you are using Mac or any Apple devices, you will need to replace python with python3.


text:
Q: asp.net core 2.1 custom default route per user I'vew got an company internal website containing different areas implemented with asp.net core's area-logic.
I'd like to redirect the users to a homepage of their choice.
For Example:
User A: contonso.com/ showing index of area invoices
User B: contonso.com/ showing index of area customers
Possible workaround: Use a generic home controller that redirects the user to the appropriate area but i would like to know if there is a more generic solution using the build-in routing capabilities.
At the moment, i would stores those information in a database but actually i don't care how to configure, as long as I'm able to do the routing dynamically.
The docs and google doesn't say anything about this case.
Is there any way to get arround a custom middleware? Some buildin support, or an existing nuget-package?

A: You could try Middleware to redirect the requests based on your logic.
Here is a demo code for MVC Controller:
                   app.Use(async (context, next) =>
        {
            if (context.Request.Path == "/" && context.User.Identity.Name == "test@outlook.com")
            {
                context.Response.Redirect("Home/About", true);
            }
            else if (context.Request.Path == "/" && context.User.Identity.Name == "test1@outlook.com")
            {
                context.Response.Redirect("Home/Contact", true);
            }
            await next();
        });

        app.UseMvc(routes =>
        {
            routes.MapRoute(
                name: "default",
                template: "{controller=Home}/{action=Index}/{id?}");
        });

Note, change the redirect URL and MVC Route based on your Area

A: U can use action like this:
public IActionResult MyIndex()
{
    string action = // get action for user
    return RedirectToAction(action, "Home")
}

along with tag helper:
Go somewhere


text:
Q: Can I check for constraints before a delete in SQL Server? I have following situation. A main table and many other tables linked together with foreign keys. Now when I would like to delete a row in the main table a ConstraintsViolation will occur, which is intended and good.
Now I want to be able to check if the ConstraintsViolation will occur before I trigger the delete row event.
Is this possible?

A: This is a question that on the surface looks good, but has implications.
First of all, you'd need to ensure that after you've read the status of those relations, nobody could change those, so obviously you need to use a transaction and lock the rows in question.
Then you need a way to figure out what relations to check, as I see in a comment here your question about what happens if someone later adds a new relation. So you need to query the schema, or perhaps auto-generate this code from the schema, so that the detection mechanism only needs to run each time you change the schema.
Now, does the exception you get really seem that expensive after this ordeal?

A: If Exists ( Select * From OtherTable
            Where OtherTableFKColumn = MainTablePrimaryKey)
   Begin
       Rollback Transaction
       RaisError('Violating FK Constraint in Table [OtherTable]', 16, 1)
   End

A: Other than checking the COUNT(*) of every related table? I don't think so.

A: One ugly attempt would be to try a DELETE in a transaction and then force a ROLLBACK if it is successful. But this is to dirty for my taste.

A: I don't think it's a good idea to attempt something like  this because it means that every foreign key has to be checked twice: once by you beforehand, and then again by the server when you execute your SQL. The performance implications could be severe.
However, if you have your mind set on doing this, the most generic way involves using the database's data dictionary. I am not familiar with the SQL Server data dictionary, but other relational databases store all their metadata in database tables that you can query. You could find all the foreign keys that reference your table and dynamically build queries which look for dependent rows.


text:
Q: Disabling button after click for a certain period of time even after page reload I am working on simple POS restaurant ordering system. Here users can add items into their cart and easily checkout. I am trying to implement that user can only click once on checkout button for a specific time and when time's over button enable again.
By now, I have disabled the button for specific time, but that is not good solution, because when page refresh, buttons are enabled again.
DEMO: Can be find here.
Html:

        <button>checkout</button>

Jquery:
$.fn.disableFor = function(mins, secs) {
    var i = [],
    play = [];

    this.click(function() {
        var selector = $(this),
        inDex = $(selector).index(),
        prevText = $(selector).text();
        i[inDex] = 0;
        var inSeconds = mins * 60 + secs;

        $(selector).prop("disabled", "disabled");

        play[inDex] = setInterval(function() {
            if(inSeconds > 60){
                inSeconds = inSeconds - 1;
                var minutes = Math.floor(inSeconds / 60);
                var seconds = inSeconds % 60;
                if(minutes >= 1){
                    if(seconds.toString().length > 1){
                        $(selector).text(minutes + ":" + seconds + " minutes left");
                    }else{
                        $(selector).text(minutes + ":" + "0" + seconds + " minutes left");
                    }
                }else{
                    $(selector).text(seconds + " seconds left");
                }
            }else{
                if(inSeconds > 1){
                    inSeconds = inSeconds - 1;
                    if(inSeconds.toString().length > 1){
                        $(selector).text(inSeconds + " seconds left");
                    }else{
                        $(selector).text("0" + inSeconds + " seconds left");
                    }
                }else{
                    $(selector).prop("disabled", "");
                    clearInterval(play[inDex]);
                    $(selector).text(prevText);
                }
            }
        }, 1000);
    });
};

$(function() {
    $("button").disableFor(2,0); // First parameter stands for minutes and the second for the seconds.
});

A: You need to use browser localStorage to store the seconds.
Once you click on checkout button we will setItem time as the the seconds - In setIterval we will keep updated the time remaining in the button and once the time reaches the limit of end we will remove using removeItem the localStorage from the browser.
If the user refreshes the checkout page (This is where your question comes in) - We click on the checkout button the we will check if there is any time remaining in the localStorage for our key we have set in before.
If there is no remaining time we will use start the clock at 1 minutes and 15 seconds OR else we will start at the time remaining using getItem in the localStorage.
I have tested this code and it works perfectly.
Demo: (You need to try this in your own browser - localStorage is not supported in this snippet.)

$.fn.disableFor = function(mins, secs) {
  var i = [],
    play = [];

  this.click(function() {
    var selector = $(this),
      inDex = $(selector).index(),
      prevText = $(selector).text();
    i[inDex] = 0;

    //Store seconds
    var inSeconds = mins * 60 + secs;

    //Get the previous stored seconds - check local storage
    var retrievedObject = localStorage.getItem('time');
    if (retrievedObject) {
      inSeconds = retrievedObject
    }

    //Disable button
    $(selector).prop("disabled", "disabled");

    play[inDex] = setInterval(function() {
      if (inSeconds > 60) {
        localStorage.setItem('time', inSeconds); //Set time again
        inSeconds = inSeconds - 1;
        var minutes = Math.floor(inSeconds / 60);
        var seconds = inSeconds % 60;
        if (minutes >= 1) {
          if (seconds.toString().length > 1) {
            $(selector).text(minutes + ":" + seconds + " minutes left");
          } else {
            $(selector).text(minutes + ":" + "0" + seconds + " minutes left");
          }
        } else {
          $(selector).text(seconds + " seconds left");
        }
      } else {
        localStorage.setItem('time', inSeconds); //Set time again
        if (inSeconds > 1) {
          inSeconds = inSeconds - 1;
          if (inSeconds.toString().length > 1) {
            $(selector).text(inSeconds + " seconds left");
          } else {
            $(selector).text("0" + inSeconds + " seconds left");
          }
        } else {
          localStorage.removeItem('time');
          $(selector).prop("disabled", "");
          clearInterval(play[inDex]);
          $(selector).text(prevText);
        }
      }
    }, 1000);
  });
};

$(function() {
  $("button").disableFor(1, 15); // First parameter stands for minutes and the second for the seconds.
});
div {
  margin: 0 auto;
  padding: 10px;
  vertical-align: middle;
  background-image: -moz-linear-gradient(bottom, white 0%, #CCC 100%);
  background-image: -o-linear-gradient(bottom, white 0%, #CCC 100%);
  background-image: -webkit-linear-gradient(bottom, white 0%, #CCC 100%);
  background-image: -ms-linear-gradient(bottom, white 0%, #CCC 100%);
  background-image: linear-gradient(bottom, white 0%, #CCC 100%);
}

button {
  color: #2b2b2b;
  text-shadow: 0 1px 0 #999;
  font-size: 18px;
  font-weight: bold;
  text-transform: uppercase;
  cursor: pointer;
  margin: 0 5px;
  border-radius: 12px;
  -moz-box-shadow: 4px 4px 4px #CCC;
  -o-box-shadow: 4px 4px 4px #CCC;
  -ms-box-shadow: 4px 4px 4px #CCC;
  -webkit-box-shadow: 4px 4px 4px #CCC;
  box-shadow: 4px 4px 4px #CCC;
}

button:hover {
  color: #3c3c3c;
  background-image: -moz-linear-gradient(top, #CCC 0%, white 20%, #666 100%);
  background-image: -o-linear-gradient(top, #CCC 0%, white 20%, #666 100%);
  background-image: -ms-linear-gradient(top, #CCC 0%, white 20%, #666 100%);
  background-image: -webkit-linear-gradient(top, #CCC 0%, white 20%, #666 100%);
  background-image: linear-gradient(top, #CCC 0%, white 20%, #666 100%);
}

button:disabled {
  color: #999;
  cursor: default;
  background: #CCC;
}

    <button>checkout</button>

A: I think this code is quite self-explanatory. Let me know if something is not clear.
I used localStorage (just like AlwaysHelping in his answer) which unfortunately doesn't work in StackOverflow's sandbox. You can save this as an html file and open it locally to test it.

        <button>checkout</button>

A: Try this:
//start cookies functions
function setCookie(cname, cvalue, exdays) {
  var d = new Date();
  d.setTime(d.getTime() + (exdays*24*60*60*1000));
  var expires = "expires="+ d.toUTCString();
  document.cookie = cname + "=" + cvalue + ";" + expires + ";path=/";
}
function getCookie(cname) {
  var name = cname + "=";
  var decodedCookie = decodeURIComponent(document.cookie);
  var ca = decodedCookie.split(';');
  for(var i = 0; i <ca.length; i++) {
    var c = ca[i];
    while (c.charAt(0) == ' ') {
      c = c.substring(1);
    }
    if (c.indexOf(name) == 0) {
      return c.substring(name.length, c.length);
    }
  }
  return "";
}
function removeCookie(cname) {
  document.cookie = cname+"=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/;";
}
//end cookies functions

var cookieCheckout = getCookie('checkouttime');
var secondsTimeout = 0;
var delayTime = 2*60;
if (cookieCheckout && cookieCheckout != "") {// if we have cookie then set cookie seconds, when load page
  secondsTimeout = delayTime - Math.round((Date.now() - parseInt(cookieCheckout)) / 1000);
  if (secondsTimeout > delayTime) {
    removeCookie('checkouttime');
    //make checkout button enable
  } else {
    //make checkout button disable
  }
}

setCookie('checkouttime', Date.now(), 30);// set timestamp, when you click on enable checkout

if (secondsTimeout > delayTime) { //if time more then need limit then refresh timer, inside interval
  removeCookie('checkouttime');
  //make checkout button enable
}


text:
Q: Why is Apache2 failing? I have issues with the server constantly. It seems to fail every few hours and I cannot tell why.
This morning I had 503 on all of my websites, I tried to restart Apache but
# service apache2 restart
[....] Restarting web server: apache2(98)Address already in use:     make_sock: could not bind to address 127.0.0.1:8080
no listening sockets available, shutting down
Unable to open logs
Action 'start' failed.
The Apache error log may have more information.
failed!

I found out some of processes were still running. Killing them helped to restart Apache.
# grep -ri listen /etc/apache2
/etc/apache2/apache2.conf:#   supposed to determine listening ports     for incoming connections, and which
/etc/apache2/apache2.conf:# Include list of ports to listen on and     which to use for name based vhosts
/etc/apache2/ports.conf:Listen 127.0.0.1:8080
/etc/apache2/ports.conf:#Listen 127.0.0.1:443
/etc/apache2/ports.conf:#    Listen 443
/etc/apache2/ports.conf:#    Listen 443

# killall -9 apache2

# service apache2 restart
[ ok ] Restarting web server: apache2.

I still have no idea how to prevent it from failing, here are some logs that I totally don't understand. Please help :)
From the time when it failed:
[Sun May 31 06:26:00 2015] [notice] FastCGI: process manager initialized (pid 9466)
[Sun May 31 06:26:00 2015] [error] python_init: Python version mismatch, expected '2.7.2+', found '2.7.3'.
[Sun May 31 06:26:00 2015] [error] python_init: Python executable found '/usr/bin/python'.
[Sun May 31 06:26:00 2015] [error] python_init: Python path being used '/usr/lib/python2.7/:/usr/lib/python2.7/plat-linux2:/usr/lib/python2.7/lib-tk:/usr/lib/python2.7/lib-old:/usr/lib/python2.7/lib-dynload'.
[Sun May 31 06:26:00 2015] [notice] mod_python: Creating 8 session mutexes based on 1000 max processes and 0 max threads.
[Sun May 31 06:26:00 2015] [notice] mod_python: using mutex_directory /tmp
[Sun May 31 06:26:01 2015] [notice] Apache/2.2.22 (Debian) mod_fastcgi/mod_fastcgi-SNAP-0910052141 Phusion_Passenger/5.0.8 PHP/5.5.25-1~dotdeb+7.1 mod_python/3.3.1 Python/2.7.3 mod_ssl/2.2.22 OpenSSL/1.0.1e mod_wsgi/3.3 configured -- resuming normal operations
[Sun May 31 06:26:01 2015] [warn] long lost child came home! (pid 17083)
[Sun May 31 06:26:01 2015] [warn] long lost child came home! (pid 17328)
[Sun May 31 06:26:01 2015] [warn] long lost child came home! (pid 17329)
[Sun May 31 06:26:01 2015] [warn] long lost child came home! (pid 17330)

And this is logged basically constantly:
[Sun May 31 13:36:03 2015] [warn] Couldn't set uid/gid/priority, closing connection.
[Sun May 31 13:36:03 2015] [warn] (itkmpm: pid=30911 uid=1001, gid=1001) itk_post_perdir_config(): setgid(1005): Operation not permitted
[Sun May 31 13:36:03 2015] [warn] Couldn't set uid/gid/priority, closing connection.
[Sun May 31 13:36:03 2015] [warn] (itkmpm: pid=30897 uid=1001, gid=1001) itk_post_perdir_config(): setgid(1005): Operation not permitted
[Sun May 31 13:36:03 2015] [warn] Couldn't set uid/gid/priority, closing connection.
[Sun May 31 13:36:04 2015] [warn] (itkmpm: pid=30930 uid=1001, gid=1001) itk_post_perdir_config(): setgid(33): Operation not permitted
[Sun May 31 13:36:04 2015] [warn] Couldn't set uid/gid/priority, closing connection.
[Sun May 31 13:36:06 2015] [warn] (itkmpm: pid=30938 uid=1001, gid=1001) itk_post_perdir_config(): setgid(33): Operation not permitted


text:
Q: jenkins calling batch file get stuck in windows 7 I have a Jenkins server in windows 7 environment, and I run a batch file from jenkins. This batch file launches a jar that calls cmd.exe in order to connect to an instrument (spirent).
The above batch file fails when is started from jenkins, installed as a windows service, but works fine either if is started directly from cmd or from a jenkins started as
java -jar jenkins.war.....

A: If the windows service user running Jenkins is different than the user you are logged in as, you are likely running into a permissions issue. Possible solutions include changing the user running the service or modifying permissions necessary to allow the service user to perform the desired tasks.


text:
Q: Limit of matrix inverse: $\lim_{t\to\infty} (A+tJ)^{−1}$ This is very similar to, but different from, the following question:
Limit of matrix inverse: $\lim_{\lambda \to \infty} (A + \lambda I)^{-1} = \mathbf{0}$?
I would like to know how to find the limit of $(A+tJ)^{-1}$ as $t$ tends to infinity. Here $A$ is an arbitrary square matrix, and $J$ is a matrix of "all ones" the same size as $A$.
Using the idea that the inverse of a matrix is its adjoint divided by its determinant, or $$(A+tJ)^{-1} = \frac{(A+tJ)^*}{|A+tJ|},$$ I've found that both the numerator and the denominator are linear functions of $t$, i.e. $\displaystyle \frac{(A+tJ)^*}{|A+tJ|} = \frac{A^* + tP}{|A| + tq}$. As long as $q \ne 0$, the said limit should be $P/q$.
For example, in the case of a 2x2 matrix $A = \left[ \begin{array}{cc} a & b \\ c & d \end{array} \right]$, I have:
$$ \lim_{t \rightarrow \infty} (A+tJ)^{-1} = \lim_{t \rightarrow \infty} \frac{\left[ \begin{array}{cc} d & -b \\ -c & a \end{array} \right] + t \left[ \begin{array}{cc} 1 & -1 \\ -1 & 1 \end{array} \right]}{(ad-bc) + t(a+d-b-c)} = \frac{1}{a+d-b-c} \left[ \begin{array}{cc} 1 & -1 \\ -1 & 1 \end{array} \right] $$
(provided that $a+d-b-c \ne 0$)
But in general, is there a concise way to express the limit in terms of $A$?

A: Denote vector $j$ as a vector of ones, of as many rows as $A$, so $J=jj^T$.
By the Sherman-Morrison formula, $(A+tJ)^{-1}=A^{-1}-\frac{A^{-1}tjj^TA^{-1}}{1+tj^TA^{-1}j}$
$=A^{-1}-\frac{A^{-1}jj^TA^{-1}}{\frac{1}{t}+j^TA^{-1}j}$.
For the inquired limit, $\frac{1}{t}$ vanishes.

A: This is only correct if, and only if, $J$ is a full rank matrix.
Then you can prove this using by contradiction
Assume there is a vector $\mathbb x$ with bounded norm, (e.g. $||\mathbb x|| \le 1$) such that $(A + tJ)^{-1}\mathbb x=\mathbb z$ is non-zero
That also means that $(A + tJ)\mathbb z = \mathbb x$, but since $J$ is full rank, and $z$ is non-zero $J\mathbb z$ is non-zero, and it follows that $tJ\mathbb z$ must be unbounded.
On the other hand if $J$ is not full rank, exists $J\mathbb z = \mathbb 0$, for that case $(A+tJ)\mathbb z = \mathbb x$, for a non-zero $\mathbb z$ and a bounded $\mathbb x$, so $(A+tJ)^{-1}\mathbb x \ne \mathbb 0$ for some $\mathbb x$, it follows that $(A + tJ)^{-1} \ne \mathbb 0$.


text:
Q: C# different syntax in formatting numbers I got a simple question regarding formatting numbers in C#.
I have a format like this
{0:0.00######################}

which was suggested by this website, which basically showing at least 2 decimal places of a number.
Then this website has suggested a different format string
0.00######################

Now, I understand the former and latter have functional differences. For instance, I should use the former in string.Format() calls and the latter in Decimal.ToString() calls. But what I'd like to know is what's the importance in having the curly braces and the
0:

Any ideas?

A: When you're using String.Format, you can have more than one "item" which will be formatted.  This is determined by using {n} where n is the index into the list of values:
var result = string.Format("Arg1 == {0}, Arg2 == {1}", arg1, arg2);

This isn't required with Decimal.ToString and similar since there is only ever one value.
The 0: is really just {0}, and : is used to break out the format specification (everything after the : is effectively the same as what the ToString methods use).

A: When using String.Format, the curly braces indicate that you are placing a parameter to be replaced by a string.  The 0 indicates that it is the first parameter, so for example consider the following:
Console.WriteLine(String.Format("{0} {1} {2}", "A", "B", "C"));

Would output "A B C".  Whereas:
Console.WriteLine(String.Format("{2} {0} {1}", "A", "B", "C"));

Would output "C A B".
Hope that helps.

A: Curly braces is used as a "sign" to be replaced with the value. Number in the curly braces (0 based index) is the index pointing the value.
Example:
string.Format("{0:#,##0} {1:#,##0} {0:#,##0}", 2345, 6789);
Will resulting:
2,345 6,789 2,345


text:
Q: Analogy electric circuit and magnetic circuit - Power Here are a table which do the analogy between electric circuit and magnetic circuit. Nevertheless, there is no analogy with power dissipation …

Nevertheless, It is said that in a transformer with an air gap, the Energy is concentrated into the air gap… This is where the reluctance is maximal as the permeability is lower. If we consider the flux constant as the air gap is small. Then we can Apply the relation P = R*Flux ? What do you think ?
Thank You very much !


text:
Q: Does stale data due to weak level of consistency count as Byzantine failure? I have difficulty understand Section 18.3 Fault Tolerance Services under Ch18 Replication in   Coulouris' Distributed Systems. If my reading and understanding is correct (which might not),

*

*Section 18.3.1 Passive Replication describes services that have linearizability consistency but don't tolerate Byzantine failures.

*Section 18.3.2 Active Replication describes services that have weak (sequential) consistency but tolerate Byzantine failures.
In a distributed systems with data replication, does stale data i.e. data inconsistency due to weak level of consistency count as Byzantine failure? (Seems to me yes, but my reading above seems no.)
When a distributed system with replication is said to tolerate Byzantine failures, does it necessarily have the strict level of consistency, i.e. linearizability? (Seems to me yes, but my reading above seems no.)
Thanks.

A: Byzantine fault can appear to be both functioning and not functioning to diffrent actors.

a server can inconsistently appear both failed and functioning to failure-detection systems, presenting different symptoms to different observers

Consistency and Linearizability is usuallly solved with a consensus algorithm. But Byzantine faults is a more difficuly problem, on a higher order - since you must have consensus about what part is "struggling" in the first place.

It is difficult for the other components to declare it failed and shut it out of the network, because they need to first reach a consensus regarding which component has failed in the first place.


text:
Q: find the slope of the tangent line Sorry I couldn't figure out how to use the editor right now and I really need help with this question.
Let $f(x)=\frac{1}{\sqrt[3]{x}}$. find the slope of the tangent line at $(8,\frac{1}{2})$
So far this is what I have I just don't know what to do from here
$$
\begin{array}{lll}
m&=&\lim_{h \to 0}\frac{f(8+h)-f(8)}{h}\\
&=&\lim_{h \to 0} \frac{\frac{1}{\sqrt[3]{8+h}}-1/2}h \\
&=&\lim_{h \to 0} \ 2-\frac{\sqrt[3]{8+h}}{2\sqrt[3]{8+h}}\\
&=&\lim_{h \to 0} \frac{2-\sqrt[3]{8+h}}{2h\sqrt[3]{8+h}}\\
\end{array}
$$
Can someone please help me out please

A: From where you're at, do this trick:
\begin{align*}
&\lim_{h \to 0} \frac{2-\sqrt[3]{8+h}}{2h\sqrt[3]{8+h}}=\lim_{h \to 0} \frac{\left(2-\sqrt[3]{8+h}\right)}{2h\sqrt[3]{8+h}}\frac{\left((8+h)^{2/3} +2(8+h)^{1/3} + 4)\right)}{\left((8+h)^{2/3} +2(8+h)^{1/3} + 4)\right)}=\\
&\lim_{h\to 0}\frac{-h}{2h(8+h)^{1/3}\left((8+h)^{2/3} +2(8+h)^{1/3} + 4)\right)}= \\
&\lim_{h\to 0} -\frac{1}{2(8)^{1/3}(8^{2/3}+2\cdot8^{1/3}+4)}=-\frac{1}{48}
\end{align*}
Here's an equivalent limit proof.
\begin{align*}
&f'(8)=\lim_{x\to 8}\frac{f(x)-f(8)}{x-8} = \lim_{x\to 8}\frac{\frac{1}{x^{1/3}}-\frac{1}{2}}{(x^{1/3}-2)(x^{2/3}+2x^{\frac{1}{3}}+4)}= \\
&\lim_{x\to 8} \frac{\frac{2-x^{1/3}}{2x^{1/3}}}{(x^{1/3}-2)(x^{2/3}+2x^{1/3}+4)}=-\frac{1}{2}\lim_{x\to 8}\frac{1}{x^{1/3}(x^{2/3}+2x^{1/3}+4)}=\\
&-\frac{1}{2}\left(\frac{1}{2(4+4+4)}\right)=-\frac{1}{48}
\end{align*}


text:
Q: Add bars to a plot to show averages after applying pandas groupby I have a sample dataframe:
test = pd.DataFrame({'cluster':['1','1','1','1','2','2','2','2','2','3','3','3'],
                 'type':['a','b','c','a','a','b','c','c','a','b','c','a']})

Then I plot % of type values for each cluster by using groupby:
pct_col = test.groupby(['cluster','type'])['type'].count()/(test.groupby('cluster').size())*100 # don't reset the index!
test = test.set_index(['cluster', 'type']) # make the same index here
test['count %'] = pct_col
test = test.reset_index() # to take the hierarchical index off again
sns.catplot(x="cluster", y="count %", hue="type", kind="bar", data=test)

How can I add additional three bars showing the average for each type based on the whole data set --> test.groupby('type')['type'].count()/(len(test))*100
Will appreciate your help!

A: Using crosstab
pd.crosstab(test.cluster,test.type,normalize='index',margins=True)
Out[305]:
type            a         b         c
cluster
1        0.500000  0.250000  0.250000
2        0.400000  0.200000  0.400000
3        0.333333  0.333333  0.333333
All      0.416667  0.250000  0.333333

#pd.crosstab(test.cluster,test.type,normalize='index',margins=True).mul(100).stack()

update I thought plot is easy with pandas
pd.crosstab(test.cluster,test.type,normalize='index',margins=True).plot(kind='bar')


text:
Q: Using the "Alternative to the Magic Patch" on a server: good idea or bad idea? I have read this question:
Getting the alternative to the 200-Line Linux Kernel patch to work
And I am trying it on my desktop(s).
Is this a good idea for a server? Would it help in any way?
Edit:
I manage several servers:

*

*Web servers, running Apache/Cherokee + PHP-Fcgi + MySQL

*Django servers, running Cherokee + Python + MySQL

*Squid proxy, running Squid 2.7

*Zabbix server, running Zabbix 1.8 full stack

*OpenSuse 11.2, running iFolder 3.8 server (though obviously this one isn't the one I expect to get answers for in here... :))

A: I'd recommend that you do not apply it to a Ubuntu server. The change improves scheduling more or less specific to desktop usage. It won't improve server response. That's the core of the criticism made by that RedHat guy, whose name I won't bother mentioning.

A: Given that it's far more likely that your server is out performing most standard desktops  these days slowing down the system won't at all help responsiveness. Likely - if at all - you are experiencing performance issue it's main bottleneck is Disk IO. Since this patches doesn't improve read/write from disks you wouldn't gain any change in performance. Definitely not worth the trouble of patching X amount of kernels on your servers.

A: There is nothing magic about this patch, it just makes your system a bit slower but also more responsive for interactive use.
So I doubt it's very useful for your servers (except in some emergency circumstances maybe).

A: The "wonder patch" will provide better results in a desktop scenario, where you want something like 'make -j64' running in background without interfering with the other ("interactive") tasks. In your case, I assume you would want the scheduler to treat all your server processes equally... I'll have to agree with Marco and say that it is definitely not worth the trouble right now.


text:
Q: Why a child process fails to write to a shared memory? I have a simple program that writes to a shared memory and reads from a shared memory,  but while reading I am getting segmentation fault.
When I am debugging, the child process is not writing information to the shared memory, and after that, the parent process is trying to read from the shared memory which has no data and is throwing segmentation fault at 1st printf,  in parent printf("%d\n",ptr->nread);
Why the child process is not able to write data to the shared memory? (it is failing at ptr->nread=20; line)
#include<sys/types.h>
#include<sys/ipc.h>
#include<sys/shm.h>
#define  SIZE 5*1024
struct databuf{
    int nread;
    char *buf;
    int xyz;
};
    struct databuf* ptr;
main()
{
    int shmid,pid;
    shmid = shmget((key_t)1,SIZE,IPC_CREAT|0777);
    pid =  fork();
    if(pid==0)
    {
            ptr = (struct databuf *)shmat(shmid,(char*)0,0);
            ptr->nread=20;
            ptr->buf=ptr+sizeof(ptr->nread);
            strcpy(ptr->buf, "abc");
            ptr->xyz=20;
    }
    else
    {
        wait(0);
        ptr = (struct databuf *)shmat(shmid,(char*)0,0);
        printf("%d\n",ptr->nread);
        printf("%s\n",ptr->buf);
        printf("%d\n",ptr->xyz);
    }
    return 0;
}

A: If ptr->nread is failing then you should put a error checking code something like this, before acessing the ptr.
 ptr = (struct databuf *)shmat(shmid,(char*)0,0);
 if (data == (struct databuf *)(-1)) {
                perror("shmat failed");
                exit(1);
 }
 ptr->nread=20;

Ref: http://linux.die.net/man/2/shmat
ptr->buf=ptr+sizeof(ptr->nread);

could be  written as:
 ptr->buf=(char*)ptr+sizeof(struct databuf)+ptr->nread;

or
 ptr->buf=(char*)ptr+ptr->nread;

The string can now be accessed in the parent process.
Brief Explanation:
If you're using shared memory, you have to make sure all the data you want to access in other processes is in the shared memory segment. Leave the data at a specified offset(in your case ptr+ptr->nread) in the memory segment. And be careful not to overwrite the existing data in the shared memory. sizeof(ptr->nread) will yield the sizeof(int).

A: Leaving to one side all the other issues with the code, I think:
shmid = shmget((key_t)1, SIZE, IPC_CREAT|0777) ;

is probably a mistake, unless you can (somehow) guarantee that (key_t)1 is not in use elsewhere.  For parent-child communication, as in this case, the simpler approach is:
shmid = shmget((IPC_PRIVATE, SIZE, IPC_CREAT|0777) ;

In general, when something apparently inexplicable happens, I find it helps to make sure I have checked for error returns.  In this case: shmget() returning -1 or shmat() returning -1... and I suspect that both have happened.

Worked solution added by @WhozCraig:
The following example works, and likely does what you're trying to accomplish. Pay note to how we calculate the address we store in ptr->buf after we home ptr to our shared memory base address. We have to leave room for the structure, so we calculate the address to start the first byte past the structure back-side.
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include<sys/types.h>
#include<sys/ipc.h>
#include<sys/shm.h>

struct databuf
{
    int nread;
    char *buf;
    int xyz;
};

#define SIZE (5*1024)

int main()
{
    // acquire shared memory first (read/write access)
    int shmid = shmget(IPC_PRIVATE, SIZE, IPC_CREAT|0666);
    if (shmid == -1)
    {
        perror("Failed to acquire shared emory.");
        exit(EXIT_FAILURE);
    }

    // fork child process
    pid_t pid = fork();

    // both parent and child need this. may as well do both before
    //  special casing child vs. parent logic.
    struct databuf *ptr = shmat(shmid,(char*)0,0);
    if (ptr == (void*)(-1))
    {
        perror("Failed to map shared memory to our process");
        exit(EXIT_FAILURE);
    }

    // child process
    if (pid==0)
    {
        ptr->nread = 20;
        ptr->buf = ((char*)ptr) + sizeof(*ptr);
        strcpy(ptr->buf, "abc");
        ptr->xyz = 30;
    }

    // parent process
    else
    {
        wait(NULL);
        printf("ptr = %p, ptr->buf = %p\n", ptr, ptr->buf);
        printf("%d\n",ptr->nread);
        printf("%s\n",ptr->buf);
        printf("%d\n",ptr->xyz);
    }
    return 0;
}

Sample Output (varies by system obviously)
ptr = 0x80000, ptr->buf = 0x8000c
20
abc
30

it is worth noting that this:
ptr->buf = ((char*)ptr) + sizeof(*ptr);

could be written as the following, using typed-pointer math:
ptr->buf = (char*)(ptr + 1);

The location where the cast is applied is important. The first applies it before we do any math, so we need to account for octet count. The second applies it after the pointer math, so simply adding one to to the typed pointer ptr will move us to the memory immediately past our ptr structure base.
Best of luck.

A: If you have a pointer from type T, an addition by one to the pointer will increment it by sizeof(T).
So you have to replace:
ptr->buf=ptr+sizeof(ptr->nread);

to
ptr->buf= ((char*)ptr )+sizeof(ptr->nread);

If you don't do that, your pointer will be incremented by sizeof(T)^2.


text:
Q: Why are there so many verb+ing in this passage? This is a letter in Toeic book, it uses many verb-ing, so make me confuse. Someone could help me clear this.

The government has released its new plan to reform the education sector. Education minister, Adam Miller, explained that the government would make a number of radical changes such as introducing smaller class sizes and providing more funding for computers and books. The new policies were originally scheduled to be introduced last year. However, Mr.Miller put off bringing them in until now because of concerns with some of the details of the proposal. He said the new system should be operating by June at the latest

A: There two different places where the '-ing' form of a verb is used.
One is called the *gerund", which is the noun form of a verb.
Let's dissect this sentence from your example:

Education minister, Adam Miller, explained that the government would make a number of radical changes such as introducing smaller class sizes and providing more funding for computers and books.

The subject is "the government" and the verb is "make". "Introducing smaller class sizes" and "providing more funding" are nouns. (Techncially, noun phrases).
If it's not clear why these are nouns, let's simplify the sentence:

The government would make X and Y.

This is a simplified version of the sentence, which hopefully makes it clear that X and Y are things the government makes.
Given that "introducing smaller class sizes" functions as a noun, we need to use the noun form of the verb "introduce", which is the gerund "introducing".

However, Mr.Miller put off bringing them in until now because of concerns with some of the details of the proposal.

"Bringing them in" is a noun phrase here, as well. The verb is "put off". So again, the gerund form of "bring" is appropriate.

The OP's example also demonstrates the second use of "-ing", which is the continuous tense. The continuous tense refers to an action that is, was, or will be ongoing.
This sentence is using the future continuous tense:

He said the new system should be operating by June at the latest.

If "the new system" is a computer system for school administrators, then such a system typically runs without interruption for years, so it makes sense to use the continuous tense to describe that.
(N.B. There are a number of technicalities related to the continuous tense that I won't go into here.)


text:
Q: Github Pages React App index.html file not in root I have researched extensively and have not been able to find an answer to this issue. I'm thinking it might still not be solved! Is there any way to change the path of a React app (in webpack) so that the index.html file can be in the root, and not in a public folder? This would be so I can host my portfolio on github pages, which requires the index.html file to be in the root.

A: You can assign the publicPath as root  in output in webpack config file
like
  output: {
    filename: '[name].js',
    publicPath: '/',
},


text:
Q: C# doesn't catch execute non query exception I have this code that calls the stored procedure to 'insert' data to tables in SQL.
using (SqlConnection connection = new SqlConnection(Global_Variables.DBcon))
{
    SqlCommand cmd = new SqlCommand("sp_WinApps_Import_ERData", connection);
    cmd.CommandType = CommandType.StoredProcedure;
    connection.Open();
    try
    {
        cmd.ExecuteNonQuery();
        Console.WriteLine("file imported!");
    }

    catch (SqlException ex)
    {
        Console.WriteLine("BATCH ID ALREADY EXISTS!" + ex.Message );
    }
    finally
    {
        connection.Close();
    }
}

but the problem is, it doesn't catch the error in the 'try-catch method' i dont know why but my code is correct.
The Error says: "Violation of UNIQUE KEY constraint 'Cons_BatchID'. Cannot insert duplicate key in object 'dbo.tbl_WinApps_FileHeader'.
Timeout expired.  The timeout period elapsed prior to completion of the operation or the server is not responding.
The statement has been terminated."

A: I solved it guys. Go to Debug > Exceptions and i just 'unchecked thrown checkbox' in Common Language Runtime Exceptions


text:
Q: Creating an oracle database connection with Talend Open Studio I want to create a database connection with talend open studio. I have installed oracle 10g and sqlplus environnement.
When I have tried creating a connection, I get this error:
java.lang.RuntimeException: java.sql.SQLException: Listener refused the connection with the following error:
ORA-12505, TNS:listener does not currently know of SID given in connect descriptor

  at org.talend.core.model.metadata.builder.database.JDBCDriverLoader.getConnection(JDBCDriverLoader.java:164)
  at org.talend.core.model.metadata.builder.database.ExtractMetaDataUtils.connect(ExtractMetaDataUtils.java:1049)
  at org.talend.core.model.metadata.builder.database.ExtractMetaDataFromDataBase.testConnection(ExtractMetaDataFromDataBase.java:311)
  at org.talend.repository.ui.utils.ManagerConnection.check(ManagerConnection.java:266)
  at org.talend.repository.ui.wizards.metadata.connection.database.DatabaseForm.checkConnection(DatabaseForm.java:2294)
  at org.talend.repository.ui.wizards.metadata.connection.database.DatabaseForm.access$45(DatabaseForm.java:2217)
  at org.talend.repository.ui.wizards.metadata.connection.database.DatabaseForm$26.widgetSelected(DatabaseForm.java:2549)
  at org.eclipse.swt.widgets.TypedListener.handleEvent(TypedListener.java:234)
  at org.eclipse.swt.widgets.EventTable.sendEvent(EventTable.java:84)
  at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:1053)
  at org.eclipse.swt.widgets.Display.runDeferredEvents(Display.java:4066)
  at org.eclipse.swt.widgets.Display.readAndDispatch(Display.java:3657)
  at org.eclipse.jface.window.Window.runEventLoop(Window.java:825)
    ....

Here is my login and password:

this is the tnsnames.ora's content
# tnsnames.ora Network Configuration File: D:\oracle\product\10.2.0\db_1\network\admin\tnsnames.ora
# Generated by Oracle configuration tools.

ORCL =
     (DESCRIPTION =
         (ADDRESS = (PROTOCOL = TCP)(HOST = user)(PORT = 1521))
          (CONNECT_DATA =
             (SERVER = DEDICATED)
                (SERVICE_NAME = orcl)
                )
           )

      EXTPROC_CONNECTION_DATA =
       (DESCRIPTION =
         (ADDRESS_LIST =
             (ADDRESS = (PROTOCOL = IPC)(KEY = EXTPROC1))
         )
        (CONNECT_DATA =
          (SID = PLSExtProc)
            (PRESENTATION = RO)
        )
    )


text:
Q: How to convert 'const wchar*' to 'const char*' on Mac OS X? Is there a elegant way to convert 'const wchar *' to 'const char *' on Mac OS X?
Kat

A: Use wcstombs:
size_t wcstombs(char *dest, const wchar_t *src, size_t n);
Make sure you have your locale set appropriately.

A: It's hard to imagine why one would be using wchar_t on OS X, but here's how it can be done in standard C++:
#include <codecvt>

int main() {
    std::wstring_convert<std::codecvt_utf8<wchar_t>,wchar_t> convert;

    wchar_t const *ws = L"Steve Nash";
    std::string s = convert.to_bytes(ws);
    char const *cs = s.c_str();
}


text:
Q: How do I read data once, and then perform multiple manipulations on said data in C#? I've created a WindowsForm Application with 3 buttons.  A click on any of the buttons reads c:\data.txt and performs a different "analysis" of the data.  Button 1 might add the numbers in data.txt, Button 2 might average them, and Button 3 might multiply them.
Under each private void button1_Click I have a line of code that reads in the data from data.txt.  This seems inefficient to me since the same "ReadLines" code is in each of the 3 button click events.
Is there a way to read the data just ONCE, and then have my buttons perform their analysis?
This way, the "ReadLines" code is only used once, and the data is somehow shared with any of the button1_Click events.

A: This is not difficult - you need to have a field to hold the values you read - the field will be available to all of your functions in the class.
 private string[] data;

 // in constructor:
 data = File.ReadAllLines(@"c:\data.txt");

 // in your methods, simply use data

Another option is to have a LoadData method that checks if data is null or not and call it from your methods:
private void LoadData()
{
  if(data == null)
    data = File.ReadAllLines(@"c:\data.txt");
}

A: If you want to further maximise the efficiency you could use a field and a property to lazy load it.
private string[] _data;

private string[] Data
{
    get
    {
        return _data ?? _data = File.ReadAllLines(@"c:\data.txt");
    }
}

Now your calling code can just consume the property without having to check if the field is null and you don't load the data until you need it.

A: To your class add property that will perform lazy loading.
First add a place to store the data
private string[] _FileData;

Then add a new property
private string[] FileData
{
    get
    {
        if (_FileData != null && _FileData.Length > 0)
            return _FileData;

        _FileData = File.ReadAllLines(@"c:\data.txt");

        return _FileData;
    }
}

Then just use the FileData property to get the file text.  It will only get the file text the first time, after that, _FileData will hold your file, and it will just get returned when you access FileData.

A: Here's an equally generic answer ;)
You can declare a shared variable (e.g. a string) which, on each button click handler, you check to see is empty or null (String.IsNullOrEmpty(myString)). If it's empty, perform the ReadLines code and store the data in your string variable. Then do the processing on the variable.
The next time you click a button, you will see that your string is not empty, and just process the string, instead of having to read the file again.


text:
Q: How do you store an erb value inside input tags in Rails? When I try to show the name of a person inside my input tag using value, the name gets cut off as soon as there is a space. So when it should say John Doe, the input is only showing John. Does anyone know why it would do this in my rails app? The database is correct, and everything shows properly if I use  tags.
form class="panel data-abide" action="" id="form1">
  <fieldset >
    <legend>Please Enter the Information Below</legend>

      Adjuster's Name
        <input class="adjustorInfo" value=<%= @adjuster.adjuster_name %>/>

A: This is because the value for the value tag has not been put in quotes.
You should change it to
<input class="adjustorInfo" value="<%= @adjuster.adjuster_name %>"/>

When you pass it without quotes, the corresponding HTML looks like this
<input class="adjustorInfo" value=John Doe/>

which is then converted to what you are seeing
<input class="adjustorInfo" value="John"/>

Passing it inside quotes forms this which is the expected value
<input class="adjustorInfo" value="John Doe"/>


text:
Q: Highlight multiple row values based on another value in tableau I have a table with 4 columns grouped by first 2 columns. Something like below
Company Department  Department Rating   Org     Org Rating  Emp Type    Employee

A       Sales        1                  XX      2           External    John

        Ops          2                  XX      1           Hybrid      Mike

B       HR           1                  YY      2           Internal    Richard

        Dev          3                  ZZ      3           Internal    Julie

I want to highlight Department and Org based on values in ratings column (1- yellow, 2- red, 3-blue)
Could anyone guide on how to make it happen on tableau?

A: Tableau by default will only highlight measure values so in order to highlight dimensions you need to trick it a bit.

*

*First, you'll want to create two dummy columns with the formula min(1).  You can either create this through a calculated field or just double click and type them in the columns shelf.

*In the Marks card for each of the two new measures (not the All card), place Department on the text field in one and Org in the text field of the other.  Set the Mark type to be Text on both of them.

*Create a calculated field to define the colors.  The actual values don't matter here as you'll assign a color to them latter.  Put this on the All marks card on the Color Shelf.

*At this point, you might have something like...

*Now to finish it off you can do a few things:

*

*Double click on the color squares in the legend to reassign them

*Change formatting on the measure to get rid of the axis, zero lines, etc

*Move the label from the bottom to the top by creating a dual axis.


text:
Q: How to create a list file in VB?
Possible Duplicate:
Get a list of all files inside of a directory in vb.net

I need to search many file in a network drive. It is very slow to use the search function one by one in Window explorer under XP. My plan is to create a VB program to generate a whole list of available files in string format first, then use string search function in the list. My question is how to create a directory list using VB?
Thanks

A: See MSDN: Directory.GetFiles() method.

A: Someone had answered a somewhat similar question I found here, enter link description here
I might suggest trying using a contains method to check if an item contains a string and then adding this to a second list to contain possible matches. Something like

Imports System
Imports System.IO
Public Function GetFileMatches(byval searchText as string) as list(of string)

Dim fileMatches as new list(of string)

for each directory in GetDirectories("c:\", "*")
       for each file in GetFiles(directory,"*")
          if file.contains(searchText) then fileMatches.add(file)
       next

next

return fileMatches
End Function

Might be able to apply some threading to speed it up as well.

A: you can use FileSystemObject for this.
you can refer the link

A: You don't even need to use VB, just do
dir *.* /s > filelist.txt

And it will output the directory listing to file filelist.txt and you can open it in notepad.


text:
Q: Why my \verb-ish command is not escaped inside \VerbatimEnvironment? Here is the code:
\documentclass{article}
\usepackage{fancyvrb}
\NewDocumentCommand\foo{v}{\texttt{#1}}
\catcode`\|\active
\AtBeginDocument{\catcode`\|\active\def|{\foo|}}
\catcode`\| 12 %
\newenvironment{vvv}
  {\VerbatimEnvironment\begin{VerbatimOut}{a.txt}}
  {\end{VerbatimOut}}
\begin{document}
\begin{vvv}
hello, |world|!
\end{vvv}
\end{document}

It doesn't compile:
Runaway text?
hello, \foo \foo \foo \foo \foo \foo \foo \foo \foo \foo \foo \foo \foo \ETC.
! TeX capacity exceeded, sorry [main memory size=5000000].
|->\foo
        |
l.20 hello, |world|!

What's wrong? I expect my vvv environment to save hello, |world|! to the file a.txt. Maybe there is an approach better than \VerbatimEnvironment?

A: \documentclass{article}
\usepackage{fancyvrb}
\NewDocumentCommand\foo{v}{\texttt{#1}}
\catcode`\|\active
\AtBeginDocument{\catcode`\|\active\def|{\foo|}}
\catcode`\| 12 %
\newenvironment{vvv}
  {\catcode`\|=12 \VerbatimEnvironment\begin{VerbatimOut}{a.txt}}
  {\end{VerbatimOut}}
\begin{document}
\begin{vvv}
hello, |world|!
\end{vvv}
\end{document}


text:
Q: If $V$ is a subspace of $\ell^2$ that doesn't contain a sequence which has only finitely many nonzero elements, can the closure of $V$ contain it? Let $V$ be a infinite dimensionale subspace of $\ell^2$ such that it doesn't exist a sequence $v \in V$ which has only finitely many nonzero elements.
Let $W=\overline{V}$ be the closure of $V$
My question is: can $W$ space contain a sequence which has only finitely many nonzero elements ?
Thanks

A: Let $0<a<1$ and take $V=$ Span$(v_n)$ where $$v_n=(1, a^{2^n}, a^{2^{n+1}},\ldots)$$
Then $V$ satisfies your condition but $W$ contains $(1, 0, 0, \ldots)$.


text:
Q: (ObjC -> Swift) Convert function "init" & "textureNamed" I get some errors when I try to convert 2 functions in Swift!
ObjC
@property (nonatomic, strong) NSMutableDictionary *textureCache;

- (instancetype)init {
    if (self = [super init])
    {
        self.textureCache = [NSMutableDictionary dictionary];
    }
    return self;
}

- (SKTexture *)textureNamed:(NSString *)textureName {
    return _textureCache[textureName];
}

Swift
var textureCache: NSMutableDictionary?

public func init() -> Self {
    return textureCache = NSMutableDictionary()
}

public func textureNamed(textureName: String!) -> SKTexture! {
    return textureCache(textureName)
}

In the "init" function :

*

*Expected identifier in function declaration -> (public func init ->
Self)

*Cannot assign a value of type 'NSMutableDictionary' to a value of type 'NSMutableDictionary?' -> (return textureCache = NSMutableDictionary())

And for the "textureNamed" function :

*

*Cannot invoke 'textureCache' with an argument list of type '(String!)'
-> (return textureCache(textureName))

If someone could help me, it would be awesome.

A: I would try something like this:
class Test: NSObject {

  var textureCache = [String:SKTexture]()

  override init() {
    super.init()
  }

  func textureNamed(name: String) -> SKTexture? {
    return self.textureCache[name]
  }

}

A: Ok, let's decompose the problem.
Swift doesn't need a return type for init and if you have a superclass, you need to call super.init():
public func init() {
    super.init() //required if you have a superclass as the override after public
    textureCache = NSMutableDictionary()
}

Second problem, the method looks correct, the problem is related to the fact that textureCache is an Optional, so you have two solutions here.
Unwrap the variable and return the cached texture cached:
public func textureNamed(textureName: String!) -> SKTexture! {
    return textureCache?(textureName)
}

Or declare textureCache as non-optional value, because you are actually initializing it in the init method:
var textureCache: NSMutableDictionary

public func textureNamed(textureName: String!) -> SKTexture! {
       return textureCache(textureName)
    }

A: Thanks for your answers, it doesn't work in the both cases ! ^^
But you helped me a lot cuz I "found" a solution :
public init() {
    textureCache = NSMutableDictionary()
}

public func textureNamed(textureName: String!) -> SKTexture! {
    return textureCache?[textureName] as! SKTexture!
}

But I'm still not sure sure, the errors disappeared hoping it will not crash later...


text:
Q: Error receiving broadcast Intent Bluetooth adapter I'm having a problem passing an arrayList using an Intent. When the search finishes,and runs ACTION_DISCOVERY_FINISHED, the application just stop running.
DesafioActivity:(sender)
private final BroadcastReceiver mReceiver = new BroadcastReceiver() {

        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();

            if (BluetoothAdapter.ACTION_DISCOVERY_STARTED.equals(action)) {
                mDeviceList = new ArrayList<BluetoothDevice>();

                mProgressDlg.show();
            } else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)) {
                mProgressDlg.dismiss();

                Intent newIntent = new Intent(DesafioActivity.this, DeviceListActivity.class);

                newIntent.putParcelableArrayListExtra("device.list", mDeviceList);

                startActivity(newIntent);
            } else if (BluetoothDevice.ACTION_FOUND.equals(action)) {
                BluetoothDevice device = (BluetoothDevice) intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);

                mDeviceList.add(device);

                showToast("Dispositivo Encontrado " + device.getName());
            }
        }
    };

DevicesListActivity;(receiver)
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    setContentView(R.layout.activity_paired_devices);

    mDeviceList = getIntent().getExtras().getParcelableArrayList("device.list");

    mListView = (ListView) findViewById(R.id.lv_paired);

    mAdapter = new DeviceListAdapter(this);

    mAdapter.setData(mDeviceList);
    mAdapter.setListener(new DeviceListAdapter.OnPairButtonClickListener() {
        @Override
        public void onPairButtonClick(int position) {
            BluetoothDevice device = mDeviceList.get(position);

            if (device.getBondState() == BluetoothDevice.BOND_BONDED) {
                unpairDevice(device);
            } else {
                showToast("Pairing...");

                pairDevice(device);
            }
        }
    });

LogCat:
12-31 17:33:04.510: E/AndroidRuntime(14779): FATAL EXCEPTION: main
12-31 17:33:04.510: E/AndroidRuntime(14779): Process: com.AMOV.mr.fit, PID: 14779
12-31 17:33:04.510: E/AndroidRuntime(14779): java.lang.RuntimeException: Error receiving broadcast Intent { act=android.bluetooth.adapter.action.DISCOVERY_FINISHED flg=0x10 } in com.AMOV.mr.fit.DesafioActivity$1@4198efa8
12-31 17:33:04.510: E/AndroidRuntime(14779):    at android.app.LoadedApk$ReceiverDispatcher$Args.run(LoadedApk.java:785)
12-31 17:33:04.510: E/AndroidRuntime(14779):    at android.os.Handler.handleCallback(Handler.java:733)
12-31 17:33:04.510: E/AndroidRuntime(14779):    at android.os.Handler.dispatchMessage(Handler.java:95)
12-31 17:33:04.510: E/AndroidRuntime(14779):    at android.os.Looper.loop(Looper.java:136)
12-31 17:33:04.510: E/AndroidRuntime(14779):    at android.app.ActivityThread.main(ActivityThread.java:5144)
12-31 17:33:04.510: E/AndroidRuntime(14779):    at java.lang.reflect.Method.invokeNative(Native Method)
12-31 17:33:04.510: E/AndroidRuntime(14779):    at java.lang.reflect.Method.invoke(Method.java:515)
12-31 17:33:04.510: E/AndroidRuntime(14779):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:789)
12-31 17:33:04.510: E/AndroidRuntime(14779):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:605)
12-31 17:33:04.510: E/AndroidRuntime(14779):    at dalvik.system.NativeStart.main(Native Method)
12-31 17:33:04.510: E/AndroidRuntime(14779): Caused by: android.content.ActivityNotFoundException: Unable to find explicit activity class {com.AMOV.mr.fit/com.AMOV.mr.fit.DeviceListActivity}; have you declared this activity in your AndroidManifest.xml?
12-31 17:33:04.510: E/AndroidRuntime(14779):    at android.app.Instrumentation.checkStartActivityResult(Instrumentation.java:1628)
12-31 17:33:04.510: E/AndroidRuntime(14779):    at android.app.Instrumentation.execStartActivity(Instrumentation.java:1424)
12-31 17:33:04.510: E/AndroidRuntime(14779):    at android.app.Activity.startActivityForResult(Activity.java:3424)
12-31 17:33:04.510: E/AndroidRuntime(14779):    at android.app.Activity.startActivityForResult(Activity.java:3385)
12-31 17:33:04.510: E/AndroidRuntime(14779):    at android.app.Activity.startActivity(Activity.java:3627)
12-31 17:33:04.510: E/AndroidRuntime(14779):    at android.app.Activity.startActivity(Activity.java:3595)
12-31 17:33:04.510: E/AndroidRuntime(14779):    at com.AMOV.mr.fit.DesafioActivity$1.onReceive(DesafioActivity.java:149)
12-31 17:33:04.510: E/AndroidRuntime(14779):    at android.app.LoadedApk$ReceiverDispatcher$Args.run(LoadedApk.java:775)
12-31 17:33:04.510: E/AndroidRuntime(14779):    ... 9 more
12-31 17:33:06.855: I/Process(14779): Sending signal. PID: 14779 SIG: 9

A: DeviceListActivity isn't declared in your AndroidManifest.xml


text:
Q: Applying Dynamic Function Based on Logical Values in R I'm using openxlsx and I get to this point:
ABC = c(TRUE,TRUE,TRUE,FALSE,...,FALSE)

if (ABC) {writeData(Worksheet, Sheet = "Sheet1","Yes Please",
        startCol = 4,
        startRow = 3)}

I need an Excel file to say "Yes Please" when the value is TRUE. Second value (TRUE) would correspond to column 5, row 3. Forth value (FALSE) would correspond to column 7, row 3 and etc.
I thought about using loop to change the column number but not sure how to loop within argument for writeData.

A: Based on the condition, only the column number is incremented while the row is still the same. We can then use a simple hack using lapply.
lapply(1:length(ABC), function(x){
    if(ABC[x]) writeData(Worksheet, sheet = "Sheet1", "Yes Please",
    startCol = 4 + (x - 1), startRow = 3)
})

we use x to increment the column as well as an index for the vector ABC.


text:
Q: symbol is squished inside button I have a xamarin.forms app with some buttons which looks like this:

The problem is that the arrow to the left is squished for some reason.
Here is xaml code for left and right button:
<Button x:Name="btn_left" Text="◄" Clicked="btn_left_Clicked" Grid.Row="2" Grid.Column="1" Padding="-5" FontSize="Large"/> <--! Squished symbol -->
<Button x:Name="btn_right" Text="►" Clicked="btn_right_Clicked" Grid.Row="2" Grid.Column="3" Padding="-5" FontSize="Large"/>

It's not a big issue, but I would like it to be equal to the other arrows.


text:
Q: Crossfilter / dc.table sorting by Timestamp I want to sort my table by the timestamp descending but in this field my testcases ascending.
How can I do the oposite?
I hope i can explain my problem.
  //------------------------table------------------------------------
    var TestCaseDim2 = perfData.dimension(function (d) {
        return d.TestCase;
    });

    dc.dataTable('#data-table')
    .dimension(TestCaseDim2)
        .group(function (d) {
            return d.Timestamp.bold().fontcolor("darkblue");
        })
    .columns([

        function (d) { return d.SerialNumber;},
        function (d) { return d.Result;},
        ])
        .width(get2ndWindowSize())
        .order(d3.descending )
        .size(700)
        .renderlet(function (table) {
        table.selectAll('.dc-table-group').classed('info', true);
        });

I hope someone can help me.

A: In your JSFiddle example, I believe but am not sure that within your groups your test scripts are ordered by test case because that is the dimension you have used on your data table.
The real issue is that in a dc.js data table, you can't control the order of groups and the ordering within groups separately. The ordering within groups is based on the order returned by the dimension and the order of groups is determined by the text of the group. Both are either ascending or descending depending on what you set in dataTable.order.
So, what do we do? I'd recommend defining your dimension on the property you want to sort by within the groups, and then if necessary reversing the direction of the dimension sort by flipping the top/bottom functions on the dimension:
var perfData = crossfilter(data);
var testScriptDim = perfData.dimension(function (d) {
  return d.testscript;
});
testScriptDim.top = testScriptDim.bottom;

dc.dataTable('#data-table')
  .dimension(testScriptDim)
    .group(function (d) {
      return d.date.bold().fontcolor("darkblue");
    })
    .columns([
      function (d) { return d.testscript; },
      function (d) { return d.duration; },
      function (d) { return d.clickcount; }
    ])
    .size(100)
    .order(d3.descending)
    .renderlet(function (table) {
      table.selectAll('.dc-table-group').classed('info', true);
    });

Here's an updated version of your JSFiddle that I think does what you want: https://jsfiddle.net/esjewett/xzrp0ggv/1/


text:
Q: How is particle creation (or annihilation) possible in non-relativistic many body physics? How is that, in many-body physics, particle creation and annihilations are possible even though it is a non-relativistic theory?

A:
Can we have particle creation or annihilation in non-relativistic physics?

The answer is an emphatic yes. It is quite a routine in non-relativistic (NR) many-body physics.

How is particle creation or destruction possible without relativity?

Absence of relativity does not allow creation (and annihilation) of particle-antiparticle pairs (or mass) with disappearance (or appearance)
of energy. Non-relativistic physics, therefore, forbids energy turning into mass or vice-versa. Since relativity is not incorporated in non-relativistic many-body theory, mass creation or mass destruction is not possible.

What is happening then?

The energy supplied to a Fermi vacuum (which is simply the Fermi level) "creates" an electron-hole pair in the lattice. This electron-hole pair "creation" is not same as the electron-positron pair creation from the vacuum of a relativistic quantum field theory. Had it been so, one would have to supply at least $2m_ec^2$ amount of energy to the Fermi vacuum to create the electron-hole pair which is the minimum energy needed to create an electron-positron pair in relativistic physics. In metals, energy goes into the electron (already present at the Fermi level), which then absorbs it to get excited at a higher level. You can call this appearance of the electron above the Fermi level and the hole below it as the "creation" of the electron-hole pair. The typical incident energy $h\nu(\ll m_ec^2)$ is sufficient to really create an electron-hole.

Addendum

Moreover, particle creation may not require relativity if the particle is gapless excitation. This is the case for phonons and magnons which are essentially non-relativistic concepts. Any tiniest bit of energy will create them. The energy supplied goes to the lattice vibration and there is nothing like energy being converted to rest mass.
If we look at the "second-quantized" Schrodinger equation, the
Hamiltonian doesn't contain the rest energy. This is because, in non-relativistic physics, the mass cannot change to energy and therefore, mass is eternal and can be ignored in the Schrodinger equation. On the other hand, relativistic quantum field theories start with Lagrangians that include the rest mass from the very beginning.

A: I don't know if that is the case, but you may have been misguided by the formalism.
For convenience, the language of second quantization is often utilized in non-relativistic many body physics. So you may have stumbled upon creation and annihilation operators in that context. Nevertheless, even if written in second quantization, the Hamiltonians of many non-relativistic particles preserve the number of particles.
A concrete example: the Hamiltonian of $N$ non-relativistic bosons with pair interaction (symmetric) potential $V$ is usually written on $L^2_s(\mathbb{R}^{3N})$ (the symmetric $L^2$, under permutation of the three dimensional variables $x_i$, $i=1,\dotsc,N$) as:
$$H=\sum_{i=1}^N-\frac{\Delta_i}{2M}+\frac{1}{N}\sum_{i<j}V(x_i-x_j)$$
On the $N$-particle sector, $H$ agrees with the second quantized operator on $\Gamma_s(L^2(\mathbb{R}^3))$ (symmetric Fock space over $L^2(\mathbb{R}^3)$):
$$\tilde{H}=\int_{\mathbb{R}^3}a^*(x)\Bigl(-\frac{\Delta_x}{2M}\Bigr)a(x)dx+\frac{1}{2}\int_{\mathbb{R}^6}V(x-y)a^*(x)a^*(y)a(x)a(y)$$
So, as you see, the operator $\tilde{H}$ uses the formalism of creation and annihilation operators $a^\#(x)$, but the operator leaves each fixed particle sector invariant, as expected in a non-relativistic theory.


text:
Q: Using NLTK tokenizer with utf8 I am a fairly new user of Python and I work mainly with imported text files, especially csv's, which give me headaches to process. I tried to read the docs like this one : https://docs.python.org/2/howto/unicode.html but I don't understand a clue of what is being said. I just want some straight down-to-earth explanation.
For instance I want to tokenize a large number of verbatims exported from the internet as a csv file. I want to use NLTK's tokenizer to do so.
Here's my code:
with open('verbatim.csv', 'r') as csvfile:
    reader = unicode_csv_reader(csvfile, dialect=csv.excel)
    for data in reader:
        tokens = nltk.word_tokenize(data)

When I do a print() on data I get clean text.
But when I use the tokenizer method, it returns the following error :

'ascii' codec can't decode byte 0xe9 in position 31: ordinal not in
  range(128)

It looks like an encoding problem. And it's always the same problem with every little manipulation I do with text. Can you help me with this ?

A: This should do it:
with open('verbatim.csv') as csvfile:  # No need to set mode to 'r', r is default
    reader = unicode_csv_reader(csvfile, dialect=csv.excel)
    for data in reader:
        tokens = nltk.word_tokenize(unicode(data, 'utf-8'))

otherwise you can also try:
import codecs
with codecs.open('verbatim.csv', encoding='utf-8') as csvfile:
        reader = unicode_csv_reader(csvfile, dialect=csv.excel)
        for data in reader:
            tokens = nltk.word_tokenize(data)

A: First you have to understand that str and unicode are two different types.
There is a lot of documentation and great talks about the subject. I think this is one of the best: https://www.youtube.com/watch?v=sgHbC6udIqc
If you are going to work with text you should really understand the differences.
Overly simplified, str is a sequence of bytes. unicode is a sequence of "characters" (code points), to get a sequence of bytes to you encode the unicode object with and encoding.
Yes, complicated. My suggestion, watch the video.
I'm not sure what your unicode_csv_reader does but I'm guessing the problem is there as nltk works with unicode. So I'm guessing that in unicode_csv_reader you are trying to encode/decode something with the wrong codec.
In [1]: import nltk

In [2]: nltk.word_tokenize(u'mi papá tiene 100 años')
Out[2]: [u'mi', u'pap\xe1', u'tiene', u'100', u'a\xf1os']

I would use the package unicodecsv from pypi. Which returns a list of unicode objects for each line that you can pass to nltk.
import unicodecsv
with open('verbatim.csv', 'r') as csvfile:
    reader = unicodecsv.reader(csvfile, dialect=csv.excel, encoding='iso-8859-1')
    for data in reader:
        tokens = nltk.word_tokenize(data)

you can provide and encoding to the reader, and there's no need to use codecs to open the file.


text:
Q: Axis2 and Rampart Module Client I need a litle help using apache axis2 and rampart module, i am trying to use a cliente but i am stuck with the error

Exception in thread "main" java.lang.RuntimeException: Undefined 'Security policy namespace cannot be null.' resource property
      at org.apache.rampart.RampartException.getMessage(RampartException.java:81)
      at org.apache.rampart.RampartException.(RampartException.java:41)
      at org.apache.rampart.RampartException.(RampartException.java:57)
      at org.apache.rampart.RampartMessageData.setWSSecurityVersions(RampartMessageData.java:387)
      at org.apache.rampart.RampartMessageData.(RampartMessageData.java:261)
      at org.apache.rampart.MessageBuilder.build(MessageBuilder.java:61)
      at org.apache.rampart.handler.RampartSender.invoke(RampartSender.java:65)
      at org.apache.axis2.engine.Phase.invokeHandler(Phase.java:340)
      at org.apache.axis2.engine.Phase.invoke(Phase.java:313)
      at org.apache.axis2.engine.AxisEngine.invoke(AxisEngine.java:262)
      at org.apache.axis2.engine.AxisEngine.send(AxisEngine.java:427)
      at org.apache.axis2.description.OutInAxisOperationClient.send(OutInAxisOperation.java:406)
      at org.apache.axis2.description.OutInAxisOperationClient.executeImpl(OutInAxisOperation.java:229)
      at org.apache.axis2.client.OperationClient.execute(OperationClient.java:165)
      at axis2.services.SimpleServiceStub.sumar(SimpleServiceStub.java:189)
      at axis2client.Application1.(Application1.java:96)
      at axis2client.Application1.main(Application1.java:192)
  Process exited with exit code 1.

This is the source code of my web sevice client:
public Application1() throws Exception {
    SimpleServiceStub stub;
    try {
        ConfigurationContext ctx = ConfigurationContextFactory.createConfigurationContextFromFileSystem("C:\\AESPANA\\Axis2Test\\Axis2Client\\src\\axis2conf\\SimpleServiceConf",null);
        stub = new SimpleServiceStub(ctx,"http://172.17.24.147:8995/Axis2Service/services/SimpleService?wsdl");

        ServiceClient client=stub._getServiceClient();
        client.engageModule("rampart");

        RampartConfig rampartConfig=getRampartConfig();
        out_sec_policy.addAssertion(rampartConfig);

        client.getOptions().setProperty(RampartMessageData.KEY_RAMPART_OUT_POLICY, out_sec_policy);

        stub._setServiceClient(client);

        System.out.println("Llamando Cliente");
        SimpleServiceStub.Sumar sum1=new SimpleServiceStub.Sumar();
        sum1.setA(2);
        sum1.setB(3);
        System.out.println("Ejecutandolo Cliente");
        SimpleServiceStub.SumarResponse response1=stub.sumar(sum1);
        System.out.println(response1);

    } catch (AxisFault e) {
        e.printStackTrace();
    } catch (RemoteException e) {
        e.printStackTrace();
    }
}

private Policy loadPolicy(String name) throws XMLStreamException {
        InputStream resource;
    try {
        resource = new FileInputStream(name);
        StAXOMBuilder builder = new StAXOMBuilder(resource);
        return PolicyEngine.getPolicy(builder.getDocumentElement());
    } catch (FileNotFoundException e) {
        // TODO
    }
    return null;
}

private RampartConfig getRampartConfig(){

                RampartConfig rampartConfig = new RampartConfig();
                rampartConfig.setPwCbClass("axis2client.SimpleServicePWCBHandle");

                CryptoConfig sigCrypto = new CryptoConfig();

                sigCrypto.setProvider("org.apache.ws.security.components.crypto.Merlin");

                Properties props = new Properties();
                props.setProperty("org.apache.ws.security.crypto.merlin.keystore.type", "JKS");
                props.setProperty("org.apache.ws.security.crypto.merlin.file","C:\\AESPANA\\Axis2Test\\Axis2Client\\src\\axis2conf\\SimpleServiceConf\\keys\\client.jks");
                props.setProperty("org.apache.ws.security.crypto.merlin.keystore.password", "apache");

                sigCrypto.setProp(props);

                rampartConfig.setSigCryptoConfig(sigCrypto);
                rampartConfig.setEncrCryptoConfig(sigCrypto);

                Policy policy = new Policy();

                return rampartConfig;

        }

public static void main(String[] args) throws Exception {
    new Application1();
}}

This is the policy.xml file for the client.
<wsp:Policy wsu:Id="PoliticaOperacion"
            xmlns:wsp="http://schemas.xmlsoap.org/ws/2004/09/policy"
            xmlns:wsu="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd"
            xmlns:sp="http://docs.oasis-open.org/ws-sx/ws-securitypolicy/200802">
    <wsp:ExactlyOne>
        <wsp:All>
            <sp:AsymmetricBinding>
                <wsp:Policy>
                    <sp:InitiatorToken>
                        <wsp:Policy>
                            <sp:X509Token sp:IncludeToken="http://docs.oasis-open.org/ws-sx/ws-securitypolicy/200702/IncludeToken/AlwaysToRecipient">
                                <wsp:Policy>
                                    <sp:WssX509V3Token10/>
                                </wsp:Policy>
                            </sp:X509Token>
                        </wsp:Policy>
                    </sp:InitiatorToken>
                    <sp:RecipientToken>
                        <wsp:Policy>
                            <sp:X509Token sp:IncludeToken="http://docs.oasis-open.org/ws-sx/ws-securitypolicy/200702/IncludeToken/Never">
                                <wsp:Policy>
                                    <sp:WssX509V3Token10/>
                                </wsp:Policy>
                            </sp:X509Token>
                        </wsp:Policy>
                    </sp:RecipientToken>
                    <sp:AlgorithmSuite>
                        <wsp:Policy>
                            <sp:TripleDesRsa15/>
                        </wsp:Policy>
                    </sp:AlgorithmSuite>
                    <sp:Layout>
                        <wsp:Policy>
                            <sp:Strict/>
                        </wsp:Policy>
                    </sp:Layout>
                    <sp:IncludeTimestamp/>
                    <sp:OnlySignEntireHeadersAndBody/>
                </wsp:Policy>
            </sp:AsymmetricBinding>
            <sp:Wss10>
                <wsp:Policy>
                    <sp:MustSupportRefKeyIdentifier/>
                </wsp:Policy>
            </sp:Wss10>
        </wsp:All>
    </wsp:ExactlyOne>
</wsp:Policy>

The services.xml is this.
<serviceGroup>
    <service name="SimpleService"
             targetNamespace="http://ws.apache.org/axis2/samples/book/"
             xmlns:wsp="http://schemas.xmlsoap.org/ws/2004/09/policy"
             xmlns:wsu="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd"
             xmlns:sp="http://docs.oasis-open.org/ws-sx/ws-securitypolicy/200802">
        <module ref="rampart"/>
        <description>SimpleService</description>
        <schema schemaNamespace="http://ws.apache.org/axis2/samples/book/xsd/"/>
        <parameter name="ServiceClass" locked="false">axis2service.SimpleService</parameter>
        <operation name="sumar">
            <messageReceiver class="org.apache.axis2.rpc.receivers.RPCMessageReceiver"/>
        </operation>
        <parameter name="InflowSecurity">
            <action>
                <passwordCallbackClass>axis2service.SimpleServiceHandler</passwordCallbackClass>
                <signaturePropFile>service.properties</signaturePropFile>
                <signatureKeyIdentifier>DirectReference</signatureKeyIdentifier>
            </action>
        </parameter>
        <wsp:PolicyAttachment xmlns:wsp="http://schemas.xmlsoap.org/ws/2004/09/policy">
            <wsp:AppliesTo>
                <policy-subject identifier="binding:soap11/operation:sumar/in"/>
                <policy-subject identifier="binding:soap12/operation:sumar/in"/>
            </wsp:AppliesTo>
            <wsp:Policy wsu:Id="PoliticaOperacion">
                <wsp:ExactlyOne>
                    <wsp:All>
                        <sp:AsymmetricBinding>
                            <wsp:Policy>
                                <sp:InitiatorToken>
                                    <wsp:Policy>
                                        <sp:X509Token sp:IncludeToken="http://docs.oasis-open.org/ws-sx/ws-securitypolicy/200702/IncludeToken/AlwaysToRecipient">
                                            <wsp:Policy>
                                                <sp:WssX509V3Token10/>
                                            </wsp:Policy>
                                        </sp:X509Token>
                                    </wsp:Policy>
                                </sp:InitiatorToken>
                                <sp:RecipientToken>
                                    <wsp:Policy>
                                        <sp:X509Token sp:IncludeToken="http://docs.oasis-open.org/ws-sx/ws-securitypolicy/200702/IncludeToken/Never">
                                            <wsp:Policy>
                                                <sp:WssX509V3Token10/>
                                            </wsp:Policy>
                                        </sp:X509Token>
                                    </wsp:Policy>
                                </sp:RecipientToken>
                                <sp:AlgorithmSuite>
                                    <wsp:Policy>
                                        <sp:TripleDesRsa15/>
                                    </wsp:Policy>
                                </sp:AlgorithmSuite>
                                <sp:Layout>
                                    <wsp:Policy>
                                        <sp:Strict/>
                                    </wsp:Policy>
                                </sp:Layout>
                                <sp:IncludeTimestamp/>
                                <sp:OnlySignEntireHeadersAndBody/>
                            </wsp:Policy>
                        </sp:AsymmetricBinding>
                        <sp:Wss10>
                            <wsp:Policy>
                                <sp:MustSupportRefKeyIdentifier/>
                            </wsp:Policy>
                        </sp:Wss10>
                    </wsp:All>
                </wsp:ExactlyOne>
            </wsp:Policy>
        </wsp:PolicyAttachment>
    </service>
</serviceGroup>

This is the WSDL file
  <?xml version="1.0" encoding="UTF-8" ?>
- <wsdl:definitions xmlns:soap12="http://schemas.xmlsoap.org/wsdl/soap12/" xmlns:soap="http://schemas.xmlsoap.org/wsdl/soap/" xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:wsdl="http://schemas.xmlsoap.org/wsdl/" xmlns:wsaw="http://www.w3.org/2006/05/addressing/wsdl" xmlns:http="http://schemas.xmlsoap.org/wsdl/http/" xmlns:ns="http://ws.apache.org/axis2/samples/book/xsd/" xmlns:ns1="http://org.apache.axis2/xsd" xmlns:mime="http://schemas.xmlsoap.org/wsdl/mime/" xmlns:tns="http://ws.apache.org/axis2/samples/book/" targetNamespace="http://ws.apache.org/axis2/samples/book/">
- <wsp:Policy xmlns:wsp="http://www.w3.org/ns/ws-policy" xmlns:wsu="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd" wsu:Id="PoliticaOperacion">
- <wsp:ExactlyOne>
- <wsp:All>
- <sp:AsymmetricBinding xmlns:sp="http://docs.oasis-open.org/ws-sx/ws-securitypolicy/200802">
- <wsp:Policy xmlns:wsp="http://schemas.xmlsoap.org/ws/2004/09/policy">
- <sp:InitiatorToken>
- <wsp:Policy>
- <sp:X509Token>
- <wsp:Policy>
  <sp:WssX509V3Token10 />
  </wsp:Policy>
  </sp:X509Token>
  </wsp:Policy>
  </sp:InitiatorToken>
- <sp:RecipientToken>
- <wsp:Policy>
- <sp:X509Token>
- <wsp:Policy>
  <sp:WssX509V3Token10 />
  </wsp:Policy>
  </sp:X509Token>
  </wsp:Policy>
  </sp:RecipientToken>
- <sp:AlgorithmSuite>
- <wsp:Policy>
  <sp:TripleDesRsa15 />
  </wsp:Policy>
  </sp:AlgorithmSuite>
- <sp:Layout>
- <wsp:Policy>
  <sp:Strict />
  </wsp:Policy>
  </sp:Layout>
  <sp:IncludeTimestamp />
  <sp:OnlySignEntireHeadersAndBody />
  </wsp:Policy>
  </sp:AsymmetricBinding>
- <sp:Wss10 xmlns:sp="http://docs.oasis-open.org/ws-sx/ws-securitypolicy/200802">
- <wsp:Policy xmlns:wsp="http://schemas.xmlsoap.org/ws/2004/09/policy">
  <sp:MustSupportRefKeyIdentifier />
  </wsp:Policy>
  </sp:Wss10>
  </wsp:All>
  </wsp:ExactlyOne>
  </wsp:Policy>
  <wsdl:documentation>SimpleService</wsdl:documentation>
- <wsdl:types>
- <xs:schema targetNamespace="http://ws.apache.org/axis2/samples/book/xsd/" attributeFormDefault="qualified" elementFormDefault="qualified">
- <xs:element name="sumar">
- <xs:complexType>
- <xs:sequence>
  <xs:element name="a" minOccurs="0" type="xs:int" />
  <xs:element name="b" minOccurs="0" type="xs:int" />
  </xs:sequence>
  </xs:complexType>
  </xs:element>
- <xs:element name="sumarResponse">
- <xs:complexType>
- <xs:sequence>
  <xs:element name="return" minOccurs="0" type="xs:int" />
  </xs:sequence>
  </xs:complexType>
  </xs:element>
  </xs:schema>
  </wsdl:types>
- <wsdl:message name="sumarRequest">
  <wsdl:part name="parameters" element="ns:sumar" />
  </wsdl:message>
- <wsdl:message name="sumarResponse">
  <wsdl:part name="parameters" element="ns:sumarResponse" />
  </wsdl:message>
- <wsdl:portType name="SimpleServicePortType">
- <wsdl:operation name="sumar">
  <wsdl:input message="tns:sumarRequest" wsaw:Action="urn:sumar" />
  <wsdl:output message="tns:sumarResponse" wsaw:Action="urn:sumarResponse" />
  </wsdl:operation>
  </wsdl:portType>
- <wsdl:binding name="SimpleServiceSoap11Binding" type="tns:SimpleServicePortType">
  <soap:binding transport="http://schemas.xmlsoap.org/soap/http" style="document" />
- <wsdl:operation name="sumar">
  <soap:operation soapAction="urn:sumar" style="document" />
- <wsdl:input>
  <wsp:PolicyReference xmlns:wsp="http://www.w3.org/ns/ws-policy" URI="#PoliticaOperacion" />
  <soap:body use="literal" />
  </wsdl:input>
- <wsdl:output>
  <soap:body use="literal" />
  </wsdl:output>
  </wsdl:operation>
  </wsdl:binding>
- <wsdl:binding name="SimpleServiceSoap12Binding" type="tns:SimpleServicePortType">
  <soap12:binding transport="http://schemas.xmlsoap.org/soap/http" style="document" />
- <wsdl:operation name="sumar">
  <soap12:operation soapAction="urn:sumar" style="document" />
- <wsdl:input>
  <wsp:PolicyReference xmlns:wsp="http://www.w3.org/ns/ws-policy" URI="#PoliticaOperacion" />
  <soap12:body use="literal" />
  </wsdl:input>
- <wsdl:output>
  <soap12:body use="literal" />
  </wsdl:output>
  </wsdl:operation>
  </wsdl:binding>
- <wsdl:binding name="SimpleServiceHttpBinding" type="tns:SimpleServicePortType">
  <http:binding verb="POST" />
- <wsdl:operation name="sumar">
  <http:operation location="sumar" />
- <wsdl:input>
  <mime:content type="application/xml" part="parameters" />
  </wsdl:input>
- <wsdl:output>
  <mime:content type="application/xml" part="parameters" />
  </wsdl:output>
  </wsdl:operation>
  </wsdl:binding>
- <wsdl:service name="SimpleService">
- <wsdl:port name="SimpleServiceHttpSoap11Endpoint" binding="tns:SimpleServiceSoap11Binding">
  <soap:address location="http://http://172.17.24.150:8995/Axis2Service/services/SimpleService.SimpleServiceHttpSoap11Endpoint/" />
  </wsdl:port>
- <wsdl:port name="SimpleServiceHttpSoap12Endpoint" binding="tns:SimpleServiceSoap12Binding">
  <soap12:address location="http://http://172.17.24.150:8995/Axis2Service/services/SimpleService.SimpleServiceHttpSoap12Endpoint/" />
  </wsdl:port>
- <wsdl:port name="SimpleServiceHttpEndpoint" binding="tns:SimpleServiceHttpBinding">
  <http:address location="http://http://172.17.24.150:8995/Axis2Service/services/SimpleService.SimpleServiceHttpEndpoint/" />
  </wsdl:port>
  </wsdl:service>
  </wsdl:definitions>

My Service Class is this
public class SimpleService {

    public int sumar(int a, int b){
        return a+b;
    }
}

Can anyone help me please, I dont know how to solved it. any idea friens?


text:
Q: tool to share text file and notify collaborators of file changes? I would like a tool that will allow me to share a text file with a colleague, and if the file changes, will email them with a list of any additions or deletions.
I believe Dropbox can notify you (using RSS) if files are added or deleted from a shared folder, but I would like a tool that will email them a diff, a list of lines that have changed.
Ideally this tool would:

*

*allow me to work with a text file on my local hard drive (rather than on the web)

*allow them to edit the file and autosync to my local file, so that the next time I open the text file, their changes will be apparent

And again:

*

*if I update the file, my colleague automatically receives an email with a list of my changes and additions

*if they update the file, I automatically receive an email with a list of therir changes and additions

Does such a tool exist? Or is there a way to do this with Dropbox?

A: If you can run a webserver, one option would be Etherpad.
For a client based editing, there's Abiword which uses some centralized location to store the document.
Both above can be used to modify files at the same time, and see others changes in realtime.
At work we've used Microsoft Sharepoint, but that's not free or very nice to use (my opinion).