text:
Q: How can I scale my image down with the size of the screen in html/css, or is scaling even the issue? I have done this many times before, but I cannot seem to find the issue. The page is fine at a certain size, but once I start testing it out and scaling down to around 1260px width, the image starts to overflow and white space is created. I removed one of the column divs so the image was moved, and I could scale smaller before the white started to do this, but then part of my footer did the same thing. I know this likely has something to do with the @media queries, but things just got a little messy along the way and I had to take a break from the project. Can anybody point out what is going on?
Thanks.
Here is an image showing the issue.
Here is an image showing correct scaling and alignment.
I provided as much HTML as I could (the chunk with the image), without going over character limit.
And I have provided my entire CSS file below that.

iframe, h1, h2, h3, h4, h5, h6, p, blockquote,
pre, a, abbr, acronym, big, cite,
code, del, dfn, em, ins, kbd, q, s, samp,
small, strike, strong, sub, sup, tt, var, b,
u, i, center, dl, dt, dd, ol, ul, li, fieldset,
form, label, legend, table, caption, tbody,
tfoot, thead, tr, th, td, article, aside,
canvas, details, embed, figure, figcaption,
footer, header, hgroup, menu, output, ruby,
section, summary, time, mark, audio, video {
    margin: 0;
    padding: 0;
    border: 0;
    font: inherit;
    vertical-align: baseline;
}

article, aside, details, , figure,
footer, header, hgroup, menu, section {
    display: block;
}

body {
    line-height: 1;
}

ol, ul {
    list-style: none;
}

blockquote, q {
    quotes: none;
}

blockquote:before, blockquote:after, q:before, q:after {
    content: '';
    content: none;
}

table {
    border-collapse: collapse;
    border-spacing: 0;
}

body {
    -webkit-text-size-adjust: none;
}

mark {
    background-color: transparent;
    color: inherit;
}

input::-moz-focus-inner {
    border: 0;
    padding: 0;
}

input, select, textarea {
    -moz-appearance: none;
    -webkit-appearance: none;
    -ms-appearance: none;
    appearance: none;
}

/* Basic */

html {
    box-sizing: border-box;
}

*, *:before, *:after {
    box-sizing: inherit;
}

body {
    background: #fff;
}

body.is-preload *, body.is-preload *:before, body.is-preload *:after {
    -moz-animation: none !important;
    -webkit-animation: none !important;
    -ms-animation: none !important;
    animation: none !important;
    -moz-transition: none !important;
    -webkit-transition: none !important;
    -ms-transition: none !important;
    transition: none !important;
}

body, input, select, textarea {
    color: #666;
    font-family: "Source Sans Pro", Helvetica, sans-serif;
    font-size: 16pt;
    font-weight: 300;
    line-height: 1.65em;
}

a {
    -moz-transition: color 0.2s ease-in-out, border-color 0.2s ease-in-out;
    -webkit-transition: color 0.2s ease-in-out, border-color 0.2s ease-in-out;
    -ms-transition: color 0.2s ease-in-out, border-color 0.2s ease-in-out;
    transition: color 0.2s ease-in-out, border-color 0.2s ease-in-out;
    border-bottom: -webkit-link;
    color: #FFFFFF;
    text-decoration: none;
}

a:hover {
    border-bottom-color: transparent !important;
    color: #FFFFFF;
}

strong, b {
    color: #555;
    font-weight: 400;
}

em, i {
    font-style: italic;
}

p {
    margin: 0 0 2em 0;
}

h1, h2, h3, h4, h5, h6 {
    color: #fff;
    line-height: 1em;
    margin: 0 0 1em 0;
}

h1 a, h2 a, h3 a, h4 a, h5 a, h6 a {
    color: inherit;
    text-decoration: none;
}

h1 {
    font-size: 2.25em;
    line-height: 1.35em;
}

h2 {
    font-size: 2em;
    line-height: 1.35em;
}

h3 {
    font-size: 1.35em;
    line-height: 1.5em;
}

h4 {
    font-size: 1.25em;
    line-height: 1.5em;
}

h5 {
    font-size: 0.9em;
    line-height: 1.5em;
}

h6 {
    font-size: 0.7em;
    line-height: 1.5em;
}

/* Container */

.container {
    margin: 0 auto;
    max-width: calc(100% - 4em);
    width: 60em;
}

.container.xsmall {
    width: 15em;
}

.container.small {
    width: 30em;
}

.container.medium {
    width: 45em;
}

.container.large {
    width: 75em;
}

.container.xlarge {
    width: 90em;
}

.container.max {
    width: 100%;
}

.address {
    color: #2e3842;
    position: fixed;
}

.phone {
    float: right;
    font-size: x-large;
}

#tree-climber {
    max-width: 100%;
    height: 100%;
    display: block;
}

@media screen and (min-width: 980px) {

    .container {
        max-width: 100% !important;
        width: 100% !important;
    }

}

@media screen and (max-width: 480px) {

    .container {
        max-width: calc(100% - 3em);
    }

    .img {
        width: fit-content;
        display: block;
    }

}

/* Row */

.row {
    display: flex;
    flex-wrap: wrap;
    box-sizing: border-box;
    align-items: stretch;
}

.row > * {
    box-sizing: border-box;
}

.row > .col-4 {
    width: 33.33333%;
}

.row > .col-6 {
    width: 100%;
}

.row {
    margin-top: 0;
    margin-left: -2em;
}

.row > * {
    padding: 0 0 0 2em;
}

.row.gtr-uniform {
    margin-top: -2em;
}

.row.gtr-uniform > * {
    padding-top: 2em;
}

.row.gtr-150 {
    margin-top: 0;
    margin-left: -3em;
}

.row.gtr-150 > * {
    padding: 0 0 0 3em;
}

/* Section/Article */

section.special, article.special {
    text-align: center;
}

header p {
    color: #999;
    margin: 0 0 1.5em 0;
    position: relative;
}

header h2 + p {
    font-size: 1.25em;
    line-height: 1.5em;
    margin-top: -1em;
}

header h3 + p {
    font-size: 1.1em;
    line-height: 1.5em;
    margin-top: -0.8em;
}

header h4 + p,
header h5 + p,
header h6 + p {
    font-size: 0.9em;
    line-height: 1.5em;
    margin-top: -0.6em;
}

header.major {
    margin: 0 0 1em 0;
}

header.major:after {
    background: rgba(144, 144, 144, 0.5);
    content: '';
    display: inline-block;
    height: 1px;
    margin-top: 1.5em;
    width: 6em;
}

header.major h2, header.major h3, header.major h4, header.major h5, header.major h6 {
    margin: 0;
}

/* Image */

.image {
    border-radius: 4px;
    border: 0;
    display: inline-block;
    position: relative;
}

.image img {
    border-radius: 4px;
    display: block;

}

.image.left {
    float: left;
    padding: 0 1.5em 1em 0;
    top: 0.25em;
}

.image.right {
    float: right;
    padding: 0 0 1em 1.5em;
    top: 0.25em;
}

.image.left, .image.right {
    max-width: 40%;
}

.image.left img, .image.right img {
    width: 100%;
}

.image.fit {
    display: block;
    margin: 0 0 2em 0;
    width: 100%;
}

.image.fit img {
    width: 100%;
}

/* List */

ol {
    list-style: decimal;
    margin: 0 0 2em 0;
    padding-left: 1.25em;
}

ol li {
    padding-left: 0.25em;
}

ul {
    list-style: disc;
    margin: 0 0 2em 0;
    padding-left: 1em;
}

ul li {
    padding-left: 0.5em;
}

ul.alt {
    list-style: none;
    padding-left: 0;
}

ul.alt li {
    border-top: solid 1px rgba(144, 144, 144, 0.5);
    padding: 0.5em 0;
}

ul.alt li:first-child {
    border-top: 0;
    padding-top: 0;
}

dl {
    margin: 0 0 2em 0;
}

/* Actions */

ul.actions {
    display: -moz-flex;
    display: -webkit-flex;
    display: -ms-flex;
    display: flex;
    cursor: default;
    list-style: none;
    margin-left: -1em;
    padding-left: 0;
}

ul.actions li {
    padding: 0 0 0 1em;
    vertical-align: middle;
}

ul.actions.special {
    -moz-justify-content: center;
    -webkit-justify-content: center;
    -ms-justify-content: center;
    justify-content: center;
    width: 100%;
    margin-left: 0;
}

ul.actions.special li:first-child {
    padding-left: 0;
}

/* Button */

input[type="submit"],
input[type="reset"],
input[type="button"],
button,
.button {
    -moz-appearance: none;
    -webkit-appearance: none;
    -ms-appearance: none;
    appearance: none;
    -moz-transition: background-color 0.2s ease-in-out, color 0.2s ease-in-out;
    -webkit-transition: background-color 0.2s ease-in-out, color 0.2s ease-in-out;
    -ms-transition: background-color 0.2s ease-in-out, color 0.2s ease-in-out;
    transition: background-color 0.2s ease-in-out, color 0.2s ease-in-out;
    background-color: floralwhite;
    border-radius: 4px;
    border: 0;
    box-shadow: inset 0 0 0 1px rgba(144, 144, 144, 0.5);
    color: #555 !important;
    cursor: pointer;
    display: inline-block;
    font-size: 0.9em;
    font-weight: 400;
    height: 2.75em;
    letter-spacing: 0.125em;
    line-height: 2.75em;
    padding: 0 2em;
    text-align: center;
    text-decoration: none;
    text-indent: 0.125em;
    text-transform: uppercase;
    white-space: nowrap;
}

input[type="submit"].wide,
input[type="reset"].wide,
input[type="button"].wide,
button.wide,
.button.wide {
    min-width: 12em;
}

input[type="submit"].disabled, input[type="submit"]:disabled,
input[type="reset"].disabled,
input[type="reset"]:disabled,
input[type="button"].disabled,
input[type="button"]:disabled,
button.disabled,
button:disabled,
.button.disabled,
.button:disabled {
    cursor: default;
    opacity: 0.25;
}

/* Main */

.main {
    padding: 6em 0 4em 0;
}

.main.style1 {
    background: #2e3842;
}

.main.style2 {
    background-color: #333;
    color: rgba(255, 255, 255, 0.75);
    background-attachment: fixed, fixed;
    background-size: contain;
    }

.main.style2 a {
    border-bottom-color: rgba(255, 255, 255, 0.5);
}

.main.style2 a:hover {
    color: #ffffff;
}

.main.style2 h1, .main.style2 h2, .main.style2 h3, .main.style2 h4, .main.style2 h5, .main.style2 h6, .main.style2 strong, .main.style2 b {
    color: #ffffff;
}

.main.style2 header p {
    color: #ffffff;
}

.main.style2 header.major:after {
    background: #ffffff;
}

.main.style2 input[type="submit"]:hover,
.main.style2 input[type="reset"]:hover,
.main.style2 input[type="button"]:hover,
.main.style2 button:hover,
.main.style2 .button:hover {
    background-color: rgba(255, 255, 255, 0.125);
}

.main.style2 input[type="submit"]:active,
.main.style2 input[type="reset"]:active,
.main.style2 input[type="button"]:active,
.main.style2 button:active,
.main.style2 .button:active {
    background-color: rgba(255, 255, 255, 0.25);
}

.main.style2 input[type="submit"].primary,
.main.style2 input[type="reset"].primary,
.main.style2 input[type="button"].primary,
.main.style2 button.primary,
.main.style2 .button.primary {
    background-color: #ffffff;
    box-shadow: inset 0 0 0 1px #ffffff !important;
    color: #333 !important;
}

.main.style2 input[type="submit"].primary:hover,
.main.style2 input[type="reset"].primary:hover,
.main.style2 input[type="button"].primary:hover,
.main.style2 button.primary:hover,
.main.style2 .button.primary:hover {
    background-color: rgba(255, 255, 255, 0.125) !important;
    color: #ffffff !important;
}

.main.style2 ul.major-icons li .icon {
    border-color: #ffffff;
}

.main.style2 .icon.major {
    color: #ffffff;
}

/* Header */

#header {
    padding: 20em 0 9em 0;
    background-color: #4686a0;
    color: rgba(255, 255, 255, 0.75);
    background-attachment: fixed, fixed, fixed;
    background-image: url('/static/images/tree-stump-pile.webp');
    background-position: top left, center center, center center;
    background-size: auto, cover, cover;
    overflow: hidden;
    position: relative;
    text-align: center;
}

#header a {
    border-bottom-color: rgba(255, 255, 255, 0.5);
    color: inherit;
}

#header a:hover {
    color: #ffffff;
}

#header h1, #header h2, #header h3, #header h4, #header h5, #header h6, #header strong, #header b {
    color: #ffffff;
}

#header header p {
    color: #ffffff;
}

#header header.major:after {
    background: #ffffff;
}

#header h1 {
    margin: 0;
}

#header p {
    margin: 1em 0 0 0;
}

#header .actions {
    -moz-justify-content: center;
    -webkit-justify-content: center;
    -ms-justify-content: center;
    justify-content: center;
    margin-top: 2.5em;
    margin-left: 0;
    position: relative;
}

#header .actions li:first-child {
    padding-left: 0;
}

#header .actions:after {
    background: #ffffff;
    content: '';
    height: 100vh;
    left: 50%;
    position: absolute;
    top: 100%;
    width: 1px;
}

#header .inner {
    -moz-transition: -moz-transform 1.5s ease, opacity 2s ease;
    -webkit-transition: -webkit-transform 1.5s ease, opacity 2s ease;
    -ms-transition: -ms-transform 1.5s ease, opacity 2s ease;
    transition: transform 1.5s ease, opacity 2s ease;
    -moz-transition-delay: 0.25s;
    -webkit-transition-delay: 0.25s;
    -ms-transition-delay: 0.25s;
    transition-delay: 0.25s;
    -moz-transform: scale(1);
    -webkit-transform: scale(1);
    -ms-transform: scale(1);
    transform: scale(1);
    opacity: 1;
    position: relative;
    z-index: 1;
}

#header .inner .actions {
    -moz-transition: -moz-transform 1.25s ease;
    -webkit-transition: -webkit-transform 1.25s ease;
    -ms-transition: -ms-transform 1.25s ease;
    transition: transform 1.25s ease;
    -moz-transition-delay: 1s;
    -webkit-transition-delay: 1s;
    -ms-transition-delay: 1s;
    transition-delay: 1s;
    -moz-transform: translateY(0);
    -webkit-transform: translateY(0);
    -ms-transform: translateY(0);
    transform: translateY(0);
    opacity: 1;
}

#header:after {
    -moz-transition: opacity 1s ease;
    -webkit-transition: opacity 1s ease;
    -ms-transition: opacity 1s ease;
    transition: opacity 1s ease;
    content: '';
    height: 100%;
    left: 0;
    opacity: 0;
    position: absolute;
    top: 0;
    width: 100%;
}

body.is-preload #header .inner {
    -moz-transform: scale(1.05);
    -webkit-transform: scale(1.05);
    -ms-transform: scale(1.05);
    transform: scale(1.05);
    opacity: 0;
}

body.is-preload #header .inner .actions {
    -moz-transform: translateY(30em);
    -webkit-transform: translateY(30em);
    -ms-transform: translateY(30em);
    transform: translateY(30em);
    opacity: 0;
}

body.is-preload #header:after {
    opacity: 1;
}

/*Logo*/

#logo {
    position: fixed;
    top: 0;
    left: 0;
    opacity: 0.5;
    z-index: 0;
}

/* Navbar */

.content {
    width: 94%;
    margin: 4em auto;
    font-size: 20px;
    line-height: 30px;
    text-align: justify;
}

.logo {
    line-height: 60px;
    position: fixed;
    float: left;
    margin: 16px 46px;
    color: #fff;
    font-weight: bold;
    font-size: 20px;
    letter-spacing: 2px;
}

nav {
    position: fixed;
    width: 100%;
    line-height: 60px;

}

nav ul {
    line-height: 60px;
    list-style: none;
    background: rgba(0, 0, 0, 0.2);
    overflow: hidden;
    color: #ffffff;
    padding: 0;
    text-align: right;
    margin: 0;
    padding-right: 40px;
    transition: 1s;
}

nav.black ul {
    background: #000;
}

nav ul li {
    display: inline-block;
    padding: 16px 40px;;
}

nav ul li a {
    text-decoration: none;
    color: #fff;
    font-size: 16px;
}

.menu-icon {
    line-height: 60px;
    width: 100%;
    background: #000;
    text-align: right;
    box-sizing: border-box;
    padding: 15px 24px;
    cursor: pointer;
    color: #fff;
    display: none;
    opacity: 0.6;
}
/* Footer */

.site-footer
{
  background-color:#26272b;
  padding:45px 0 20px;
  font-size:15px;
  line-height:24px;
  color:#737373;
}
.site-footer hr
{
  border-top-color:#bbb;
  opacity:0.5
}
.site-footer hr.small
{
  margin:20px 0
}
.site-footer h6
{
  color:#fff;
  font-size:16px;
  text-transform:uppercase;
  margin-top:5px;
  letter-spacing:2px
}
.site-footer a
{
  color:#737373;
}
.site-footer a:hover
{
  color:#3366cc;
  text-decoration:none;
}
.footer-links
{
  padding-left:0;
  list-style:none
}
.footer-links li
{
  display:block
}
.footer-links a
{
  color:#737373
}
.footer-links a:active,.footer-links a:focus,.footer-links a:hover
{
  color:#3366cc;
  text-decoration:none;
}
.footer-links.inline li
{
  display:inline-block
}
.site-footer .social-icons
{
  text-align:right
}
.site-footer .social-icons a
{
  width:40px;
  height:40px;
  line-height:40px;
  margin-left:6px;
  margin-right:0;
  border-radius:100%;
  background-color:#33353d
}
.copyright-text
{
  margin:0
}
@media (max-width:991px)
{
  .site-footer [class^=col-]
  {
    margin-bottom:30px
  }
}
@media (max-width:767px)
{
  .site-footer
  {
    padding-bottom:0
  }
  .site-footer .copyright-text,.site-footer .social-icons
  {
    text-align:center
  }
}
.social-icons
{
  padding-left:0;
  margin-bottom:0;
  list-style:none
}
.social-icons li
{
  display:inline-block;
  margin-bottom:4px
}
.social-icons li.title
{
  margin-right:15px;
  text-transform:uppercase;
  color:#96a2b2;
  font-weight:700;
  font-size:13px
}
.social-icons a{
  background-color:#eceeef;
  color:#818a91;
  font-size:16px;
  display:inline-block;
  line-height:44px;
  width:44px;
  height:44px;
  text-align:center;
  margin-right:8px;
  border-radius:100%;
  -webkit-transition:all .2s linear;
  -o-transition:all .2s linear;
  transition:all .2s linear
}

/* XLarge */

@media screen and (max-width: 1680px) {

    /* Basic */
    body, input, select, textarea {
        font-size: 14pt;
    }

    /* Header */
    #header {
        padding: 6em 0 6em 0;
    }

}

Lorem ipsum dolor adipiscing

                        amet dolor consequat

Adipiscing a commodo ante nunc accumsan interdum mi ante adipiscing. A nunc lobortis non nisl
                    amet
                    vis volutpat aclacus nascetur ac non. Lorem curae eu ante amet sapien in tempus ac.
                    Adipiscing
                    id
                    accumsan adipiscing ipsum.

A: I think this can help you:
On the code bellow you selected the image using the id selector:
#tree-climber {
    max-width: 100%;
    height: 100%;
    display: block;
}

But here you defined as a class:

Because of this your styling is not working.
You just have to use the class selector:
.tree-climber {
    max-width: 100%;
    height: 100%;
    display: block;
}


text:
Q: How to know when all superviews did load in nested views As i understood, nested views are loaded from inner ones so viewDidLoad method for inner views run before superviews! and all parent and super properties are nil...
I need to initialize inner view when it loaded. Currently i've created methods in inner classes and call them in grand parent viewDidLoad method. Is there any similar method to be executed when screen is fully loaded?

A: *

*viewDidLoad is method of UIViewController. Not UIView. So you
cant use viewDidLoad for UIView.

*You mentioned ...

I need to initialize inner view when it loaded.

In fact, it is good you add this view when it is properly initialized.

*

*You can make use of viewWillAppear and put your checks and use viewDidLoad appropriately there after.

//Much better here:
-(void) tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath
{
    if([indexPath row] == lastRow){
        //end of loading
    }
}

Where lastRow is
[tableView numberOfRowsInSection: 0] - 1

redpajama_set_name: RedPajamaStackExchange


text:
Q: Max limit on number of input in vs code java I am trying some algorithm which requires large no of input samples for testing but at a time I cannot take input more than certain number of times.
N = sc.nextInt();
...
int[] arr = new int[N];

for(int i=0; i<N; i++){
  arr[i] = sc.nextInt();
}

for(int elem: arr){
  System.out.println(elem+" ");
}

Input format is
N
//HERE GOES ARRAY ELEMENTS

where N- no of element in array
I'm using this user input test_case_1, but I can only input fraction of the given values.
I wanted to know what is restricting the number of input in vscode

A: Usually, using a scanner is perfectly alright. But with input samples of up to 90 000, which seems to be test case 1, it might be very slow due to excessive flushing.
Something like this might be more effective:
BufferedReader br = new BufferedReader(new FileReader("temp_code_input.txt"));
...
int N = Integer.parseInt(br.readLine());
...
StringTokenizer st = new StringTokenizer(br.readLine());
/*
Assumes every input is on the same line. If not, create a new StingTokenizer
for each new line of input.
*/
int[] arr = new int[N];
for (int i = 0; i < N; i++) {
  arr[i] = Integer.parseInt(st.nextToken());
}

for (int elem : arr) {
  System.out.println(elem)
}

A:
I'm just manually inputting the values by pasting it

It would be easier for you to just read this input from a file with the Scanner class.
      String s = Files.readString("PATH_TO_YOUR_FILE", StandardCharsets.US_ASCII);

      // create a new scanner with the specified String Object
      Scanner scanner = new Scanner(s);

      // find the next int token and print it
      // loop for the whole scanner
      while (scanner.hasNext()) {

         // if the next is a int, print found and the int
         if (scanner.hasNextInt()) {
            //Store the data here ...
         }
         // if no int is found, print "Not Found:" and the token
         System.out.println("Not Found :" + scanner.next());
      }

A: When i test the input you provided, it stops and not accept more numbers when i paste them, so i ask in github: Limit max number of terminal input then get the reply:

when I paste your example input into the terminal, it succeeds
(although takes quite awhile) - what you might be seeing is the output
(pasted text) trimmed relative to what you're expecting because of the
maximum terminal scrollback which can be configured with
terminal.integrated.scrollback

So please waiting because it would succeed that pasting the input. Enlarge the value of terminal.integrated.scrollback in Settings.json to check the output.


text:
Q: Trying to install cordova with 'npm.cmd' but automatically close after a few second I want to learn about developing android apps using Cordova. I'm using this tutorial.
I can't proceed to the next steps:
C:\>npm install -g cordova

Because when I open the npm.cmd it always automatically closes after 0.5 seconds!
I dont know why.
i have tried from this StackOverflow thread:
npm.cmd closes instantly after few seconds
But still can't open npm.cmd.

A: Don't use npm.cmd use your platform terminal on windows you can open command Prompt check for node you can use node -v if node exists you can run npm install -g cordova


text:
Q: Replace keys with values in a Hash What is the best way to replace all keys with values in a hash?
I came up with:
Hash[hash.map {|k,v| [v,k]}]

Is there a better solution?

A: There's a built-in method for that:
 hash.invert

A: It's possible to invert a hash:
{ 'a' => 1, 'b' => 2 }.invert # => {1=>"a", 2=>"b"}

But be careful of the side-effects:
{ 'a' => 1, 'b' => 2, 'c' => 2 }.invert # => {1=>"a", 2=>"c"}

A hash's keys must be unique, but values don't have to be. When you invert the hash the duplicate values will collide, overwriting each other, with the last one winning.


text:
Q: How to call a WebService which has a querystring data? I have a webservice which i need to call in .net application. The link looks like this.
http://www.contoso.com/student?id=12345

This will work only when its called like this. For rest of the this i dont have access. ie if i call it on a browser without the querystring it will not work. but with querystring it will return an XML data.
Now, when i call this in the .net application its not working?
How can I call this in a .NET application?
The Normal Webservice Importing methods are not working since it needs a querystring with value and we dont have access to the links which doesnt have the querystring.

A: How are you currently trying to download it?
A very simple way to do this is to use the HttpWebRequest and HttpWebResponse classes;
public XmlDocument GetStudentXml(int studentId)
{
    XmlDocument targetXml = new XmlDocument();

    HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(String.Format("http://www.contoso.com/student?id={0}", studentId));

    webRequest.Credentials = System.Net.CredentialCache.DefaultCredentials;
    webRequest.Accept = "text/xml";

    HttpWebResponse webResponse = (HttpWebResponse)webRequest.GetResponse();

    using (Stream responseStream = webResponse.GetResponseStream())
    {
        XmlTextReader reader = new XmlTextReader(responseStream);
        targetXml.Load(reader);
        reader.Close();
    }

    webResponse.Close();

    return targetXml;

}

This method simply creates a HttpWebRequest, initializes it with the URL (via String.Format so as to append the student id), some windows credentials and the expected content type.
It then calls the remote address via the GetResponse method. The response is then loaded into a stream, and an XmlTextReader is used to load the Xml data from the response stream into the XmlDocument, which is then returned to the caller.
You can also use WebClient and XDocument to achieve the same thing:
string url = String.Format("http://www.contoso.com/student?id={0}", studentId);
string remoteXml;

using (var webClient = new WebClient())
{
    remoteXml = webClient.DownloadString(url);
}

XDocument doc = XDocument.Parse(remoteXml);


text:
Q: runonuiThread UI loop This is my code
I want I show the progressdialog until receive the data from server,
and when I got result from the server(if items.size>0), progressdialog will be dismiss;
But I run this code, I receive the data from the server but in runonuiThread, still running progressdialog.
List<ServerData> items = new ArrayList();
progressdialog.show();

    Thread thread = new Thread(new Runnable() {
                @Override
                public void run() {

                    HttpRequest...
                    Gson gson = new Gson();
                    Type type = new TypeToken<List<ServerData>>(){}.getType();
                    items = gson.fromJson(String,type);

                    Log.d("ThreadInfo","" + items.size);

                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            if(items.size > 0){
                                progressdialog.dismiss();
                            }
                        }
                    });
                }
            });

When I Log the ThreadInfo, It sends items.size value is 1
but still progressdialog is running and not disappear.
Question,
How I can dismiss the progressdialog when items.size is not 0?
If you have any idea, help me please.

A: You have to change your code like this
if (items.size > 0) {

    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                                progressdialog.dismiss();
                        }
                    });

}


text:
Q: Unable to Kill Greenlets in Python Script with Ctrl C command When I press Ctrl+C the call jumps into signal_handler as expected, but the greenlets are not getting killed as they continue the process.
# signal handler to process after catch ctrl+c command
def signal_handler(signum, frame):
    print("Inside Signal Handler")
    gevent.sleep(10)
    print("Signal Handler After sleep")
    gevent.joinall(maingreenlet)
    gevent.killall(maingreenlet,block=True,timeout=10)
    gevent.kill(block=True)
    sys.exit(0)

def main():
 signal.signal(signal.SIGINT, signal_handler) // Catching Ctrl+C

 try:
   maingreenlet = [] // Creating a list of greenlets
   while True:
    for key,profileval in profile.items():
      maingreenlet.append(gevent.spawn(key,profileval)) # appending all grrenlets to list
      gevent.sleep(0)
  except (Error) as e:
    log.exception(e)
    raise

if __name__ == "__main__":
    main()

A: The main reason your code is not working is because the variable maingreenlet is defined inside the main function, and is out of the scope of the signal_handler function which tries to access it. Your code should throw an error like this:
NameError: global name 'maingreenlet' is not defined
If you were to move the line maingreenlet = [] into the global scope, i.e. anywhere outside of the two def blocks, the greenlets should get killed without problem.
Of course that's after you fix the other issues in your code, like using // instead of # to start the comments, or calling the function gevent.kill with the wrong parameter. (you didn't specify your gevent version but I assume the current version 1.3.7) Actually this function call is redundant after you call gevent.killall.
Learn to use a Python debugger liker pdb or rpdb2 to help you debug your code. It'll save your precious time in the long run.


text:
Q: threadid=9: thread exiting with uncaught exception (group=0x40015560) I am facing a force close problem when i am executing my android app. I am facing force close error when i am trying to make a "Toast" as per the response code received from server. Even though there is no problem is sending the messages, because the message is getting delivered properly everytime. The error occurs while displaying the toast. I am pasting all the codes and log messages. Please help me in sorting out the error
Log Cat
09-05 10:08:02.122: W/KeyCharacterMap(719): No keyboard for id 0
09-05 10:08:02.122: W/KeyCharacterMap(719): Using default keymap: /system/usr/keychars
/qwerty.kcm.bin
09-05 10:08:30.392: D/dalvikvm(719): GC_EXTERNAL_ALLOC freed 228K, 53% free 2625K/5511K,
external 2061K/2137K, paused 64ms
09-05 10:08:34.382: D/SmsResponse(719): 1
09-05 10:08:34.382: W/dalvikvm(719): threadid=9: thread exiting with uncaught exception
(group=0x40015560)
09-05 10:08:34.412: E/AndroidRuntime(719): FATAL EXCEPTION: Thread-10
09-05 10:08:34.412: E/AndroidRuntime(719): java.lang.RuntimeException: Can't create handler
inside thread that has not called Looper.prepare()
09-05 10:08:34.412: E/AndroidRuntime(719):  at android.os.Handler.<init>(Handler.java:121)
09-05 10:08:34.412: E/AndroidRuntime(719):  at android.widget.Toast.<init>(Toast.java:68)
09-05 10:08:34.412: E/AndroidRuntime(719):  at android.widget.Toast.makeText(Toast.java:231)
09-05 10:08:34.412: E/AndroidRuntime(719):  at
com.bluetitan.freesms.MainActivity.sendMessage(MainActivity.java:65)
09-05 10:08:34.412: E/AndroidRuntime(719):  at
com.bluetitan.freesms.MainActivity.run(MainActivity.java:144)

09-05 10:08:34.412: E/AndroidRuntime(719):  at java.lang.Thread.run(Thread.java:1019)
09-05 10:08:34.742: W/IInputConnectionWrapper(719): showStatusIcon on inactive InputConnection
09-05 10:08:36.142: E/WindowManager(719): Activity com.bluetitan.freesms.MainActivity has leaked
window com.android.internal.policy.impl.PhoneWindow$DecorView@40558428 that was originally added
here
09-05 10:08:36.142: E/WindowManager(719): android.view.WindowLeaked: Activity
com.bluetitan.freesms.MainActivity has leaked window
com.android.internal.policy.impl.PhoneWindow$DecorView@40558428 that was originally added here
09-05 10:08:36.142: E/WindowManager(719):   at android.view.ViewRoot.<init>(ViewRoot.java:258)
09-05 10:08:36.142: E/WindowManager(719):   at
android.view.WindowManagerImpl.addView(WindowManagerImpl.java:148)
09-05 10:08:36.142: E/WindowManager(719):   at
android.view.WindowManagerImpl.addView(WindowManagerImpl.java:91)
09-05 10:08:36.142: E/WindowManager(719):   at
android.view.Window$LocalWindowManager.addView(Window.java:424)
09-05 10:08:36.142: E/WindowManager(719):   at android.app.Dialog.show(Dialog.java:241)
09-05 10:08:36.142: E/WindowManager(719):   at
android.app.ProgressDialog.show(ProgressDialog.java:107)
09-05 10:08:36.142: E/WindowManager(719):   at
android.app.ProgressDialog.show(ProgressDialog.java:90)

 09-05 10:08:36.142: E/WindowManager(719):  at
 com.bluetitan.freesms.MainActivity.onClick(MainActivity.java:123)

 09-05 10:08:36.142: E/WindowManager(719):  at android.view.View.performClick(View.java:2485)

 09-05 10:08:36.142: E/WindowManager(719):  at android.view.View$PerformClick.run(View.java:9080)
 09-05 10:08:36.142: E/WindowManager(719):  at
 android.os.Handler.handleCallback(Handler.java:587)
 09-05 10:08:36.142: E/WindowManager(719):  at
 android.os.Handler.dispatchMessage(Handler.java:92)
 09-05 10:08:36.142: E/WindowManager(719):  at android.os.Looper.loop(Looper.java:123)
 09-05 10:08:36.142: E/WindowManager(719):  at
 android.app.ActivityThread.main(ActivityThread.java:3683)
 09-05 10:08:36.142: E/WindowManager(719):  at java.lang.reflect.Method.invokeNative(Native
 Method)
 09-05 10:08:36.142: E/WindowManager(719):  at java.lang.reflect.Method.invoke(Method.java:507)
 09-05 10:08:36.142: E/WindowManager(719):  at
 com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:839)

 09-05 10:08:36.142: E/WindowManager(719):  at
 com.android.internal.os.ZygoteInit.main(ZygoteInit.java:597)
 09-05 10:08:36.142: E/WindowManager(719):  at dalvik.system.NativeStart.main(Native Method)

MainActivity.java
public class MainActivity extends Activity implements OnClickListener, Runnable {
Context context;

// public final static String EXTRA_NUMBER =
// "com.example.myfirstapp.NUMBER";
// public final static String EXTRA_MESSAGE =
// "com.example.myfirstapp.MESSAGE";
EditText editTextNum, editText, editUserName, editPassword;
Button btnsend;
ProgressDialog pd;
String gateway_name;
Thread t;
Spinner spinner1;
String toastMsg = "Message Sent To Server";

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    this.requestWindowFeature(Window.FEATURE_NO_TITLE);
    setContentView(R.layout.activity_main);
    editUserName = (EditText) findViewById(R.id.edit_userName);
    editPassword = (EditText) findViewById(R.id.edit_password);
    editTextNum = (EditText) findViewById(R.id.edit_number);
    editText = (EditText) findViewById(R.id.edit_message);
    spinner1 = (Spinner) findViewById(R.id.SpinnerGateway);
    btnsend = (Button) findViewById(R.id.btnsend);
    btnsend.setOnClickListener(this);
}

/** Called when the user clicks the Send button */
public void sendMessage() {
    String usrname = editUserName.getText().toString();
    String usrPassword = editPassword.getText().toString();
    String number = editTextNum.getText().toString();
    String message = editText.getText().toString();
    gateway_name = String.valueOf(spinner1.getSelectedItem());
    String msgreciever = number;
    String testMessage = message;
    try {
        SmsSender.sendMessage(msgreciever, testMessage, usrname,
                usrPassword, gateway_name);
        toastMsg = SmsSender.toastText;
    } catch (Exception ex) {
        Toast.makeText(MainActivity.this, "SMS Sending Failed.",
                Toast.LENGTH_SHORT).show();
    }

}

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

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle item selection
    switch (item.getItemId()) {
    case R.id.menu_settings:
        settingmenuClicked();
        return true;
    case R.id.menu_help:
        showHelp();
        return true;
    default:
        return super.onOptionsItemSelected(item);
    }
}

public boolean isOnline() {
    ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo netInfo = cm.getActiveNetworkInfo();
    if (netInfo != null && netInfo.isConnectedOrConnecting()) {
        return true;
    }
    return false;
}

public boolean isValid() {
    if (editUserName.getText().length() == 10
            && editPassword.getText().length() != 0
            && editTextNum.getText().length() == 10
            && editText.getText().length() != 0) {
        return true;
    }
    return false;
}

public void onClick(View v) {
    // TODO Auto-generated method stub
    if (v == btnsend) {
        if (!isOnline()) {
            Toast.makeText(MainActivity.this,
                    "No Internet Access..Cannot Send SMS",
                    Toast.LENGTH_SHORT).show();
        } else if (!isValid()) {
            Toast.makeText(MainActivity.this,
                    "All fields are required. Try Again.",
                    Toast.LENGTH_SHORT).show();
        } else {
            pd = ProgressDialog.show(MainActivity.this, "Free Sms",
                    "Sending SMS..Please Wait..!!", true);
            t = new Thread(this);
            t.start();
        }

    }
}

public void settingmenuClicked() {
    Toast.makeText(MainActivity.this, "Setting Menu Coming Soon",
            Toast.LENGTH_SHORT).show();
}

public void showHelp() {
    Toast.makeText(MainActivity.this, "Help Coming Soon",
            Toast.LENGTH_SHORT).show();
}

public void run() {
    // TODO Auto-generated method stub
    sendMessage();
    mHandler.sendEmptyMessage(0);
}

public Handler mHandler = new Handler(Looper.getMainLooper()) {
    @Override
    public void handleMessage(Message msg) {
        // TODO Auto-generated method stub
        super.handleMessage(msg);
        pd.dismiss();
        Toast.makeText(MainActivity.this, "Message Sent to server", Toast.LENGTH_SHORT)
                .show();
        editTextNum.setText("");
        editText.setText("");
        editTextNum.requestFocus();
    }
};
}

SmsSender.java
public class SmsSender {

static final String _url = "http://ubaid.tk/sms/sms.aspx";
static final String charset = "UTF-8";
public static String responsecode = "0";
public static Integer responseInt;
public static String toastText = "Message Sent To Server";

// to build the query string that will send the message
private static String buildRequestString(String targetPhoneNo,
        String message, String userName, String Password, String Gateway)
        throws UnsupportedEncodingException {
    String[] params = new String[5];
    params[0] = userName;
    params[1] = Password;
    params[2] = message;
    params[3] = targetPhoneNo;
    params[4] = Gateway;

    String query = String.format(
            "uid=%s&pwd=%s&msg=%s&phone=%s&provider=%s",
            URLEncoder.encode(params[0], charset),
            URLEncoder.encode(params[1], charset),
            URLEncoder.encode(params[2], charset),
            URLEncoder.encode(params[3], charset),
            URLEncoder.encode(params[4], charset));
    return query;

}

public static void sendMessage(String reciever, String message,
        String userName, String password, String Gateway) throws Exception {
    // To establish the connection and perform the post request
    URLConnection connection = new URL(_url
            + "?"
            + buildRequestString(reciever, message, userName, password,
                    Gateway)).openConnection();
    connection.setRequestProperty("Accept-Charset", charset);
    // This automatically fires the request and we can use it to determine
    // the response status
    InputStream response = connection.getInputStream();
    BufferedReader br = new BufferedReader(new InputStreamReader(response));
    // System.out.println(br.readLine());
    // response code = br.readLine();
    Log.d("SmsResponse", br.readLine());
    responsecode = br.readLine();
    responseInt = Integer.valueOf(responsecode).intValue();
    switch (responseInt) {
    case 1:
        toastText = "Message Sent Successfully";
        break;
    case -1:
        toastText = "Server Error";
        break;
    case -2:
        toastText = "Invalid Username";
        break;
    case -3:
        toastText = "Invalid Message Text";
        break;
    case -4:
        toastText = "Login Failed";
        break;
    case -5:
        toastText = "IP is blocked";
        break;
    default:
        toastText = "Unknown Error";
        break;
    }

    // responseInt = Integer.valueOf(br.readLine()).intValue();

}

public static void main(String[] args) throws Exception {
    // To DO
    // String testPhoneNo = "9876543210";
    // String testMessage = "Sending Messages From java is not too hard";
    // sendMessage(testPhoneNo, testMessage);
}

}

A: You cannot call a Toast from that thread. You need to run the code on the UI thread. This is the simplest way to get around it:
this.runOnUiThread(new Runnable() {
    public void run() {
        Toast.makeText(MainActivity.this, "SMS Sending Failed.",
            Toast.LENGTH_SHORT).show();

    }
});

Also does this code mean that my solution to this question was correct? If so please remember to select the correct answer, If not please resolve that question before asking a separate question involving the same code.
EDIT: Also the reason you are getting an exception that is calling this toast message is because you send the response code off before you store it. Only the first call to readLine() will return the response code. In the first question you sent to System.out.println() which did nothing. Now you are sending it to your log so you are able to see it, but then it's gone after that. You need to store it before you log it:
responsecode = br.readLine();
Log.d("SmsResponse", responsecode);

A: Threads are used when we have to a heavy task or time consuming task which cannot be carried on the Main UI thread as the other UI Operation's will come to hold and it'll give you and error.
So doing such time consuming task such as Makking Network connection or downloading any file we need Threads.
But toast is a UI element which will only execute on Main UI thread.


text:
Q: Two Way Sorted/Unsorted Drag Drop with JQuery UI I've got a complex drag/drop scenario that I just can't figure out.  What I've come up with is here: jsfiddle.net/aTjMG/2/
On the left, I have a list of names.  On the right, I have a group of teams.  The list on the left should be alphabetized and not sortable.  The user should be able to assign a person to a team by dragging from the list on the left to a team.  The person's assigned to teams should be able to be sorted or moved to another team, or moved back to the unassigned pool.
I am able to move from the unassigned pool on the left to any team.  I can sort the people in the teams.  What I can't figure out from here is:

*

*How to move from team to team.

*How to move from team to unassigned.

*How to remove the person from their current location when dropped somewhere else

*How to prevent a person (on a team) from being duplicated when I sort the people

I think the big problem is that I can't figure out how to catch the "drop" of the drag-n-drop to change the unassigned person to assigned.
A kick in the right direction would be appreciated.  An example that does just this would be majorly appreciated!

A: If I understand the problem correctly this is really just multiple sorted lists.
Update to your fiddle: http://jsfiddle.net/aTjMG/8/
The key is simply declaring them all as sortable and not messing with draggable at all, which is used for more free-form drag and drop.
$(function() {
  $( ".sortable" ).sortable({
    connectWith: ".sortable"
  }).disableSelection();
});

There is an example of this at the UI docs as well: http://jqueryui.com/sortable/#connect-lists


text:
Q: Two threads adding new rows at the same time - how to prevent? In my application, I have couple of threads that execute some logic.
At the end they adding new row to some table.
Before adding the new row, they check if a previous entry with the same details does not already exist. If one found - they updating instead of adding.
The problem is when some thread A do the check, see that no previous entity with the same details exist, and just before he add a new row, the thread B search the DB for the same entity. Thread B see that no such entity exist so he add new row too.
The result is that there are two rows with the same data in the table.
Note: no table key violated, because the thread get the next sequence just before adding the row, and the table key is some ID that does not related to the data.
Even if I will change the table key so it will be a combination of the data, It will prevent two rows with the same data, but will cause a DB error when the second thread will try to add the row.
Thank you in advance for the help, Roy.

A: You should be using a queue, possibly blocking queue. Threads A and B (producers) would add objects to the queue and another thread C (consumer) would poll the queue and remove the oldest object from the queue persisting it to the DB. This will prevent the problem when both A and B in the same time want to persist equal objects

A: You speak of "rows" so presumably this is a SQL database?
If so, why not just use transactions?
(Unless the threads are sharing a database connection, in which case a mutex might help, but I would prefer to give each thread a separate connection.)

A: I would recommend avoid locking in the client layer. Synchronized only works within one process, later you may scale so that your threads are across several JVMs or indeed machines.
I would enforce uniqueness in the DB, as you suggest this will then cause an exception for the second inserter. Catch that exception and do an update if that's the business logic you need.
But consider this argument:
Sometimes either of the following sequences may occur:
A insert Values VA, B updates to values VB.
B insert VB, A updates to VA.
If the two threads are racing either of these two outcomes VA or VB is equally valid. So you can't distinguish the second case from A inserts VA and B just fails!
So in fact there may be no need for the "fail and then update" case.

A: I think this is a job for SQL constraints, namely "UNIQUE" on the set of columns that have the data + the appropriate error handling.

A: Most database frameworks (Hibernate in Java, ActiveRecord etc in Ruby) have a form of optimistic locking. What this means is that you execute each operation on the assumption that it will work without conflict. In the special case where there is a conflict, you check this atomically at the point where you do the database operation, throw an exception, or error return code, and retry the operation in your client code after requerying etc.
This is usually implemented using a version number on each record. When a database operation is done, the row is read (including the version number), the client code updates the data, then saves it back to the database with a where clause specifying the primary key ID AND the version number being the same as it was when it was read. If it is different - this means another process has updated the row, and the operation should be retried. Usually this means re-reading the record, and doing that operation again on it with the new data from the other process.
In the case of adding, you would also want a unique index on the table, so the database refuses the operation, and you can handle that in the same code.
Pseudo code would look something like
do {
  read row from database
  if no row {
     result_code = insert new row with data
  } else {
     result_code = update row with data
  }
} while result_code != conflict_code

The benefit of this is that you don't need complicated synchronization/locking in your client code - each thread just executes in isolation, and uses the database as the consistency check (which it is very quick, and good at). Because you're not locking on some shared resource for every operation, the code can run much faster.
It also means that you can run multiple separate operating system processes to split the load and/or scale the operation over multiple servers as well without any code changes to handle conflicts.

A: You need to wrap the calls to check and write the row in a critical section or mutex.
With a critical section, interrupts and thread-switching are disabled while you perform the check and write, so both threads can't write at once.
With a mutex, the first thread would lock the mutex, perform its operations, then unlock the mutex. The second thread would attempt to do the same but the mutex lock would block until the first thread released the mutex.
Specific implementations of critical section or mutex functionality would depend on your platform.

A: You need to perform the act of checking for existing rows and then updating / adding rows inside a single transaction.
When you perform your check you should also acquire an update lock on those records, to indicate that you are going to write to the database based on the information that you have just read, and that no-one else should be allowed to change it.
In pseudo T-SQL (for Microsoft SQL Server):
BEGIN TRANSACTION
SELECT id FROM MyTable WHERE SomeColumn = @SomeValue WITH UPDLOCK
-- Perform your update here
END TRANSACTION

The update lock wont prevent people reading from those records, but it will prevent people from writing anything which might change the output of your SELECT

A: Multi Threading is always mind-bending ^^.
Main thing to do is to delimit the critical resources and critical operations.

*

*Critical resource : your table.

*Critical operation : adding yes, but
the whole procedure

You need to lock access to your table from the beginning of the check, until the end of the add.
If a thread attempt to do the same, while another is adding/checking, then he waits until the thread finish its operation. As simple as that.


text:
Q: How to obtain programmatically video type - Live or DVR in ExoPlayer I use the last version of ExoPlayer (2.10.0) in my Android app. And I want to play different video types (VOD, LIVE, DVR) with different videoplayer interface. For example, I want to show DefaultTimeBar on ExoPlayer controlls in VOD and DVR videos and I want to hide this view when video is LIVE.
All videos play well, but I dont know, how to check programmatically the type of video. I was looking for information and found that I can use flags isCurrentWindowDynamic and isCurrentWindowSeekable of SimpleExoPlayer object. But when I show them in logs, I see the next:
1) VOD video, url ="https://commondatastorage.googleapis.com/gtv-videos-bucket/CastVideos/hls/GoogleIO-2014-CastingToTheFuture.m3u8"
videoPlayer?.isCurrentWindowDynamic // returns false
videoPlayer?.isCurrentWindowSeekable // returns true

2) DVR video, url = "https://svs.itworkscdn.net/lanatvlive/lana/playlist.m3u8?DVR"
videoPlayer?.isCurrentWindowDynamic // returns true
videoPlayer?.isCurrentWindowSeekable // returns true

3) LIVE video, url = "https://live-k2301-kbp.1plus1.video/189931/smil:189931.smil/playlist.m3u8"
videoPlayer?.isCurrentWindowDynamic // returns true
videoPlayer?.isCurrentWindowSeekable // returns true

Both flags in DVR and LIVE are the same. So, how to distinguish the type DVR or LIVE programmatically?


text:
Q: How to catch "Pause" or restart "event" using phonegap build? Hi I am making a JQM and PhoneGap app. I would like to catch events like "pause","restart" or resume. Do you know how to do this? I read docs, but there are no clues how to do it in javascript code for phonegap build.
Thanks.

A: In the documentation for the events, they give a full example as well as a short example, which I'll reproduce here:
document.addEventListener("pause", onPause, false);

function onPause() {
  // Handle the pause event
}

Just like in normal JavaScript, you can attach to events using the addEventListener method on any node. In the case of PhoneGap, their device events are triggered on the document object.
If I understand you correctly and JQM means jQuery Mobile: In jQuery, it's possible to add handlers for arbitrary events by using:
$(document).on('pause', onPause);

(This uses the jQuery 1.7 syntax, but I believe that's a requirement for jQuery Mobile).


text:
Q: SimpleInjector MVC Controller injection keeps giving compiler error I'm using simple injector, however my MVC Controllers keep failing with a class specified in the constructor due to no 0 argument constructors.
My code in Global.asax to register all controllers and simple injector
        container = new Container();

        // register MVC controllers
        container.RegisterMvcControllers(Assembly.GetExecutingAssembly());
        container.RegisterMvcIntegratedFilterProvider();

        // register our objects
        container.Register<ICacheManager, MemoryCacheManager>(Lifestyle.Singleton);
        container.RegisterSingle<ILogger, NLogLogger>();

        container.Register(typeof(UsersOnlineModule));

        container.Verify();
        DependencyResolver.SetResolver(new SimpleInjectorDependencyResolver(container));

My test controller class
public class SidcProjectController : Controller
{
    public SidcProjectController(ICacheManager cm)
    {

    }
}

SearchController
public class SearchController : SidcProjectController
{
    [HttpPost()]
    public ActionResult Query(string query)
    {
        return View();
    }
}

Trying to compile this solution gives me a compiler error:

Error 2   'sidc.Framework.Web.Controllers.SidcProjectController' does
  not contain a constructor that takes 0 arguments  D:\Projecten\Software
  Development\Source\Workspaces\SIDC\sidc\sidc\Areas\Projects\Controllers\SearchController.cs   10  18  sidc

SearchController is of type SidcProjectController that acts as a base and requires ICacheManager to read values from the cache.

A: You are receiving a compiler error because your SearchController inherits from SidcProjectController which has a non default constructor. Simple Injector will not inject anything into this constructor simply because it can't. Simple Injector has no knowledge of the inheritance and the clr, as the compiler correctly warns, need you to create the base when it hasn't a non default constructor. See MSDN.
You should new up the base class from the constructor of the implementation like this:
public class SearchController : SidcProjectController
{
    public SearchController(ICacheManager cm) : base(cm)
    {
    }
}

Understand that you need to do this for every dependency you need in your base controller. Therefore think twice if you really need a base class! And if you really need one it should not be dependent on anything or you will violate OCP and run into trouble pretty quickly.
So while my answer will compile I strongly advise against using this approach, because your base class will become a maintenance nightmare.


text:
Q: How to pass output of one XSLT TBB to another XSLT TBB in SDL Tridion 2011 SP1 I am using XSLT mediator from SDL Tridion World to create an XSLT TBB. Here my requirement is like, I want to pass output of one XSLTTBB to another XSLT TBB.
Say I have an XSLT TBB named "1" where in I output:
<aaa>
hi
</aaa>
<bbb>
hello
</bbb>

I want to write another XSLT TBB which takes the first TBB's output and processes the data into
<ccc>hi hello</ccc>

Consider the example as very generic. I am using Template Builder to combine two TBBs. But  I am not getting the exact result.
Is it necessary to configure the XSLT Mediator for Template Builder too? If yes, show me how to do that.
If there is any such way, let me know.
Thank you in advance.

A: This is possible by using the template parameters as follows:

*

*TBB 1 is configured with output 'Temp' and Output format type 'Xml'

*TBB 2 is configured with input 'Temp' and output 'Output'

*TBB 2 is configured to load the package items as parameters

*Add  to the top of TBB 2 (so that you can use the variable from within the XSLT using something like )

*You can make the output of TBB 1 either a String or an XmlDocumnet. If you use an XmlDocument, you can perform XPath queries on the variable in TBB 2.

It is not necessary to configure anything on the Template Builder, since the mediator is hosted on the TCM server.

A: I'd suggest that you look to see whether you can improve your design so that you don't need to do this. In general, it's pretty unusual to need more than one "templating" TBB in your pipeline. In principle, you should be doing enough preparation (in assembly building blocks) before you reach the templating layer, and then you should be able to do it all in one go.


text:
Q: Lyapunov Indirect Method I have searched a reference (book/paper) where I could find a theorem related to the Lyapunov Indirect Method for any equilibrium point, but I have not found yet. I only found for the zero equilibrium point. Somebody can help me?
I am searching the following Theorem:
Let us consider the non-linear system $\dot{x}=f(x)$ with an arbitrary equilibrium point $\bar{x}$. This equilibrium point $\bar{x}$ is:

*

*asymptotically stable if all eigenvalues of $Df(\bar{x})$ have negative real part;

*unstable if at least one eigenvalue of $Df(\bar{x})$ has positive real part;

where $Df(\bar{x})$ is the Jacobin matrix of $f$ applied in the equilibrium point $\bar{x}$.
Thank you very much!
Ana


text:
Q: Powershell Regex not triggering I'm having a problem getting a Regex to extract a portion of a string and I can't see what I have done wrong.
The string:
Backup job DailyBackupToNAS completed successfully.   Destination: Network location Start time: 01/05/2013 05:00:28 End time: 01/05/2013 05:39:13 Duration: 00:38:45.5875346

The code:
$destinationregex = "Destination: (.*)Start time:"
If ($message -match $destinationregex)
{
    $destination = $matches[1]
}

I am trying to extract the text Network Location
Any pointers would be appreciated!
As requested a fuller scope of code
$events = get-eventlog application -source BackupAssist -newest 50
Foreach ($event in $events)
{
  $message = $event.message
  $destinationregex = "Destination: (.*)Start time:"
  If ($message -match $destinationregex)
  {
    $destination = $matches[1]
  }
  Else
  {
    $destination = "Unknown"
  }
  Write.Host $destination
}

A: Okay, I'm posting as an answer this time, for more flexible formatting, and because I'm confident this will finally solve the problem. ;)
Try this:
$destinationregex = '(?s)Destination: ([^\r\n]*).*?Start time:'

The (?s) means that wildcards can match newline characters. The grouping ([^\r\n]*) matches until the end of the line, and the .*? matches the line break. The following would work too:
$destinationregex = 'Destination: (.*?)\r\nStart time:'
In fact, since you really only want to match from after "Destination: " to the end of the line, you could just do this, which is the simplest (unless you specifically want to make sure that you only match if "Start time:" is the very next thing):
$destinationregex = 'Destination: (.*)'
If it still doesn't work, it may be because $message is being read as an array instead of a string. You can easily test that by adding the debugging line $message.GetType() immediately after setting $message. If it's an array, try setting $message this way (in addition to using one of the regular expressions above):
$message = $event.message | Out-String
In fact, doing it this way works in either case, but the | Out-String is superfluous if it's already a string, though it doesn't hurt.
For clarity, here's the modified code block, as I think it will end up, depending on the answers to the questions above:
foreach ($event in $events)
{
  $message = $event.message | Out-String
  $destinationregex = 'Destination: (.*)'
  If ($message -match $destinationregex)
  {
    $destination = $matches[1]
  }
  else
  {
    $destination = "Unknown"
  }
  Write-Host $destination
}


text:
Q: Android dynamic background I am somewhat of a new android developer and have a question regarding changing the background dynamically at runtime.
What I want to do is set a background color in a LinearLayout Tag, and later change that background color in my activity class. This code below is not working. Am I missing something or is this the wrong approach for trying to change the background color in a linear layout
LinearLayout lv = (LinearLayout)findViewById(R.id.ChoiceLayout);
lv.setBackgroundColor(0x000080);

Thanks in advance

A: First thing I've noticed is that your color has ALPHA = 0x00. Which makes it transparent. Try changing to
lv.setBackgroundColor(0xFF000080);

A: AFAIK, that should work fine. Use hierarchyviewer to try to diagnose what is going wrong.

A: already answered in another post , unfortunately i don't know that link but know the solution.
use
lv.setBackgroungColor(GetResources().getColor(int color));


text:
Q: Control size of text-only buttons in QToolBar I'm using PySide. I have a QMainWindow with a vertical QToolBar myToolBar. I use myToolBar.toolButtonStyle = Qt.ToolButtonTextOnly to make the toolbar's buttons contain only text, no icons. I add QActions to the QToolBar, and buttons are automatically created. I'd like to make the buttons taller, but since I'm not using any QToolButton objects, I don't know how. QAction has a setFont() method, so I can make the font larger, but what I want is some padding inside the button. How can I accomplish that?

A: http://qt-project.org/doc/qt-4.8/stylesheet-reference.html#qtoolbutton-widget
Something like the following should do it:
myToolBar.setStyleSheet("QToolButton{padding: 20px;}");

Basically that says, set the style for any widgets underneath this object of the type QToolButton, to have the QStyle set for padding on all four sides set to 20px.
If you only wanted to set the padding on the top and right sides, it would look like this:
padding: 20px 0px 4px 0px;

http://www.w3schools.com/css/css_padding.asp


text:
Q: Python MySQLdb works from Python on Command Line but not Django Views.py I have a Django views.py function named getpos that gets served by apache2 and wsgi.py. If I run the exact same code from my views.py in a normal Python session from the Ubuntu command line, the MySQLdb connection works fine:
>>> import MySQLdb
>>> db = MySQLdb.connect(host="localhost",port=22,user="root",passwd="mypassword",db="gps")
>>>
>>> cursor = db.cursor()

If I run it from the django debug server, it fails with:
ERROR: (2003, "Can't connect to MySQL server on 'localhost' ([Errno 111] Connection refused)")

The code that runs is this:
def getpos(request):

    query = "SELECT * FROM..."

    # connect to the DB and return nearby deals
    db = MySQLdb.connect(host="localhost",port=22,user="root",passwd="mypassword",db="gps")
    cursor = db.cursor()

    # Query the gps Data database
    results = cursor.execute(query)
    db.commit()

Howcome I can connect from Python on the command line but not in the views.py file with Django? Thanks.
I've tried using "127.0.0.1" instead of "localhost", but nothing seems to work.

A: I had to change my port in the connect argument to host="localhost",port=3306.


text:
Q: Why can i go to www.domain.com/index.php/put_anything_here? Why is it possible to go further into my index.php file as it was a folder like: www.domain.com/index.php/put_anything_here_and_it_loads_the_file_without_styling
I want it to use the .htaccess to redirect them to the index.php when they go to a file that does not exist like index.php/anything_here - but for some reason it thinks that index.php/anything_here exists...
Right now i have just set my .htaccess to redirect to this page if one of the errors happen:
This is my .htaccess:
ErrorDocument 404 /404error.php
ErrorDocument 400 /404error.php
ErrorDocument 401 /404error.php
ErrorDocument 403 /404error.php
ErrorDocument 500 /404error.php

Thanks


text:
Q: Dropwizard-Hibernate - IllegalArgumentException: No query defined for that name Apologies for asking this when other people have asked before, but the other solutions appear to use @ComponentScan which is for Spring, and I am using dropwizard, so that wont work for me.
This is my (pretty simple) DTO class.
package apidto.entity.organization;

import lombok.Data;

import javax.persistence.*;

@Entity
@Table(name = "organization")
@NamedQueries({@NamedQuery( name =
        "apidto.entity.organization.Organization.findAll",
        query = "SELECT o from Organization o")})

public @Data class Organization {

    @Id
    private long id;

    @Column(name = "name")
    private String name;
}

and I have the following DAO class...
import apidto.entity.organization.Organization;
import io.dropwizard.hibernate.AbstractDAO;
import org.hibernate.SessionFactory;

import java.util.List;

public class OrganizationDAO extends AbstractDAO<Organization> {

    public OrganizationDAO(SessionFactory sessionFactory)
    {
        super(sessionFactory);
    }

    public List<Organization> findAll()
    {
        return list(namedQuery("apidto.entity.organization.Organization.findAll"));
    }
}

A: You should use ScanningHibernateBundle in the Application class. ScanningHibernateBundle will scan apidto.entitypackage and all nested packages and add all classes with @Entity annotation to the Hibernate SessionFactory.
class SomeApp extends Application<SomeConfiguration> {

    @Override
    public void initialize(Bootstrap<SomeConfiguration> bootstrap) {

        HibernateBundle<SomeConfiguration> hibernate = new ScanningHibernateBundle<SomeConfiguration>(
                "apidto.entity") {
            @Override
            public PooledDataSourceFactory getDataSourceFactory(SomeConfiguration configuration) {
                return configuration.getDataSourceFactory();
            }
        };

        bootstrap.addBundle(hibernate);
    }

}

A: I had the same problem using Dropwizard and Hibernate. I had a User entity class like this:
@Entity
@Table(name = "users")
@NamedQueries({
    @NamedQuery(name = "com.majidkhorsandi.dropbookmarks.core.User.findAll",
    query = "SELECT u FROM User u"),
    @NamedQuery(name = "com.majidkhorsandi.dropbookmarks.core.User.findByUsernamePassword",
    query = "SELECT u FROM User u WHERE u.username = :username AND u.password = :password")
})

public class User {

@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private long id;

private String username;

private String password;

/*private List<Bookmark> bookmarks = new ArrayList<>();*/

public User() {
}

public User(String username, String password) {
    this.username = username;
    this.password = password;
}
...

And then I had my DAO class as:
public class UserDAO extends AbstractDAO<User> {

    UserDAO(SessionFactory sessionFactory) {
        super(sessionFactory);
    }

    List findAll() {

        return list(namedQuery("com.majidkhorsandi.dropbookmarks.core.User.findAll"));
    }

    public Optional<User> findByUsernamePassword(String username, String password) {
        return  Optional.ofNullable(uniqueResult(
                namedQuery("com.majidkhorsandi.dropbookmarks.core.User.findByUsernamePassword")
                .setParameter("username", username)
                .setParameter("password", password)
        ));
    }
}

Then here is how my hibernate.cfg.xml looked:
<hibernate-configuration>

<session-factory>

    <!-- Database connection settings -->
    <property name="connection.driver_class">org.h2.Driver</property>
    <property name="connection.url">jdbc:h2:mem:db1;DB_CLOSE_DELAY=-1</property>
    <property name="connection.username">sa</property><!--./target/example-->
    <property name="connection.password">sa</property>

    <!-- JDBC connection pool (use the built-in) -->
    <property name="connection.pool_size">10</property>

    <!-- SQL dialect -->
    <property name="dialect">org.hibernate.dialect.H2Dialect</property>

    <!-- Enable Hibernate's current sessions tracking by thread of execution -->
    <property name="current_session_context_class">managed</property>

    <!-- Disable the second-level cache  -->
    <property name="cache.provider_class">org.hibernate.cache.internal.NoCacheProvider</property>

    <!-- Echo all executed SQL to stdout -->
    <property name="show_sql">true</property>

    <mapping class="com.majidkhorsandi.dropbookmarks.core.User"/>

</session-factory>

</hibernate-configuration>

I thought that the mapping tag in the hibernate.cfg.xml should be enough to do the mapping of User:
<mapping class="com.majidkhorsandi.dropbookmarks.core.User"/>

but Apparently, it was not. So What I had to do was to add the following extra line to the class in which I am building the SessionFactory using the hibernate configuration (in my case HibernateUtil):
            configuration.addAnnotatedClass(User.class);

So eventually here is how my HibernateUtil looked like after the fix:
public class HibernateUtil {

    private static final SessionFactory sessionFactory;

    static {
        try {
            Configuration configuration = new Configuration().configure();
            configuration.addAnnotatedClass(User.class);
            StandardServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder()
                    .applySettings(configuration.getProperties())
                    .build();
            sessionFactory = configuration.buildSessionFactory(serviceRegistry);
        } catch (Throwable ex) {
            // Log the exception.
            System.err.println("Initial SessionFactory creation failed." + ex);
            throw new ExceptionInInitializerError(ex);
        }
    }

    static SessionFactory getSessionFactory() {

        return sessionFactory;
    }
}


text:
Q: Issue with fixed width tcolorbox in start of new par (right to left context) I have this example of a fixed width tcolorbox in RTL context inserted in the beginning of a paragraph, if I add \indent indentation appears normally  but without it box go in opposite direction! Is there any way to solve this problem?
I look for commands to add before tcolorbox which give correct result in all cases
\documentclass{book}
\usepackage[showframe]{geometry}
\usepackage{tcolorbox}

\begin{document}

\pagedir TRT \pardir TRT \bodydir TRT \textdir TRT

%% without \leavevmode

% this is fine
\indent
{\textdir TLT\begin{tcolorbox}[width=3cm,nobeforeafter]
box
\end{tcolorbox}}text

% not fine
{\textdir TLT\begin{tcolorbox}[width=3cm,nobeforeafter]
 box
\end{tcolorbox}}text

%% with \leavevmode

% fine
{\leavevmode\textdir TLT\begin{tcolorbox}[width=3cm,nobeforeafter]
 box
\end{tcolorbox}}text

% not fine
{\leavevmode\textdir TLT\begin{tcolorbox}
 box
\end{tcolorbox}}

\end{document}


text:
Q: Google Domain Forwarding - with Content-Type JSON I have a domain foo.com registered with google domains. I have configured it to forward to myfoo.com (including path forwarding, etc.).
When HTTP requests are sent, it successfully forwards
foo.com --> myfoo.com
foo.com/abcd --> myfoo.com/abcd
But when the HTTP requests include JSON data (Content-Type JSON), I cant see the data on myfoo.com. I do see that the forwarding to myfoo.com happens. But there is no data. Does this involve some configuration on my server side or something on google domain forwarding? PS: I have made sure that my server side can handle JSON data. When I directly reach myfoo.com/something with Content-Type JSON, I can handle it.


text:
Q: onbackpressed not working in kotlin webview i am working on web view but the app crashes when pressed back button and progress bar does not show 100%
it opens up a website and it also doesnt support javascript alert box?
here is my code
    override fun shouldOverrideUrlLoading(view: WebView?, url: String?): Boolean {
            view?.loadUrl(url)
            setting!!.domStorageEnabled= true
            setting!!.javaScriptEnabled = true
            return true
        }

    }
     // Get the web view settings instance
    val settings = webview.settings;
     // Enable java script in web view
    settings.javaScriptEnabled = true

    // More optional settings, you can enable it by yourself
    settings.domStorageEnabled = true
    settings.setSupportMultipleWindows(true)
    settings.loadWithOverviewMode = true
    settings.allowContentAccess = true
    settings.setGeolocationEnabled(true)
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
        settings.allowUniversalAccessFromFileURLs = true
    }

    settings.allowFileAccess = true

    // WebView settings
    webview.fitsSystemWindows = true

    /* if SDK version is greater of 19 then activate hardware acceleration
    otherwise activate software acceleration  */

    webview.setLayerType(View.LAYER_TYPE_HARDWARE, null)

    webview.loadUrl("https://www.google.com/")

        override fun onBackPressed() {
            if (webview!!.canGoBack()) {
                // If web view have back history, then go to the web view back history
                webview?.goBack()
            }else{
                super.onBackPressed()
            }
        }

Logcat had this to say:
E/InputEventSender: Exception dispatching finished signal.
E/MessageQueue-JNI: Exception in MessageQueue callback: handleReceiveCallback
E/MessageQueue-JNI: kotlin.KotlinNullPointerException
        at com.work.social.MainActivity.onBackPressed(MainActivity.kt:134)

A: Remove code from onBackPressed()
Regarding JS alert box, have you tested on real device?

A: I would highly suspect your local !! in onBackPressed().
override fun onBackPressed() {
    when {
        webview?.canGoBack() == true -> webview.goBack()
        else -> super.onBackPressed()
    }
}

Calling !! is, in most cases, a bad idea. And a source of KotlinNullPointerException (eg: Kotlin tries to cast T? as T and if null, fails).


text:
Q: Forest Trust relationship access denied I have resource forest (domain1.net) set up for Exchange 2013 with a trust relationship to another forest (domain2.local) where users are set up. This has been running for a couple months without issue until today.  The users have not been logging on to domain2.local with the exception of authentication for their mailboxes which are linked accounts.
This has been been a phased migration which got held up due to external factors, the users are currently logging in to a completely separate domain (otherdomain.local which is an SBS2008 setup with) and just using outlook to connect with the credentials from domain2.local.
Today I started the process to move the users over to the domain2.local.  As the next step in that process I added another DC to the domain, and this is where things broke.  I got a call saying all users were getting a popup requesting credentials for the Outlooks.  Entering valid credentials made no difference and the box kept popping up and not allowing connection, however users could log in with OWA.  On investigation I realised I had named the new DC in in domain2 the same as a DC in domain1, albeit with a different domain name, this is what seems to have broken things, that is according to some posts on various forums.
In an attempt to resolve this I have removed the trust between the 2 domains and tried to recreate it, but get an access denied error, the trust does create on both sides but wont validate.  Also when i look at the routed suffixes on each side, the domain1.net suffix is listed in the doamin2.local properties, but the domain2.local suffixes are not listed in the domain1.net properties.
I am struggling with this, the customer is only partially working so this is quite urgent, your help is much appreciated.

A: Well after leaving the issue for a couple of hours i went back to it and was able to recreate the trust without issue, and after that all email issues were resolved.  I haven't seen any evidence but i'm suspecting after demoting and renaming the DC that the changes hadn't fully committed and it just needed to catchup with itself.  I did however discover a netlogon event that stated the it couldn't reach the dc that got demoted, but that was a few hours after i demoted it, not sure if that event would have helped had i ssen it sooner though.


text:
Q: X.PagedList.MVC namespace not available following NuGet install I'm trying to switch from PagedList to X.PagedList. I've used NuGet to uninstall the PagedList and PagedList.Mvc packages and then to install X.PagedList and X.PagedList.Mvc.
When I go to update my views, I find myself in a strange situation: I can't seem to reference the PagedList.Mvc namespace as detailed in the example like this:
@using X.PagedList.Mvc;
@using X.PagedList;

In Visual Studio and when debugging, this gives the following exception:

The type or namespace name 'Mvc' does not exist in the namespace
  'X.PagedList' (are you missing an assembly reference?)

(As an aside, if I leave off that using, I get exceptions about missing definitions, as expected.)
Is there a problem with the NuGet package? Is there some way to manually add an assembly reference to a package installed via NuGet?

A: So, in the end I did find a hacky way to get this to work...
All I needed to do was manually add a reference to X.PagedList.Mvc.dll. Oddly, this was present in the packages directory (.\packages\X.PagedList.Mvc.5.3.0.5300\lib\net46) and has what looks to be a valid package file.
Not sure why this didn't happen automatically, but I'm suspicious that it was due to some conflict with the old PagedList.Mvc package.
Going to leave this question open for a week or two in case anyone can weigh in with something a little more insightful.

UPDATE: The approach above worked well locally, but failed when I deployed to test. This prompted a bit more digging and a resolution to get NuGet working properly.
I used the NuGet package explorer to find out that X.PagedList.Mvc targets a more recent version of the .NET framework than the project I was adding it to (4.6 vs 4.5). Bit disappointed that the install didn't fail more helpfully, but at least its sorted now.


text:
Q: Ungroup Values from Series in Report Builder 3.0 I am creating a chart in Report Builder 3.0 and am having difficulty with one particular bit.  The images will help explain what I need

The left image is my current set-up.  At the moment, Value2 is grouped by Mth and GroupAdj but I want it only grouped by Mth.  The middle image shows what I need (taken from Excel) - the line graph is Value2.  The right image is how the current set-up looks when the report is run in SSRS.  Is there a way I can get the right image looking like the middle?
Let me know if anymore information is needed, thanks in advance


text:
Q: Using Python to create specific folder within multiple folders I have a directory containing 450 folders, all unique names. Inside this folder I need to create a sub-folder called Metadata, so it looks like the following:
Folder1/Metadata
Folder2/Metadata
Folder3/Metadata
Is there a way using Python to create this example?

A: The functions you are looking for are all in the os module:
import os
for item in os.listdir('.'):
    if os.path.isdir(item):
        newdir = os.path.join(item, 'Metadata')
        if not os.path.exists(newdir):
            os.makedirs(newdir)


text:
Q: Leakage inductance is function of the air gap I would like to know why leakage inductance is function of the air gap transformer. How does it influence the leakage flux ? What is the relation between them ?
Thank you very much :)

A:
I would like to know why leakage inductance is function of the air gap
  transformer. How does it influence the leakage flux ? What is the
  relation between them ?

With a transformer core of high effective magnetic permeability, you could say that the flux produced by one winding 99.9% couples to the other winding. The closer the coupling is to 100%, the smaller is the leakage flux.
For a core with moderate effective permeability, you might attribute a coupling factor of only 99%. For a core of low effective permeability you might "say" the coupling is around 90%.
Adding a gap to a core of high permeability makes the effective permeability of a transformer smaller and, in turn, the coupling also reduces. A bigger gap reduces the effective permeability even more.
In other words, it isn't the gap itself that creates all the leakage flux but rather the drop in overall permeability making the core "less attractive" of a "path" for magnetic fields to flow along.
An effective relative permeability of 10 is only 10 times that of air and, although most flux would flow through that core, a decent proportion (say 10%) will short cut the core and return back through the air. Whether you use a high permeability core with a gap to bring it down from 1000 to 10 or, you use an un-gapped core of low permeability (10), the effect is the same.

A: the electrical representation of leakage flux is leakage inductance.
Leakage flux : It is that flux which is doesn't link primary and secondary.
Useful flux is that which links primary and secondary.


text:
Q: How to change the default values of primitive data types When a long field is null in the database, eclipselink gives it a default value of 0 upon loading. How can I change that globally, so that the default value becomes -1?

A: So I had a look in the source code of EclipseLink and I found out that this is actually easy to change, because the default value of a primitive class can be set through the api, with the method Session.setDefaultNullValue. (This requires using a SessionCustomizer.)
public class MySessionCustomizer implements SessionCustomizer {

  @Override
  public void customize(final Session session) {

    DatasourceLogin login = session.getLogin();
    login.setDefaultNullValue(long.class, -1L);

  }
}


text:
Q: Compatibility of musixtex with amsmath I've been using musixtex and amsmath in the same document (article class) up until I today encountered the problem that whenever I type \cup for a set union, a quaver appears instead (or sometimes compiling just reports an error). I am not within the environment called by \begin{music} when this occurs. Is there anything I can do to fix this?
To give an example:
\documentclass[11pt,a4paper]{article}
\usepackage{amsmath} %Maths stuff
\usepackage{amsthm} %Theorems
\usepackage{amsfonts}  % for blackboard bold, etc
\usepackage{musixtex}

\begin{document}
$A\cup B$
\end{document}

A: musixtex overrides the latex \cup command, but you could do the following to use one or other definition, depending on whether you are in math.

\documentclass[11pt,a4paper]{article}
\usepackage{amsmath} %Maths stuff
\usepackage{amsthm} %Theorems
\usepackage{amsfonts}  % for blackboard bold, etc
\let\cupA\cup
\usepackage{musixtex}
\let\cupB\cup

\protected\def\cup{\ifmmode\expandafter\cupA\else\expandafter\cupB\fi}

\begin{document}

1: $A\cup B$

2: A \cup B

\end{document}


text:
Q: Interpolating dataset to achieve continuous time intervals? I have my original data set arranged with respect to time in a non-uniform manner. How can I convert it in uniform time intervals (lets say in  10 mins continuous interval)?
 Date   Time  Lat  Long
1-1-08 23.00  12   13
1-1-08 23.20  14   18
1-1-08 23.50  20   14
2-1-08 00.00  16   17
2-1-08 00.30  13   20
2-1-08 00.50  18   19
2-1-08 01.30  11   21
2-1-08 01.40  15   18


text:
Q: iCloud running out of space, but it's not I keep getting messages from iCloud saying my drive is out of room. It is not, it is about half full:

Any ideas here?

A: Open System Preferences and inspect your iCloud Storage there. What you are looking at in Finder is only the size of your iCloud Drive files.
After opening System Preferences, select "Apple ID" in the top row, or "iCloud" in the bottom row if you are running an older version of macOS. On this screen, you will see a meter indicating your storage usage. Hover over different segments to see information about them, and click "Manage" to see more detail.


text:
Q: c# WCF DataService client behavoir similar to BeforeSendRequest I have a WinForm client that its using WCF DataServices. I would like to know if WCF DataServices has some kind of BeforeSendRequest and AfterSendRequest so I can show on the UI an icon that some database request its running.
Any clue?
Thanks

A: Unfortunately WCF doesn't have anything like Global.asax where we can handle BeginRequest and EndRequest

A: Based on your question, I guess the interface IClientMessageInspector will be handy.
The methods to be implemented will be BeforeSendRequest and AfterReceiveReply. I guess these are the two events you are looking for.
The documentation regarding this is available in the following msdn link
http://msdn.microsoft.com/en-us/library/system.servicemodel.dispatcher.iclientmessageinspector.aspx
In short, you will have to implement the IClientMessageInspector( part of System.ServiceModel.Dispatcher) and also implement IEndpointBehavior (part of System.ServiceModel.Description) to hook the inspector on to the client endpoint. And thus change the configuration in the client endpoint to refer the endpoint behaviour that was added.


text: Q: Porting MFC application from visual studio 2005 to 2015 I am porting an mfc application from VS 2005 to VS 2015. I simply upgraded by opening the application in VS 2015. It built successfully with some minor changes. I am facing a Problem during runtime. The mainframe class OnCreate method Fails. It simply Returns without creating a mainframe handle. I also observed that in VS 2005 the mainframe is inherited from CMDIFrameWnd class while in VS2015 it is inherited from CMDIFrameWndEx class. I have changed that and tried as well but still the same error. Has someone else also faced a similar Problem? Can anyone direct me to the possible error and fix for the same?


text:
Q: How to enable standard keyboard shortcuts for the service console? How to enable keyboard shortcuts for the salesforce console? do we need to write any coding to enable standard keyboard shortcuts? Enable shortcut keys option is disabled in my dev org?

A: check below link  for enable keyboard shortcuts in your organization
https://help.salesforce.com/apex/HTViewHelpDoc?id=console2_setup_keyboard_shortcuts.htm&language=en


text:
Q: What exactly is the git extensions "Amend last commit" button doing? I've accidentally pressed the "Amend last commit" button in git extensions. My last commit has already been pushed/shared with others, so I actually do not want to do that.
I usually used this button like this:

*

*click on the button – it loads the previous message

*stage new changes

*when click on the button again, it performs git commit --amend
Now, I don't want to click the button again. I'd rather like to overwrite the message and do regular commit.
The thing that confuses me is: When I close the commit dialog and open it again, I can see the old message in the box.
Can someone please confirm if this is how buttons will behave, and I don't "amend" anything?

A:
Can someone please confirm if this is how buttons will behave, and I don't "amend" anything?

Just tested this on my local system, it will create a new commit and not amend the previous one.


text:
Q: Is it ever known which peoples of the Hainish universe were results of genetic experimentation or manipulation? In The Left Hand of Darkness a theory is mentioned that the Gethenians may have been the result of some type of genetic manipulation or experimentation in their distant past. This speculation was cited as one explanation for their apparently uncommon and astounding hermaphroditic physiology.
I think in the same book it was mentioned that certain other peoples of the known universe might also have similar origins.
Is this ever explored further? Does the possibly Hainish history of genetic manipulation ever become known?


text:
Q: Accessing heavily nested array when parsing JSON in Javascript I'm trying to parse JSON using Javascript but having trouble accessing the value that is 568 part on the first PWER object (this value changes and I just want to display it on the page). The '1452520496000' part also changes value based on time. I'm new to javascript and JSON, the examples that I've seen in researching tend to be simpler than this, such as accessing the PWER in "cid" : "PWER" which I can do.
Here is a sample of the JSON output from the API:
[
{"cid":"PWER",
 "data":[{"1452520496000":568}],
 "sid":"144",
 "units":"kWm",
 "age":5
 },

{"cid":"MOTN",
 "data":[{"1452520489000":0}],
 "sid":"910",
 "units":"S",
 "age":12
 },

{"cid":"LGHT",
 "data":[{"1452520489000":19.09}],
 "sid":"910",
 "units":"L",
 "age":12}
 ]

I have adapted code from the example here as a skeleton for the HTTP GET request while I work out how to parse this. This is what I have so far:

The issue is that this just displays [object Object] on my page.
I've been trying to use the console to debug this:
console.log(arr[0]);

Object {cid: "PWER", data: Array1, sid: "144", units: "kWm", age:
  5}

This shows that it is managing to access the API using the token and pull data.
I want to access 'Array1' in 'data' so I check to see what that contains:
console.log(arr[0].data);

[Object]
      0: Object
  length: 1
  __ proto __: Array[0]

I next try to access the object which is 0 in the index:
console.log(arr[0].data[0]);

Object {1452520496000: 568}

The 568 value that I want is there but I cannot access it, the 1452520496000 part is forever changing. How would be the best way of going about accessing that?

A: So you would have to use Object.keys(object) to get the key you are after
var data = arr[0].data[0];
var keys = Object.keys(data);
console.log(keys[0], data[keys[0]]);

A: var obj = arr[0].data[0];

console.log(obj[ Object.keys( obj )[ 0 ] ] );

get all the keys inside obj using Object.keys() into an array and then get the first index (first key name) from it.

A: JSON works on key value pair formula. The object you are using doesn't fit in JSON format.
"data":[{"1452520496000":568}],

You can use above data like below two formats:

*

*Use both in array "data":[ "1452520496000", "568"],

*Use some keys "data":{"key1":"1452520496000", "key2" : "568"},
and if you want to use the same format then I found a way to parse your JSON
var d= 'your json';
var parsedObjects = $.parseJSON(JSON.stringify(d));

Stringify json and then parse.

A: epascarello has a good answer. An alternative would be to do a simple loop through the POJO in 'data'. A simple for loop example (though you could use other, more performant loops):
var data = arr[0].data[0];
var out;
for (var key in data) {
    out = data[key];
}

Note that if there are other keys present in that 'data' object, you will have to add some error checking before assigning 'out'. E.g. if you have this:
{
    ...
    data: [{ "foo": "someval", "1452520496000": 568, "bar": "someotherval" }]

... Then you would need to do some validation inside your loop to verify the current key is the correct one. I would also then break as soon as you find the right key, for perf.


text:
Q: Is it possible to have the technician and the reference computer on the same computer; windows7 with WAIK? Can you have both the technician and the reference computer on the same computer; windows7 with WAIK?
You take an image an put it under c:\Images for example. So you both capture from the same and put the image in the same computer?

A: That is not recommended, as running sysprep on your technician computer will remove it from the domain (if you are on one), re-set your activation, remove all drivers (unless otherwise specified in the answer file), etc... If anything goes wrong, you could break the technician computer and would need to rebuild it from scratch. Also, you would be including the WAIK files in the image, adding about 1.7 GB to the size of your image.