text:
Q: Unable to read e-mails from Outlook for last 1 hour with Python I am trying to read emails from my outlook for last 1 hour. I have used the below code. here i am not getting any error but it is not giving me any output.
import win32com.client
import datetime as dt
import pandas as pd

date_time = dt.datetime.now()

lastHourDateTime = dt.datetime.now() - dt.timedelta(minutes=60)

outlook = win32com.client.Dispatch("Outlook.Application").GetNameSpace("MAPI")
inbox = outlook.GetDefaultFolder(6)
messages = inbox.Items
messages.Sort("[ReceivedTime]", True)
message = messages.GetLast()
lastHourMessages = messages.Restrict("[ReceivedTime] >= '" + lastHourDateTime.strftime('%m/%d/%Y %H:%M %p') + "'")
timeStamp = dt.datetime.now().strftime("%d-%m-%Y_%H.%M.%S")

for lastHourMessage in lastHourMessages:
   print(lastHourMessage.subject)

I checked the len(messages), it is giving me total count of inbox mails. Whereas len(lastHourMessages) is showing as 0.
According to me, Restrict function is not working properly. Could anyone please help me?

A: Change %y to %Y at line below.
lastHourMessages = messages.Restrict("[ReceivedTime] >= '" + lastHourDateTime.strftime('%m/%d/%y %H:%M %p') + "'")

Just to be sure, correct is
lastHourMessages = messages.Restrict("[ReceivedTime] >= '" + lastHourDateTime.strftime('%m/%d/%Y %H:%M %p') + "'")

UPDATE #1
I added some debug info in your code to help understand what going wrong.
Try to use code below. Hope, it will help you.
import win32com.client
import datetime as dt

one_hour_before = dt.datetime.now() - dt.timedelta(minutes=60)
print(f'one_hour_before: {one_hour_before.astimezone()}')

# Get Outlook NameSpace object.
outlook = win32com.client.Dispatch("Outlook.Application").GetNamespace("MAPI")

# Get The Inbox folder.
# Other folder types:
#   https://learn.microsoft.com/en-us/office/vba/api/outlook.oldefaultfolders
inbox_folder = outlook.GetDefaultFolder(6)
print(f'{inbox_folder}\n')

# Get collection of Outlook items and sort.
messages = inbox_folder.Items
messages.Sort("[ReceivedTime]", True)

# Check all items and ReceivedTime.
for it, message in enumerate(messages):
  print(f'{it}\t{message.ReceivedTime} - {message.Subject}')

  # If recevied one hour before, print it.
  received_time = dt.datetime.utcfromtimestamp(message.ReceivedTime.timestamp())
  if received_time >= one_hour_before:
    print(f'^^^\tRECEIVED ONE HOUR BEFORE')

# Get items received one hour before, if there are.
one_hour_before_messages = \
  messages.Restrict( "[ReceivedTime] >= '"
                   + one_hour_before.strftime('%m/%d/%Y %H:%M %p')
                   + "'")

# Print them
if len(one_hour_before_messages) == 0:
  print('No items received one hour before.')
else:
  print('Items received one hour before:')
  for one_hour_before_message in one_hour_before_messages:
    print(f'{one_hour_before_message.ReceivedTime} \
- {one_hour_before_message.Subject}')

Result of code above:
one_hour_before: 2020-03-09 12:31:06.515809+09:00
受信トレイ

0       2020-03-09 13:19:04.102000+00:00 - RE: TEST
^^^     RECEIVED ONE HOUR BEFORE
1       2020-03-09 09:46:10.128000+00:00 - TEST
Items received one hour before:
2020-03-09 13:19:04.102000+00:00 - RE: TEST


text:
Q: PHP 6 - Roadmap? Has anyone found a roadmap for PHP version 6?
Also, any very rough ETA on the release date (please don't answer "when it's ready", I'm just trying to get a sense of if it's first half of 2010, second half, etc)

A: There already is a dev version that you can use, 6.0.0-dev
http://snaps.php.net/
If I had to guess, it will be 2 years at least before we see betas and release candidates.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Angular Karma-Jasmine Unit Testing with EJS index I am trying to implement front-end unit-tests on an Angular project which uses a server-side templating engine to render an index.ejs or index.dust. This file also includes a global variable var cdn = "http://s3.amazon.com"; which is used throughout the angular app.
When I runstart karma karma.config.js, I receive ReferenceError: cdn is not defined: app.js L20.
The cdn var is available when I run my app with Node, but when I try to run unit-tests on my Angular Ctrls, I receive the error above.
I tried to use the karma-ejs-preprocessor module (here: https://www.npmjs.com/package/karma-ejs-preprocessor) to instantiatecdn in my tests, but I get a new error: No provider for "framework: jasmine".
index.ejs
<!doctype html>

    <meta charset="utf-8">
    <title>Test</title>

Angular Unit Testing

karma.conf.js
    // Karma configuration
// Generated on Sat Mar 12 2016 02:53:19 GMT-0800 (Pacific Standard Time)

module.exports = function(config) {
  config.set({

    // base path that will be used to resolve all patterns (eg. files, exclude)
    basePath: '',

    // frameworks to use
    // available frameworks: https://npmjs.org/browse/keyword/karma-adapter
    frameworks: ['jasmine'],

    // list of files / patterns to load in the browser
    files: [
      'client/src/bower_components/angular/angular.js',
      'client/src/bower_components/angular-ui-router/release/angular-ui-router.js',
      'client/src/bower_components/angular-mocks/angular-mocks.js',
      'client/src/bower_components/angular-resource/angular-resource.js',
      'client/src/app.js',
      'tests/test.js'
    ],

    // list of files to exclude
    exclude: [
    ],

    plugins: [
      'karma-qunit',
      'karma-ejs-preprocessor',
      'karma-jasmine',
      'karma-chrome-launcher'
    ],

    // preprocess matching files before serving them to the browser
    // available preprocessors: https://npmjs.org/browse/keyword/karma-preprocessor
    preprocessors: {
      'server/_views/index.ejs': ['ejs']
    },

    ejsOptions: {
      parentPath: './server/_views/index.ejs'
    },

    // test results reporter to use
    // possible values: 'dots', 'progress'
    // available reporters: https://npmjs.org/browse/keyword/karma-reporter
    reporters: ['progress'],

    // web server port
    port: 9876,

    // enable / disable colors in the output (reporters and logs)
    colors: true,

    // level of logging
    // possible values: config.LOG_DISABLE || config.LOG_ERROR || config.LOG_WARN || config.LOG_INFO || config.LOG_DEBUG
    logLevel: config.LOG_INFO,

    // enable / disable watching file and executing tests whenever any file changes
    autoWatch: true,

    // start these browsers
    // available browser launchers: https://npmjs.org/browse/keyword/karma-launcher
    browsers: ['Chrome'],

    // Continuous Integration mode
    // if true, Karma captures browsers, runs the tests and exits
    singleRun: false,

    // Concurrency level
    // how many browser should be started simultaneous
    concurrency: Infinity
  })
}

test.js
describe('State1Ctrl', function () {
  var $rootScope,
      $scope,
      controller;

  beforeEach(function () {
    module('app', 'ui.router');

    inject(function ($injector) {
      $rootScope = $injector.get('$rootScope');
      $scope = $rootScope.$new();
      controller = $injector.get('$controller')('State1Ctrl', { $scope: $scope } );
    });
  });

  describe('Init', function () {
    it('should be init', function () {
      expect($scope.test).toBeTruthy();
    });
  });
});

app.js
(function() {
  'use strict';

  angular.module('app', [
    'ui.router'
  ])

  .controller('State1Ctrl', ['$scope', function($scope) {
    console.log('cdn2', cdn);
    $scope.test = 'hi';
    console.log($scope.test);
  }])

  .config(['$stateProvider', '$urlRouterProvider', function ($stateProvider, $urlRouterProvider) {
     // For any unmatched url, redirect to /state1
  $urlRouterProvider.otherwise("/state1");

  // cdn is available here
  console.log("cdn: ", cdn);

  // Now set up the states
  $stateProvider
    .state('state1', {
      url: "/state1",
      templateUrl: cdn + "views/state1.html",
      controller: 'State1Ctrl'
    })
    .state('state1.list', {
      url: "/list",
      templateUrl: "views/state1.list.html",
      controller: function($scope) {
        $scope.items = ["A", "List", "Of", "Items"];
      }
    })
    .state('state2', {
      url: "/state2",
      templateUrl: "views/state2.html"
    })
    .state('state2.list', {
      url: "/list",
      templateUrl: "views/state2.list.html",
      controller: function($scope) {
        $scope.things = ["A", "Set", "Of", "Things"];
      }
    });

  }]);

})();

Repo here demonstrating problem: https://github.com/superveetz/Loopback-Tests.git

*

*npm install from base.

*bower install from /client/src

*karma start karma.conf.js from base.

*node . from base to see cdn is avail normally.

A: Please update your plugin part in karma.config.
plugins: [
  'karma-qunit',
  'karma-ejs-preprocessor',
  'karma-jasmine',
  'karma-chrome-launcher'
],

and run these command.
npm install karma-jasmine --save-dev

npm install karma-chrome-launcher --save-dev

for further details please check here
EDIT 1:
Please do thihs changes.
inject(function ($injector) {
      $rootScope = $injector.get('$rootScope');
      $scope = $rootScope.$new();
      controller = $injector.get('$controller')('State1Ctrl', { $scope: $scope } );
    });

Instead of $rootScope.new() use $rootScope.$new()
Define  cdn console.log('cdn2', cdn) your cdn so it will not stop your test script


text:
Q: How to turn off or fix: Property 'children' does not exist on type 'ChildNode'.ts(2339) on Typescipt? I have the following code and although it works like a charm, TS complains that "children" does not exist. I tried turning it off but that didn't have an effect. How can I solve this error either by turning it off or adding the correct type?

Property 'children' does not exist on type 'ChildNode'.ts(2339)

 const pElement = React.useRef<HTMLParagraphElement>(null)

  if (id % 2 === 0) {
    /* eslint-disable-next-line  */
 pElement.current!.parentElement!.nextSibling!.children[3].classList.remove(class)
      } else {
   /* eslint-disable-next-line  */
pElement.current!.parentElement!.previousSibling!.children[3].classList.remove(class)
          }


text:
Q: How to call a recursive linked list traversal function in C++ I have this function:
    void TraverseRecursive ( Node * head, void (*visit) (Node *) )
    {
      if ( head != nullptr )
      {
        visit( head ) ;
        TraverseRecursive( head->next, visit ) ;
      }
    }

And I'm trying to call it in main.cpp with
TraverseRecursive ( head, TraverseRecursive ) ;

Which gives me the error "argument of type "void (*)(Node *head, void (*visit)(Node ))" is incompatible with parameter of type "void ()(Node *)" "
So how do I correctly call it? I am just learning linked lists and obviously don't understand what
 void (*visit) (Node *)

means at all.

A: The second argument should be a function to call back for every node in the list. It only takes a single parameter (the node to "visit").
void visitor(Node *node)
{
  printf("%s\n", node->data);  // Or whatever
}

TraverseRecursive( head, visitor ) ;

Side note: What wasteful use of recursion. If you're lucky, the compiler will optimize it away. You should be using
void TraverseRecursive( Node * head, void (*visit) (Node *) )
{
  for (; head != nullptr; head = head->next)
  {
    visit( head ) ;
  }
}

A: void (*visit) (Node *)

means "pointer to a function taking one argument of type Node* and returning void". But TraverseRecurive takes two argumenst and is therefore of different type.
You need to define a function like
void doSomething(Node* n)
{
}

and pass it to TraverseRecursive


text:
Q: How many instances of a letter appear in a dictionary I have this question where it takes a dictionary and tries to find each instance of a letter if it exists and prints it so
 get_letter_frequency('all animals are equal but some animals are more equal than others')

would print:
a appears 10 times
b appears 1 time
e appears 7 times
h appears 2 times
i appears 2 times
l appears 6 times
m appears 4 times
n appears 3 times
o appears 3 times
q appears 2 times
r appears 4 times
s appears 4 times
t appears 3 times
u appears 3 times

I have this so far for my get_letter_frequency function
def get_letter_frequency(a_string):
    dictionary = {}
    words = a_string.split()
    for letters in words:
      if letters != " ":
          if letters in dictionary:
              dictionary[letters] += 1
          else:
              dictionary[letters] = 1
      dictionary_keys = dictionary.keys()
      new_list = list(dictionary_keys)
      new_list.sort()
      for alphabet in new_list:
          if dictionary[alphabet] == 1:
              print(alphabet, "appears", dictionary[alphabet], "time")
          else:
              print(alphabet, "appears", dictionary[alphabet], "times")

But this instead gives me all the letters in the dictionary and tells me how many times it appear.
all appears 1 time
animals appears 2 times
are appears 2 times
but appears 1 time
equal appears 2 times
more appears 1 time
others appears 1 time
some appears 1 time
than appears 1 time

Can you please help. Thank you.

A: The issue in the code is:
for letters in words:

Since words is a list of words, the variable letters will contain each of those words in turn, not the letters from those words.
The Counter class from the collections module does what you need:
In [1]: from collections import Counter

In [2]: ctr = Counter('all animals are equal but some animals are more equal than others')

In [3]: list(ctr)
Out[3]: ['a', ' ', 'b', 'e', 'i', 'h', 'm', 'l', 'o', 'n', 'q', 's', 'r', 'u', 't']

In [4]: dict(ctr)
Out[4]:
{' ': 11,
 'a': 10,
 'b': 1,
 'e': 7,
 'h': 2,
 'i': 2,
 'l': 6,
 'm': 4,
 'n': 3,
 'o': 3,
 'q': 2,
 'r': 4,
 's': 4,
 't': 3,
 'u': 3}

Without using the collections module
If you must do this with for loops and no modules:
def get_letter_frequency(a_string):
    dictionary = {}
    for letter in a_string.replace(' ', ''):
        dictionary[letter] = dictionary.get(letter, 0) + 1
    for letter in sorted(dictionary.keys()):
        print(letter, "appears", dictionary[letter], ["time", "times"][dictionary[letter]>1])

For example:
>>> get_letter_frequency('all animals are equal but some animals are more equal than others')
a appears 10 times
b appears 1 time
e appears 7 times
h appears 2 times
i appears 2 times
l appears 6 times
m appears 4 times
n appears 3 times
o appears 3 times
q appears 2 times
r appears 4 times
s appears 4 times
t appears 3 times
u appears 3 times

A: The error is in these lines:
words = a_string.split()
for letters in words:

You are expecting it to iterate all the letters in words, but it actually traverses individual words. In Python, you can use strings as if they are lists of characters, so changing your `for line to the following will work:
for letters in a_string:

A: I would argue using collections.Counter gives you the most elegant solution, but if you prefer to use your own function try
letters = list(a_string)

instead of str.split().

A: Lets say you have the string as such(taking from your example)
statement = 'all animals are equal but some animals are more equal than others'
characters = list(statement)

then

from collections import Counter

Counter(characters)

Output:

Counter({'a': 10,
         'b': 1,
         'e': 7,
         'h': 2,
         'i': 2,
         'l': 6,
         'm': 4,
         'n': 3,
         'o': 3,
         'q': 2,
         'r': 4,
         's': 4,
         't': 3,
         'u': 3})

It seems like all the answers are more or less on same lines :D

A: The standard library provides for such counters:
>>> from collections import Counter
>>> words = "apple banana apple strawberry banana lemon cupcake battery staple"
>>> Counter(words)
Counter({' ': 8,
         'a': 12,
         'b': 4,
         'c': 2,
         'e': 7,
         'k': 1,
         'l': 4,
         'm': 1,
         'n': 5,
         'o': 1,
         'p': 6,
         'r': 4,
         's': 2,
         't': 4,
         'u': 1,
         'w': 1,
         'y': 2})

A: words = a_string.split() splits the string into a list of words. You then loop through all those words instead of the letters. Since you don't seem to care for spaces " " you could replace that by
no_whitespace_str = a_string.replace(" ", "")
for letters in no_whitespace_str:
    ...

A shorter version would be
def get_letter_frequency(str):
    occ = {v: str.count(v) for v in str.replace(" ","")}
    for letter, num in sorted(occ.iteritems()):
        print "{} appears {} times".format(letter, num)

A: sent = "all animals are equal but some animals are more equal than others"
dic = {}

for ele in sent:
    dic.setdefault(ele,0) += 1

This gives dic as using (print dic)
{'a': 10, ' ': 11, 'b': 1, 'e': 7, 'i': 2, 'h': 2, 'm': 4, 'l': 6, 'o': 3, 'n': 3, 'q': 2, 's': 4, 'r': 4, 'u': 3, 't': 3}
In python string is a list so you can iterate over individual characters in a string


text:
Q: Bootstrap vertical alignment not working no matter what I've read tons of different topics and articles about that common issue but still no working solution. Now I'm kinda desperate so I'd very grateful for any help and here's code:

.auth-tab {
 background-color: red;
}

    sth

What I want is to vertically and horizontally align .auth-tab

A: Break it down into small testable steps without referencing all the various classes at once. Start with just the container, row and single column. Then test to evaluate if it works. Then add one more class and test. Repeat until you see what fails. My guess is the syntax. What version of bootstrap is being used. Also, instead of calling a bootstrap class, call the css attribute; style="text-align:center;".


text:
Q: openlayers3 prevent screen updates I'm working on a openlayers3 application and we will need to reorder the display layers.  I would like to be able to prevent display updates until we are finished changing the layer collection.  Is that possible?
thanks, D

A: may be helpful:
var features = getYourFeature

or
var features = layer.getSource().getFeatures();

then do something with the features with your own business
it's a collection(array) of feature
then reset the features to the layer like this
layer.getSource().clear();
layer.getSource().addFeatures(features);

*/


text:
Q: Plot time series of credit ratings (letters) R ggplot2 stairs plot I am trying to make a stairs plot for a credit ratings time series, but the plot I obtain is disconnected in between each steps. I would like the plot not to have disconnections when the credit rating goes up or down. See example below.
ratings = c("BB+", "BBB+", "A-", "A", "A")
dates = c("2005-04-27", "2005-04-28", "2008-05-01", "2009-05-02", "2010-05-03")

df = data.frame(dates, ratings)

df$ratings = factor(df$ratings, levels=rev(unique(df$ratings))) # order credit ratings

library("ggplot2")
ggplot(df, aes(x=dates)) +
  geom_step(aes(y = ratings))+
  ylab(label="Ratings") +
  xlab("Date")

A: The problem is that geom_step is built on geom_line, which defaults to splitting categorical factors into separate lines. So in this case, geom_step is working as intended, but because each category is on one horizontal line, you never see a step. We can overcome this by overriding the default grouping by setting group = 1. Also, when you create your example data, the date vector should be wrapped in as.Date.
ratings = c("BB+", "BBB+", "A-", "A", "A")
dates = as.Date(c("2005-04-27", "2005-04-28", "2008-05-01", "2009-05-02", "2010-05-03"))

df = data.frame(dates, ratings)

df$ratings = factor(df$ratings, levels=rev(unique(df$ratings))) # order credit ratings

library("ggplot2")
ggplot(df, aes(x=dates)) +
  geom_step(aes(y = ratings, group = 1))+
  ylab(label="Ratings") +
  xlab("Date")

Plotting multiple time series
To plot multiple series as intended with ggplot, you want "long" data, in which each row contains a single observation. This means that rather than having a column for each series, you'll have a column for the ratings, a column for the corresponding dates, and a column that labels each series (the dplyr or reshape2 packages are good at transforming data to long format). For example:
ratings = c("BB+", "BBB+", "A-", "A", "A", "BBB+")
dates = as.Date(c("2005-04-27", "2005-04-28", "2008-05-01", "2009-05-02", "2010-05-03", "2011-01-01"))
rating.series = factor(c(1, 1, 1, 2, 2, 2))

df = data.frame(dates, ratings, rating.series)

df$ratings = factor(df$ratings, levels=rev(unique(df$ratings))) # order credit ratings

library("ggplot2")
ggplot(df, aes(x=dates)) +
  geom_step(aes(y = ratings, group = rating.series, color = rating.series))+
  ylab(label="Ratings") +
  xlab("Date")


text:
Q: GET imageRoute 404 (Not Found) on Laravel I have a Laravel project that I've mainly been working on it's back end, but now I copied the layouts from another project which has two images on the header. This is one of them:

The images on my old project are stored on public/imagenes/temp_imgs/, so I created those same folders on my new project and stored the images there. But when I run it I get the following error:

GET http://localhost:8000/competencias/imagenes/temp_imgs/logo%20temporal.png 404 (Not Found)

It seems as if it isn't looking for the images on my public folder but rather on the location of the view (competencias), the view is competencias/crear.blade.php
I don't remember much from the configuration on the old project, I only now I ran npm install on both at creation, so both have bootstrap and vue. But that's al I now, maybe you can help me see if a configuration file on the old project is making the image src point to the public folder, or figuring out what's generating the error.
EDIT:
If I paste one of the files from my old project to my new one the images are shown. If I rename one of the files from my new project and give it a name of a file from my old project the images are also shown! I hope this helps in figuring this thing out.

A: You should use {{ asset('imagenes/temp_imgs/logo temporal.png') }}
For all assets use {{asset(....)}} to solve all problems that maybe appear for you
Hope help you

A: in laravel 5.4 you will not able to see image as your link
route will lock your every public folder
http://localhost:8000/competencias/imagenes/temp_imgs/logo%20temporal.png

just try to use like that

or


text:
Q: If $G_1, G_2$ are two nonzero subgroups of $(\mathbb{Q},+)$, prove that $G_1\cap G_2\neq\{0\} $. Let $(\mathbb{Q},+)$ be additive group of rational numbers. If $G_1, G_2$ are two nonzero subgroup of $(\mathbb{Q},+)$, prove that $G_1\cap G_2\neq\{0\}$.
My approach :
Take $p/q\in G_1$ and $a/b \in G_2$. Then $p/q+p/q+..=p \in G_1 $ ($q$ times addition). Similarly $a\in G_2$.
Now we can always choose $p$ and $a$ as positive because in group their inverse are of opposite parity.
Now set $l=lcm(p,a)$. Since $l=\frac{pa}{d}$ where $d=\gcd(p,a)$ one finds $l\in G_1$.
Reason : Just  $p+...p=l$ where (addition is done $\frac{a}{d}$ times).
similarly $l\in G_2$.
So $l\in G_1\cap G_2 $.
Hence $G_1\cap G_2\neq \{0\}$. Proved
I would like to know if my solution is correct. This was supposed to be a tough problem. So it feels like i have committed some mistake in proof. Thank you.

A: seems ok! both groups are Z-modules so $ bp\frac{a}{b}=pa \in G_1$ and similarly $aq\frac{p}{q} = ap \in G_2$


text:
Q: Netsuite - CSV Import of Invoices I'm using NetSuite's CSV import to import invoices into the system.
The problem is that we tried to import transactions that should have been made from Sales Orders, with column Created From in CSV and wanted to map it to Created From Field. But because field Created From is disabled in Netsuite and cant be added to custom form of invoice, we don't have an option to map the data to that field.
Is there a workaround for this problem except to make a map/reduce script that would do record.transform() on said sales order records?


text:
Q: How can i clone a fieldset without displaying it to the user? I have a fieldset here:
<fieldset class="pollQuestion" id="pq1">
    <legend id="legend">Q&A</legend>

            <input type="text" id="formheader" value="Question 1""></input>

            <input type="button" class="addQuestion" value="Add Question" />
            <input type="button" class="delQuestion" value="Remove Question" />

        Answers

            <input type="text" id="formanswer1" value="" />

            <input type="button" class="addAnswer" value="Add Answer" />
            <input type="button" class="delAnswer" value="Remove Answer" />

</fieldset>

I want to clone() this because i may populate it with array contents or i may just not fill it out at all. I would like a function like:
$(document).ready(function () {
    window.clone = $('#pq1').clone();
});

but i can't get it to work for some reason
I have an example fiddle here.

A: You have two typos:
window.clone = "$('#pq1').clone()"; //remove quotes

$('$clone').attr('id', 'pq'+newNum); should be $clone.attr('id', 'pq'+newNum);
Updated fiddle

A: That will create only one clone which you try to append multiple times.
But aside from that, in your Fiddle you put that in a string window.clone = "$('#pq1').clone()"
And then after running $clone = window.clone you try to use that in a jQuery object $("$clone")... something tells me you have no idea what you're doing...
Here is the updated Fiddle. I've managed to salvage it so that you can create new questions, but you can't remove them because you try to access #btnDel, which doesn't exist. Good luck...

A: $(document).ready(function () {
   $(".pollQuestion").clone().appendTo("#legend");
});

If this is want you are trying to do!

A: In order to clone the element, you can do:
$(document).ready(function () {
    var $clone = $('#pq1').clone();
}

And then, in your click event, use that $clone object (don't declare it again). It won't be displayed until you attach it to DOM.

A: Try this:
$(document).ready(function () {
    //store in a local variable to document.ready so as not to pollute the global namespace
    var myClone = $('#pq1').clone();
    // move into document.ready so it has access to the local variable.
    $('.addQuestion').live('click', function () {
        var num = $("#pollContent fieldset.pollQuestion").length;
        var newNum = new Number(num + 1); // the numeric ID of the new input field being added
        // return a clone of the original cloned object.
        var $clone = myClone.clone();
        //remove the quotes from $clone as you want to pass the jQuery constructor a jQuery object, not a selector string.
        $($clone).attr('id', 'pq' + newNum);
        //update the question in the text box for visual confirmation that this is working.
        $($clone).find('#formheader').val('Question ' + newNum);
        // insert the new element after the last "duplicatable" input field
        $('#pq' + num).after($clone);
        // enable the "remove" button
        $('#btnDel').attr('disabled', '');
    });
});

and, of course, an updated fiddle.


text:
Q: Cannot set headers after they are sent : response.redirect() NodeJS I need to user diferents response.redirect() but I get an error in my console.
Error code : Unhandled rejection Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client
My code :
    // on vérifie si max par semaine atteint si c'est le cas on supprime la resa
    if (moment(createdItem.date).isSame(new Date(), 'week')) {
      createdItem.destroy().then(function() {
        request.flash('danger', 'Total de réservation maximum par semaine atteint');
        response.redirect('/user/__show');
      });
    }

    // dans le cas d'un abonnement trouvé on touche pas aux cartes
    if (findedRpaUserServiceSub) {
      request.flash('success', 'Réservation ajoutée');
      response.redirect('/user/__show');
    }

    // si on trouve une carte mais sans abonnement
    if (findedRpaUserServiceCard) {
      if ((findedRpaUserServiceCard.remaining_services - 1) === 0) {
        findedRpaUserServiceCard.destroy().then(function() {
          request.flash('success', 'Réservation ajoutée');
          response.redirect('/user/__show');
        });
      } else {
        findedRpaUserServiceCard.update({
          remaining_services: findedRpaUserServiceCard.remaining_services - 1
        }).then(function() {
          request.flash('success', 'Réservation ajoutée');
          response.redirect('/user/__show');
        });
      }
    }

A: You are redirecting the user multiple times. These if are not exclusives. You should, at minima, use else if statement
// on vérifie si max par semaine atteint si c'est le cas on supprime la resa
    if (moment(createdItem.date).isSame(new Date(), 'week')) {
      createdItem.destroy().then(function() {
        request.flash('danger', 'Total de réservation maximum par semaine atteint');
        response.redirect('/user/__show');
      });
    }

    // dans le cas d'un abonnement trouvé on touche pas aux cartes
    else if (findedRpaUserServiceSub) {
      request.flash('success', 'Réservation ajoutée');
      response.redirect('/user/__show');
    }

    // si on trouve une carte mais sans abonnement
    else if (findedRpaUserServiceCard) {
      if ((findedRpaUserServiceCard.remaining_services - 1) === 0) {
        findedRpaUserServiceCard.destroy().then(function() {
          request.flash('success', 'Réservation ajoutée');
          response.redirect('/user/__show');
        });
      } else {
        findedRpaUserServiceCard.update({
          remaining_services: findedRpaUserServiceCard.remaining_services - 1
        }).then(function() {
          request.flash('success', 'Réservation ajoutée');
          response.redirect('/user/__show');
        });
      }
    }
    else {
     // something else
    }

You can also add a return inside each if to stop further processing or use next() if you are using expressjs to go to the next middleware.


text:
Q: What do we mean by building the instances of abstract class? CloseableHttpClient is an abstract class and it is mention in the document of HttpClientBuilder that it build instances of CloseableHttpClient.
But we can't build the instances of abstract class ?
Class HttpClientBuilder --> Builder for CloseableHttpClient instances.
CloseableHTTpClient is an abstract class.
I would like to know the meaning of the below line
CloseableHttpClient client = HttpClientBuilder.create().build()

The Build method is returning object of type CloseableHttpClient.


text:
Q: Install MovableType under Nginx on Ubuntu I want to try MovableType (and I do not want to install Apache).
I took a clean Ubuntu Server 9.10 instance, and did something along these lines:
$ sudo apt-get install mysql mysqlclient
$ sudo apt-get install movabletype
$ sudo apt-get install nginx

Now I see that I have to tell nginx to look at /usr/lib/cgi-bin/movabletype/.
But nginx does not support pure CGI scripts, and I've got a feeling that MovableType would want some custom configuration anyway.
I failed to find any good docs on how to pair MT with nginx. Are there any? A config file example would be perfect.

A: *

*Add additional fastcgi parameters in nginx config:
fastcgi_param    PERL5LIB $document_root/mt/lib;
fastcgi_param    MT_HOME $document_root/mt;
fastcgi_param    MT_CONFIG $document_root/mt/mt-config.cgi;

*Use CGI wrapper from http://nginx.localdomain.pl/wiki/FcgiWrap


text:
Q: Origin 'http://localhost:3000' is therefore not allowed access Twitter API I'm developing a web application that uses the Twitter API REST. I have a page with Twitter accounts and a button for adding a new account. When the button is pressed, the function in the Angular controller is executed:

// Calls token to add a new Twitter user
    $scope.callToken = function () {
        $http.get('/token')
            .then(function (response) {
                console.log(response);
            });
    };

This is the code in the backend to serve de request. It simply redirects to Twitter to add a new user.

// routes.js
var token = express.Router();

 token.route('/token')
  .get(cuentasCtrl.getToken);

// Account file

exports.getToken = function(req, res) {

 twitter.getRequestToken(function(err, requestToken, requestSecret) {
        if (err)
            res.status(500).send(err);
        else {
            _requestSecret = requestSecret;
            res.setHeader('Access-Control-Allow-Origin', '*');
            res.redirect("https://api.twitter.com/oauth/authenticate?oauth_token=" + requestToken);
        }
    });
};

But I get the next error:
Origin 'http://localhost:3000' is therefore not allowed access Twitter API

My server is running on localhost:3000 and If I put localhost:3000/token in my browser there is no problem. I have read  the solutions for using CORS and tested other browsers but it hasn't worked for me. What have i done wrong?

A: The redirect you are sending in your express response is caught by the http client you use in the frontend and the redirect happens there. You are in a classical CORS situation and of course this is not how you can interact with the Twitter rest APIs.
You have to make http calls to Twitter on the node side (server to server) or use a client side client library for Twitter (https://dev.twitter.com/web/javascript)


text:
Q: Why is my gif pixelated in firefox and not in google chrome browser? I have a gif as logo in my navbar, in google chrome the gif looks fine but in firefox and internet explorer it is getting pixelated.
Here below the result left chrome right firefox:

How can I fix this I allready tried is this:
Image-rendering: -webkit-optimize-contrast or this image-rendering: optimizequality;
But none of them results in a sharp gif
Here is the html with css:
<img src="/img/dasbot-logo-wit.gif" alt="" class="logo-img">

img {
    max-width: 100%;
    height: auto;
}

How is this possible and how can I fix this?
Here is the gif link:
https://gph.is/2HYzaqT

A: For all of us, this logo appears to be pixelated around the edges of the words. To fix this, you should download some sort of application, (Coreldraw is my recommendation, just use the trial), then run a quick trace of each frame in the animation. A quick trace just traces the outside of the item and makes it look not pixelated. It also has other functions (laser cutting), but that doesn't matter right now.
Once you have your gif traced, you should re-upload it back onto giphy. This isn't a coding solution as it is a problem with your gif.


text:
Q: Multiple loops issue in matlab Sorry for asking really basic question but I am confused in multiple loops.
I want to run loops all at same time and then break the loop and go to next loop for R, e and x combine.
Means for R =1 ,e=1 ,x=1 and then R=2 ,e=2 ,x=2 and so on.

Can someone tell me where I am at fault or what is missing to get my desired results?
Code:
 threshold = [0.4:0.1:1.1];
 limit_for_idx  = [0.4:0.1:1.1];
 limit = [0.4:0.1:1.1];

 D=1;
 E=1;
 J=0;
  for R = 1:numel(threshold);
      for e = 1:numel(limit_for_idx);
          for x = 1:numel(limit)

          J = J+1 ;
          % Perform Tasks and go to next loop for R ,e and x
          break
      end
        break
    end
  end

A: The wrong in your code is that in the 2nd iteration and so on, e and x will get 1 again, and not 2 or which value that you want.
To solve that, just iterate one variable and equal them all to it:
threshold = [0.4:0.1:1.1];
limit_for_idx  = [0.4:0.1:1.1];
limit = [0.4:0.1:1.1];
D=1;
E=1;
J=0;
for R=1:numel(threshold)
   e=R;
   x=R;
   % do your stuff...
end


text:
Q: Java service which extracts the value of a field at runtime I need to build a java service which extracts the value of a field at runtime. The path of the field in the canonical and the canonical document itself should be given as input.
Eg:
fromDoc consists of sub documents within it, in a hierarchy, ie.
fromDoc/Data/Parameters/outDate
 •fromDoc

     •Data

        •Parameters

           •outDate(string)

For inStringValues I give the input as 'fromDoc/Data/Parameters/outDate'
the output should return the value of the variable 'fromDoc/Data/Parameters/outDate' at run time.
I have a code which implements this with the key value pair logic.
IDataCursor pipelineCursor = pipeline.getCursor();

      // fromDoc
IData     fromDoc = IDataUtil.getIData( pipelineCursor, "fromDoc" );
String[] inStringValues = IDataUtil.getStringArray( pipelineCursor, "inStringValues" );
if ( fromDoc == null)
{
    return;
}
pipelineCursor.destroy();
int len = inStringValues.length;
String[] outStrings = new String[len];
IDataCursor fromCursor = fromDoc.getCursor();
boolean hasData = false;

while( fromCursor.next() )
{
    for(int i=0;i<len;i++)
    {
        String key = fromCursor.getKey();
        String val = fromCursor.getValue().toString();
        if(key.equals(inStringValues[i]))
        {
             outStrings[i]=key + "," + val;
        }
    }
}

fromCursor.destroy();

IDataCursor pipelineCursor_1 = pipeline.getCursor();
IDataUtil.put( pipelineCursor_1, "outStrings", outStrings );

pipelineCursor_1.destroy();

Please let me know how I can modify this code to implement the above mentioned logic?
Or let me know if anyone has such an existing service with you.

A: Tundra has a service that does exactly what you need: tundra.document:get($document, $key).

*

*$document is the com.wm.data.IData document you want to extract the value from

*$key is the name of the key you want to extract, and can be fully-qualified and include array indexing, for example "path/to/my[1]/key"
The relevant Java code is as follows:
public static final void get(IData pipeline) throws ServiceException {
  IDataCursor cursor = pipeline.getCursor();

  try {
    IData document = IDataUtil.getIData(cursor, "$document");
    String key = IDataUtil.getString(cursor, "$key");
    IDataUtil.put(cursor, "$value", get(document, key));
  } finally {
    cursor.destroy();
  }
}

// wrapper class for fully qualified IData keys
public static class Key {
  public static final String SEPARATOR = "/";
  public static final java.util.regex.Pattern INDEX_PATTERN = java.util.regex.Pattern.compile("\\[(-?\\d+?)\\]$");

  protected boolean hasIndex = false;
  protected int index = 0;
  protected String key = null;

  public Key(String key) {
    java.util.regex.Matcher matcher = INDEX_PATTERN.matcher(key);
    StringBuffer buffer = new StringBuffer();
    while(matcher.find()) {
      hasIndex = true;
      index = Integer.parseInt(matcher.group(1));
      matcher.appendReplacement(buffer, "");
    }
    matcher.appendTail(buffer);
    this.key = buffer.toString();
  }

  public boolean hasIndex() {
    return hasIndex;
  }

  public int getIndex() {
    return index;
  }

  public String toString() {
    return key;
  }

  public static java.util.Queue<Key> parse(String key) {
    String[] parts = key.split(SEPARATOR);
    java.util.Queue<Key> queue = new java.util.ArrayDeque<Key>(parts.length);

    for (int i = 0; i < parts.length; i++) {
      queue.add(new Key(parts[i]));
    }
    return queue;
  }

  public static boolean isFullyQualified(String key) {
    return key != null && (key.contains(SEPARATOR) || INDEX_PATTERN.matcher(key).find());
  }
}

// returns the value associated with the given key from the given IData document
public static Object get(IData input, String key) {
  Object value = null;
  if (input != null && key != null) {
    // try finding a value that matches the literal key
    IDataCursor cursor = input.getCursor();
    try {
      value = IDataUtil.get(cursor, key);
    } finally {
      cursor.destroy();
    }

    // if value wasn't found using the literal key, the key could be fully qualified
    if (value == null && Key.isFullyQualified(key)) value = get(input, Key.parse(key));
  }

  return value;
}

// gets a value from an IData document with a fully qualified key
protected static Object get(IData input, java.util.Queue<Key> keys) {
  Object value = null;

  if (input != null && keys != null && keys.size() > 0) {
    IDataCursor cursor = input.getCursor();
    Key key = keys.remove();

    if (keys.size() > 0) {
      if (key.hasIndex()) {
        IData[] array = IDataUtil.getIDataArray(cursor, key.toString());
        value = get(get(array, key.getIndex()), keys);
      } else {
        value = get(IDataUtil.getIData(cursor, key.toString()), keys);
      }
    } else {
      if (key.hasIndex()) {
        Object[] array = IDataUtil.getObjectArray(cursor, key.toString());
        value = get(array, key.getIndex());
      } else {
        value = IDataUtil.get(cursor, key.toString());
      }
    }
    cursor.destroy();
  }

  return value;
}

public static <T> T get(T[] array, int index) {
  T item = null;

  if (array != null) {
    // support reverse/tail indexing
    if (index < 0) index += array.length;

    item = array[index];
  }

  return item;
}

Note: Tundra has a complementary service for setting a value in a com.wm.data.IData document too: tundra.document.put($document, $key, $value).

A: What about this ?
    // fromDoc
    IDataCursor cursor = pipeline.getCursor();
    IData fromDoc = IDataUtil.getIData(cursor, "fromDoc");

    if (fromDoc == null) {
        return;
    }

    // Data
    cursor = fromDoc.getCursor();
    IData Data = IDataUtil.getIData(cursor, "Data");

    if (Data == null) {
        return;
    }

    // Parameters
    cursor = Data.getCursor();
    IData Parameters = IDataUtil.getIData(cursor, "Parameters");

    if (Parameters == null) {
        return;
    }

    // outDate
    cursor = Parameters.getCursor();
    String outDate = IDataUtil.getString(cursor, "outDate");

    // Here I have the outDate value


text:
Q: Javascript debugging in VS2013 not working properly There is a problem with VS 2013 and debugging JS code.
The problem is like when I try to debug a JS code in VS 2013 the debugger does not pause the code execution (which it should ideally) and let me debug. there is a workaround for this though which is run the code again the debugger will pause the code execution second time.
I usually don't load the solution I just open only the files (.js or .htm ) I need to debug and put the Debugger; in the code and run the page in the IE it invokes the JIT but previously in VS2010 it also pause he code execution in the line with Debugger;
But funny thing is it does so when i run the same code twice in the second time it hit the debugger; and pauses the code execution in the VS2013.
I did a little bit of googling after that i found that this is a known issue with VS 2103 and which has been fixed in Update 2.
Unable to debug
VS2013 Javascript Debugging
which all says the problem was fixed in the Update 2 but i have Update 4 installed in my system .
Is there any way to fix this. OR i am doing something wrong like any setting or something.


text:
Q: Removing unneeded row I am having an issue removing duplicated rows. I've tried using ORDER BY to remove duplicates but it needs to be more sophisticated than that and I am not sure how to do that. I have some duplicate rows that I would want to remove the one where the account number is null but what is making it complicated is that there are some rows that there is no account number at all and I want to keep those.
For example:
       AppID | First Name | Last Name |   SSN  | Account Number
Keep:  1021    John         Doe        ********  124989
Remove 1021    John         Doe        ********  NULL
Keep:  1287    Mary         Smith      ********  NULL

A: How to delete duplicate rows in SQL Server?
It should help you resolve your problem.
For next time you should search StackOverFlow more careful.

A: select * from (
select data.*,
---------you can add colums after partition by part. and decide which rows is needed and take them
row_number() over(partition by appid,first_name,last_name,ssn order by case when trim (account_number)= '' then 0 else 1 end desc)  rn
-----
from  (
select 1021 appid,'john' first_name,'doe' last_name, '****' ssn,124989 account_number from dual
union all
select 1021 appid,'john' first_name,'doe' last_name, '****' ssn,null account_number from dual
union all
select 1287 appid,'mary' first_name,'smith' last_name, '****' ssn,null account_number from dual
)data
)where rn=1

A: One method is row_number().  If you want one row for all combos of the first five columns:
select t.*
from (select t.*,
             row_number() over (partition by AppID, First Name, Last, Name, SSN
                                order by (case when account_number is not null then 1 else 2 end)
                               ) as seqnum
      from t
     ) t
where seqnum = 1;

Use rank() if you want to keep all rows that have valid accounts -- although you might need additional logic if you can have multiple rows with NULL accounts.
However, aggregation might also do what you want:
select AppID, First Name, Last, Name, SSN, max(account_number)
from t
group by AppID, First Name, Last, Name, SSN;


text:
Q: Autoshrink feature of Label in Tableview cell on scrolling doesn't work I have two labels side by side in custom cell of tableview. When I am adding data into it first time it looks like this :

which is fine and is the required design .
Problem occurs when I start scrolling the tableview. After going down in tableview and coming up it changes like this:

First label has autoshrink feature added but not in second label.  I am doing everything in storyboard except the data poulating part.
Please tell me if I am doing anything wrong in it.
Any help will be appreciated.
**EDIT: **
The custom cell that I have added in the project:

There are two labels that I have highlighted by selecting them.
Constraints for the First Label are:

I have also added Auto Shrink feature in first label :

Constraints for the second label are:

I haven't added Auto Shrink feature in second label as I have to keep fixed font size in second label.

A: Finally after reading more about Content Hugging Priority and Content Compression Resistance Priority I got the solution.
Thanks to this blog too:

*

*https://krakendev.io/blog/autolayout-magic-like-harry-potter-but-real
I changed the priority as follows:
For First label:

For Second Label :

and it is working perfectly fine.


text:
Q: Can someone explain this excel worksheet formula in a logical progression? I'm trying to convert this Excel worksheet formula to Python and I don't fully understand what's going on. I understand the cell references in this code and the "if(logical_test,[value_if_true],[value_if_false]" format, but I get lost in this piece of code while trying to understand it:
=IF('Sales on Amazon'!$K2="Standard", IF(
    AND(
         IF(
            'Sales on Amazon'!$G2,
            14/16,
            12/16
            )
        >='Sales on Amazon'!$E2,
        MAX(
            'Sales on Amazon'!$B2:$D2
           )
       <=15,
       MIN(
           'Sales on Amazon'!$B2:$D2
           )
       <=0.75,
       MEDIAN(
              'Sales on Amazon'!$B2:$D2
              )
         <=12
       ),
       "SML STND",
       "LRG STND"
   ),
   IF(
OR(
   'Sales on Amazon'!$J2>165,
   'Sales on Amazon'!$E2>150,
   MAX(
       'Sales on Amazon'!$B2:$D2
      )>108
   ),
"SPL OVER",
 IF(
    'Sales on Amazon'!$J2>130,
   "LRG OVER",
   IF(
      OR(
         'Sales on Amazon'!$E2>70,
         MAX(
             'Sales on Amazon'!$B2:$D2
            )>60,
         MEDIAN(
                'Sales on Amazon'!$B2:$D2
               )>30
         ),
      "MED OVER",
     "SML OVER")
  )
))

A: This should be fun.... So you have a data sheet named Sales on Amazon that this is referencing. That is where your data is.

*

*If the value in column K equals the string "Standard" then 2 through 7 are your True condition for your if statement, 8 through 17 are your False condition.

All of these need to be True to return a True for the AND

*If the value in column G is True, then 0.875, else 0.75, and if that is greater or equal to than the value in column E

*And the max of the range of columns B, C, D, is greater than or equal to 15

*And the min of the range of columns B, C, D, is less than or equal to0.75

*And the median of the range of columns B, C, D, is less than or equal to 12
This is the evaluation of the AND

*Then if 2, 3, 4, and 5, are True, SML STND

*Else LRG STND

This ends the True condition of the first if statement that starts the formula.

This begins the False conditionof the first if statement that starts the formula.

Only one of these need to be True for the If statements's condition to be True.

*If the value in column J is greater than 165

*Or if the value in column E is greater than 150

*Or the max of the range of columns B, C, D, is greater than 108

*Then if any either 8, 9, or 10 evaluate to True then SPL OVER

*Else if they are all False, then if the value of column J is greater than 130 then LRG OVER
ELSE 13 through 16 are the True condition for 12, which is the False condition for 8, 9, and 10.
Only one needs to return a true for the whole Or statement to be True, and  17 is the False condition.

*If the value in column E is greater than 70

*Or the max of the range of columns B, C, D, is greater than 60

*Or the median of the range of columns B, C, D, is greater than 30

*Then if any either 13, 14, or 15 evaluate to True then MED OVER

*Else SML OVER
And there you have it.
To test it out, just look at the data and work through these steps and see if the answer you get is the same as the value in Excel.

The reason I say columns is that I saw that the formulas had $B2 $D2, etc. So I made the assumption that this formula is copied down a column for a range of data. It however only reverences the values for those columns in the same row.


text:
Q: Why This Lua's Program Didn't Compile Correctly? (EEPro) First I want to clarify that I am a total newbie using Lua.
My Goal is Creating a Java application using the code posted below.
I have a Lenovo Y560, which has a Windows 7 x64 operating system. I downloaded LuaForWindows_v5.1.4-46 for this purpose.
As I said, my goal is to create a Java application for mobile which has a Symbian OS S40, my idea is to turn this program in Lua to Java. But along the way I doubt there were doubts.
I apologize if I made this question incorrectly.
EEPro for Nspire on Lua
Trying to Compile this Lua's Program, I got the following Error:
> > lua -e "io.stdout:setvbuf 'no'" "EEPro.big.lua"
> > lua: proyecto.big.lua:14: attempt to call field 'uchar' (a nil value)
> stack traceback:
proyecto.big.lua:14: in function 'utf8'
proyecto.big.lua:35: in main chunk
[C]: ?

Exit code: 1

Could you tell me why this Happen?

A: string.uchar can be implemented this way (just insert these lines at the beginning of yourEEPro.big.lua file):
function string.uchar(c, ...)
    if c then
        local t, h, s = {}, 128, string.uchar(...)
        while c >= h do
            t[#t+1] = 128 + c%64
            c = math.floor(c/64)
            h = h > 32 and 32 or h/2
        end
        t[#t+1] = 256 - 2*h + c
        return s.char((table.unpack or unpack)(t)):reverse()..s
    else
        return ''
    end
end


text:
Q: calling a method on the root from a component, what is wrong with my code? I have a component for my bootstrap modal. The modal has a button is labeled "Got It",which I am trying to call a method found on the root instance. It is not working--I cannot tell what I am missing. I have added a click handler and emit the click, but cannot trigger the clear function? Please advise what is wrong- thanks

 Vue.component('modal', {
    template: '#modal-template',
    props:{
        bgClass:{
            type:String,
            default:'default'
        },

    },
    methods: {
  clickHandler () {
      this.$emit('click');
    }

 }
  })

  new Vue({
      el: "#app",
      data: function data() {
      return{
      showModalZ:false
      }
      },

    methods: {

        clear: function(){
        alert("checkme");
        }
        }

  })
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css">
       <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css">
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css">

hello

                    <modal v-if="showModalZ" @close="showModalZ = false">

input goes here

                            test

                        </modal>

A: You need to emit 'close' event from model component clickHandler function and capture it on parent with @close
Working example:

Vue.component('modal', {
  template: '#modal-template',
  props: {
    bgClass: {
      type: String,
      default: 'default'
    }
  },
  methods: {
    clickHandler() {
      this.$emit('close');
    }
  }
})

new Vue({
  el: "#app",
  data: function data() {
    return {
      showModalZ: false
    }
  },
  methods: {
    clear: function() {
      alert("checkme");
    }
  }
})
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css">
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css">

hello

  <modal v-if="showModalZ" @close="showModalZ = false">

input goes here

test

  </modal>

A: simply use  this.$parent.$root.methodname()
e.g   this.$parent.$root.clear();

Vue.component('modal', {
    template: '#modal-template',
    props: {
        bgClass: {
            type: String,
            default: 'default'
        },
    },
    methods: {
        clickHandler() {
            this.$parent.$root.clear();
        }
    }
})

new Vue({
    el: "#app",
    data: function data() {
        return {
            showModalZ: false
        }
    },
    methods: {
        clear: function () {
            alert("checkme");
        }
    }
})
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css">
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css">

hello

<modal v-if="showModalZ" @close="showModalZ = false">

input goes here

        test

</modal>


text:
Q: Java Plugin Table Color T I have a view with a table that is populated with an array list. The problem is that I can't solve an error regarding the table foreground.
Piece of code:
(1) Table table = new Table(parent, SWT.SINGLE);
(2) table.setForeground(Color.BLUE);

error on (2) : The method setForeground(Color) in the type control is not applicable for the arguments (Color)
I've imported java.awt.color
Can anybody tell me where I'm wrong ?

A: Table is an SWT control and does not use anything from java.awt
You should be importing org.eclipse.swt.graphics.Color - but this does not have any predefined colors.
To get predefined colors in SWT use:
Display display = table.getDisplay();

Color color = display.getSystemColor(SWT.COLOR_BLUE);

A: You are mixing AWT and SWT. The setForeground method of an SWT table needs a org.eclipse.swt.graphics.Color reference. Call it like this:
Display display = table.getDisplay(); // or whatever can get you the display reference
table.setForeground(display.getSystemColor(SWT.COLOR_BLUE));


text:
Q: How to get the current datetime in UTC from an Excel VBA macro Is there a way in an Excel VBA macro to get the current datetime in UTC format?
I can call Now() to get the current time in the local timezone; is there a generic way to then convert this to UTC?

A: Granted this question is old, but I just spent some time putting together some clean code based on this and I wanted to post it here in case anyone coming across this page might find it useful.
Create a new Module in the Excel VBA IDE (optionally giving it a name of UtcConverter or whatever your preference may be in the Properties Sheet) and paste in the code below.
HTH
Option Explicit

' Use the PtrSafe attribute for x64 installations
Private Declare PtrSafe Function FileTimeToLocalFileTime Lib "Kernel32" (lpFileTime As FILETIME, ByRef lpLocalFileTime As FILETIME) As Long
Private Declare PtrSafe Function LocalFileTimeToFileTime Lib "Kernel32" (lpLocalFileTime As FILETIME, ByRef lpFileTime As FILETIME) As Long
Private Declare PtrSafe Function SystemTimeToFileTime Lib "Kernel32" (lpSystemTime As SYSTEMTIME, ByRef lpFileTime As FILETIME) As Long
Private Declare PtrSafe Function FileTimeToSystemTime Lib "Kernel32" (lpFileTime As FILETIME, ByRef lpSystemTime As SYSTEMTIME) As Long

Public Type FILETIME
  LowDateTime As Long
  HighDateTime As Long
End Type

Public Type SYSTEMTIME
  Year As Integer
  Month As Integer
  DayOfWeek As Integer
  Day As Integer
  Hour As Integer
  Minute As Integer
  Second As Integer
  Milliseconds As Integer
End Type

'===============================================================================
' Convert local time to UTC
'===============================================================================
Public Function UTCTIME(LocalTime As Date) As Date
  Dim oLocalFileTime As FILETIME
  Dim oUtcFileTime As FILETIME
  Dim oSystemTime As SYSTEMTIME

  ' Convert to a SYSTEMTIME
  oSystemTime = DateToSystemTime(LocalTime)

  ' 1. Convert to a FILETIME
  ' 2. Convert to UTC time
  ' 3. Convert to a SYSTEMTIME
  Call SystemTimeToFileTime(oSystemTime, oLocalFileTime)
  Call LocalFileTimeToFileTime(oLocalFileTime, oUtcFileTime)
  Call FileTimeToSystemTime(oUtcFileTime, oSystemTime)

  ' Convert to a Date
  UTCTIME = SystemTimeToDate(oSystemTime)
End Function

'===============================================================================
' Convert UTC to local time
'===============================================================================
Public Function LOCALTIME(UtcTime As Date) As Date
  Dim oLocalFileTime As FILETIME
  Dim oUtcFileTime As FILETIME
  Dim oSystemTime As SYSTEMTIME

  ' Convert to a SYSTEMTIME.
  oSystemTime = DateToSystemTime(UtcTime)

  ' 1. Convert to a FILETIME
  ' 2. Convert to local time
  ' 3. Convert to a SYSTEMTIME
  Call SystemTimeToFileTime(oSystemTime, oUtcFileTime)
  Call FileTimeToLocalFileTime(oUtcFileTime, oLocalFileTime)
  Call FileTimeToSystemTime(oLocalFileTime, oSystemTime)

  ' Convert to a Date
  LOCALTIME = SystemTimeToDate(oSystemTime)
End Function

'===============================================================================
' Convert a Date to a SYSTEMTIME
'===============================================================================
Private Function DateToSystemTime(Value As Date) As SYSTEMTIME
  With DateToSystemTime
    .Year = Year(Value)
    .Month = Month(Value)
    .Day = Day(Value)
    .Hour = Hour(Value)
    .Minute = Minute(Value)
    .Second = Second(Value)
  End With
End Function

'===============================================================================
' Convert a SYSTEMTIME to a Date
'===============================================================================
Private Function SystemTimeToDate(Value As SYSTEMTIME) As Date
  With Value
    SystemTimeToDate = _
      DateSerial(.Year, .Month, .Day) + _
      TimeSerial(.Hour, .Minute, .Second)
  End With
End Function

A: If all you need is the current time, you can do this with GetSystemTime, which involves fewer Win32 calls. It gives you a time struct, with millisecond precision, which you can format how you'd like:
Private Declare PtrSafe Sub GetSystemTime Lib "Kernel32" (ByRef lpSystemTime As SYSTEMTIME)

Private Type SYSTEMTIME
  wYear As Integer
  wMonth As Integer
  wDayOfWeek As Integer
  wDay As Integer
  wHour As Integer
  wMinute As Integer
  wSecond As Integer
  wMilliseconds As Integer
End Type

Usage:
Dim nowUtc As SYSTEMTIME
Call GetSystemTime(nowUtc)
' nowUtc is now populated with the current UTC time. Format or convert to Date as needed.

A: Simply, you can use COM Object to achieve UTC Time Information.
Dim dt As Object, utc As Date
Set dt = CreateObject("WbemScripting.SWbemDateTime")
dt.SetVarDate Now
utc = dt.GetVarDate(False)

A: Sigh. The question is about Excel VBA, NOT about "Excel VBA for Windows".
In short, none of the answers, however upvoted they may be, works on a Mac or on Linux (yes, Office, at least Office 2000, runs on Linux too)
So here is my answer. It's predictible it gets zero vote, but truth is not a beauty contest.
For Windows, see the other answers (those that silently assume Windows, demonstrating how programmers create problems by assuming things).
For the Mac, see https://macscripter.net/viewtopic.php?id=41117.
For Linux, see How do I get GMT time in Unix?
Have fun with VBA. Sorry to be so dry, but there's so much approximation going arround, S.O. gets scary now.

A: http://excel.tips.net/Pages/T002185_Automatically_Converting_to_GMT.html
There is a macro on that page with a LocalTimeToUTC method.  Looks like it would do the trick.  Also some formula examples if you wanted to go that route.
Edit - Another link.  http://www.cpearson.com/excel/TimeZoneAndDaylightTime.aspx  This page has several methods for date/time.  Pick your poison.  Either should do the trick, but I feel like the second is prettier.  ;)

A: If you also need to account for daylight saving time, you may find the following code useful:
Option Explicit

'''''''''''''''''''''''''''''''''''''''''''''''''''''
' Windows API Structures
'''''''''''''''''''''''''''''''''''''''''''''''''''''
Private Type SYSTEM_TIME
    wYear As Integer
    wMonth As Integer
    wDayOfWeek As Integer
    wDay As Integer
    wHour As Integer
    wMinute As Integer
    wSecond As Integer
    wMilliseconds As Integer
End Type

Private Type TIME_ZONE_INFORMATION
    Bias As Long
    StandardName(0 To 31) As Integer
    StandardDate As SYSTEM_TIME
    StandardBias As Long
    DaylightName(0 To 31) As Integer
    DaylightDate As SYSTEM_TIME
    DaylightBias As Long
End Type

'''''''''''''''''''''''''''''''''''''''''''''''''''''
' Windows API Imports
'''''''''''''''''''''''''''''''''''''''''''''''''''''
Private Declare Function GetTimeZoneInformation Lib "kernel32" _
    (lpTimeZoneInformation As TIME_ZONE_INFORMATION) As Long

Private Declare Function TzSpecificLocalTimeToSystemTime Lib "kernel32" _
    (lpTimeZoneInformation As TIME_ZONE_INFORMATION, lpLocalTime As SYSTEM_TIME, lpUniversalTime As SYSTEM_TIME) As Integer

Function ToUniversalTime(localTime As Date) As Date
    Dim timeZoneInfo As TIME_ZONE_INFORMATION

    GetTimeZoneInformation timeZoneInfo

    Dim localSystemTime As SYSTEM_TIME
    With localSystemTime
        .wYear = Year(localTime)
        .wMonth = Month(localTime)
        .wDay = Day(localTime)
    End With

    Dim utcSystemTime As SYSTEM_TIME

    If TzSpecificLocalTimeToSystemTime(timeZoneInfo, localSystemTime, utcSystemTime) <> 0 Then
        ToUniversalTime = SystemTimeToVBTime(utcSystemTime)
    Else
        err.Raise 1, "WINAPI", "Windows API call failed"
    End If

End Function

Private Function SystemTimeToVBTime(systemTime As SYSTEM_TIME) As Date
    With systemTime
        SystemTimeToVBTime = DateSerial(.wYear, .wMonth, .wDay) + _
                TimeSerial(.wHour, .wMinute, .wSecond)
    End With
End Function

A: My Access project works with mostly Access tables linked to MS SQL Server tables. It is a DAO project and I was having trouble even getting a SQL sproc with GETUTCDATE() to come back. But following was my solution.
-- Create SQL table with calculated field for UTCDate
CREATE TABLE [dbo].[tblUTCDate](
    [ID] [int] NULL,
    [UTCDate]  AS (getutcdate())
) ON [PRIMARY]
GO

Create an Access table, dbo_tblUTCDate,  linked via ODBC to the SQL table tblUTCDate.
Create an Access query to select from the Access table. I called it qryUTCDate.
SELECT dbo_tblUTCDate.UTCDate FROM dbo_tblUTCDate

In VBA:
Dim db as DAO.database, rs AS Recordset
Set rs = db.OpenRecordset("qryUTCDate")
Debug.Print CStr(rs!UTCDATE)
rs.Close
Set rs = Nothing
db.Close
Set db = Nothing


text:
Q: my page load time is so slow after the code I have these two lines of code:
<?php $arr2 = explode(' ',trim($Event["League"]["name"]));$LeagueName1 = $arr2[0]; ?>

and
<img class="league-name" src="/theme/Design/img/leagues/<?php
if(isset($LeagueName1)):?><?=$LeagueName1;?><?php endif; ?>.png"
alt="" />

After I wrote them, my page loading time is slow. Also, I get  bad gateway error when I upload a new png file to the src directory.

A: I would clean this up and add a default "fallback" image as others have said in the comments
<img class="league-name" src="/theme/Design/img/leagues/<?= isset($LeagueName1) ? $LeagueName1 : $defaultImage; ?>.png" />

Alternately you could check first and then to the output
<?php
    $image_src = isset($LeagueName1) ? $LeagueName1 : $defaultImage;
?>

//... other stuff

<img class="league-name" src="/theme/Design/img/leagues/<?= $image_src; ?>.png" />

Without the default image you wind up trying to load this file
  /theme/Design/img/leagues/.png

Which probably does not exist.  You can even omit the image altogether
  <?php if(!empty($LeagueName1)): ?>
       <img class="league-name" src="/theme/Design/img/leagues/<?= $LeagueName1; ?>.png" />
  <?php endif; ?>

That all depends on what you want to do...
If you notice I changed this to empty.  Empty doesn't care if it's set or not, but it will save you in the case that $LeagueName1 = '' which is set, but would put you right back where you started.  Just don't use 0 for the file name such as 0.png .. lol


text:
Q: Difference of fct_reorder and reorder This is an exmaple of fct_reorder
boxplot(Sepal.Width ~ fct_reorder(Species, Sepal.Width, .desc = TRUE), data = iris)

This code is identical with boxplot(Sepal.Width ~ reorder(Species, -Sepal.Width), data = iris)
What is the better point  fct_reorder() than reorder()?

A: The two functions are very similar, but have a few differences:

*

*reorder() works with atomic vectors and defaults to using mean().

*fct_reorder() only works with factors (or character vectors) and defaults to using median()
Example:
library(forcats)

x <-  1:10
xf <- factor(1:10)
y <-  10:1

reorder(x, y)
#>  [1] 1  2  3  4  5  6  7  8  9  10
#> attr(,"scores")
#>  1  2  3  4  5  6  7  8  9 10
#> 10  9  8  7  6  5  4  3  2  1
#> Levels: 10 9 8 7 6 5 4 3 2 1

reorder(xf, y)
#>  [1] 1  2  3  4  5  6  7  8  9  10
#> attr(,"scores")
#>  1  2  3  4  5  6  7  8  9 10
#> 10  9  8  7  6  5  4  3  2  1
#> Levels: 10 9 8 7 6 5 4 3 2 1

fct_reorder(x, y)
#> Error: `f` must be a factor (or character vector).

fct_reorder(xf, y)
#>  [1] 1  2  3  4  5  6  7  8  9  10
#> Levels: 10 9 8 7 6 5 4 3 2 1

Created on 2022-01-07 by the reprex package (v2.0.1)


text:
Q: How can I align divs correctly to fit page width without overflow? Okay so I am playing around with flex box, I have created this simple layout of divs but I am evidently formatting them wrong.
I have put a div at the top for 100% so you can compare where the divs end.

Is there a way to align the divs to fit the page?
I thought that simply adding some % width statements I could easily fill the page however since I'm using margins for the divs it doesn't add up. See codepen here and snippet below:

.container {
  display: flex;
  flex-direction: row;
  flex-wrap: wrap;
}

.myBox {
  border: 0.5px solid black;
  margin: 5px;
  padding: 10px;
}

.headerTitle {
  width: 100%;
}

.bottomLeft {
  width: 29%;
}

.bottomRight {
  width: 100%;
}

.wrapBottomRight {
  width: 37%;
  display: flex;
  flex-direction: row;
  flex-wrap: wrap;
}

 HELLO THERE

 Title

 Some shit

 Title

 Some shit

 Title

 Some shit

 Title

 Some shit

A: When using a wrapping flexbox all factors that contributes to the width of the flex items relative to the flexbox must be considered - so margins and borders must be taken into account:

*

*remove default body margin

*use border-box to include padding and border in width

*Use width: calc(33.33% - 10px) for the mybox and wrapBottomRight elements

See demo below:

body {
  margin: 0;
}

* {
  box-sizing: border-box;
}

.container {
  display: flex;
  flex-direction: row;
  flex-wrap: wrap;
}

.myBox {
  width: calc(33.33% - 10px); /* added*/
  border: 0.5px solid black;
  margin: 5px;
  padding: 10px;
}

.headerTitle {
  width: 100%;
}

.bottomLeft {
  /* width: 29%; */
}

.bottomRight {
  width: 100%;
}

.wrapBottomRight {
  width: calc(33.33% - 10px); /* added */
  display: flex;
  flex-direction: row;
  flex-wrap: wrap;
}

 HELLO THERE

 Title

 Some shit

 Title

 Some shit

 Title

 Some shit

 Title

 Some shit

A: So you will likely want to tweak the widths and heights of the different divs, but the layout you are after is quite easy with flexbox and justify-content: space-between;. In order to achieve this I needed to add one more wrapper .bottomContainer and remove the flex-wrap: wrap;. Check out the flex-direction: column: where you need boxes to flow vertically.
Everyone's favorite flexbox resource: https://css-tricks.com/snippets/css/a-guide-to-flexbox/

* {
  box-sizing: border-box;
}
.container {
  display: flex;
  flex-direction: column;
  margin: 5px;
}

.bottomContainer {
  display: flex;
  justify-content: space-between;
}

.myBox {
  border: 1px solid black;
  padding: 10px;
}

.headerTitle {
  margin-bottom: 10px;
}

.bottomLeft {
  width: 30%;
}

.bottomRight {
  height: 48%;
}

.wrapBottomRight {
  width: 37%;
  display: flex;
  flex-direction: column;
  justify-content: space-between;
}

 HELLO THERE

 Title

 Some shit

 Title

 Some shit

 Title

 Some shit

 Title

 Some shit

A: Hope this helps!

.container {
  display: flex;
  flex-direction: row;
  flex-wrap: wrap;
}

.myBox {
  border: 0.5px solid black;
  margin: 5px;
  padding: 10px;
  width: 50%
}

.headerTitle {
  width: 100%;
}

.bottomLeft {
  width: 20%;
}

.bottomRight {
  width: 20%;
}

.wrapBottomRight {
  display: flex;
  flex-direction: row;
  flex-wrap: wrap;
  width: 20%;
}

 HELLO THERE

 Title

 Some shit

 Title

 Some shit

 Title

 Some shit

 Title

 Some shit

Happy Coding!


text:
Q: Obtain string from JSON Object I have to following response from a server: page:{"result":"ok","id_photo":36782710}.And I'm trying to obtain the result from there by doing this:
String r=page.toString();
JSONArray jArray = new JSONArray(r);
JSONObject jsdata = r.getJSONObject(0);

String result = jsdata.getString("result");
System.out.println("Raspunsul de la server este:" +result);

But I get the following error:
WARN/System.err(30452): org.json.JSONException: Value {"result":"ok","id_photo":36782710} of type org.json.JSONObject cannot be converted to JSONArray
at org.json.JSON.typeMismatch(JSON.java:107)
at org.json.JSONArray.<init>(JSONArray.java:91)
at org.json.JSONArray.<init>(JSONArray.java:103)
at com.Contest.DialogExampleActivity.executeMultiPartPost(DialogExampleActivity.java:131)
at com.Contest.DialogExampleActivity.btnSend_onClick(DialogExampleActivity.java:88)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:507)
at android.view.View$1.onClick(View.java:2157)
at android.view.View.performClick(View.java:2534)
at android.view.View$PerformClick.run(View.java:9210)
at android.os.Handler.handleCallback(Handler.java:587)
at android.os.Handler.dispatchMessage(Handler.java:92)
at android.os.Looper.loop(Looper.java:123)
at android.app.ActivityThread.main(ActivityThread.java:3701)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:507)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:862)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:620)
at dalvik.system.NativeStart.main(Native Method

Anyone any idea?

A: Try instantiating it as a JSONObject instead as the data your a parsing is not an array but a object.
JSONObject json = new JSONObject(response);
String result = json.getString("result");

A: As madsleejensen said, it should be treated as JSONObject not JSONArray, and for future references, simple advice to differ when to use the right type is: JSONObject is covered by {} and JSONArray covered by [].

A: try this:
http://www.androidcompetencycenter.com/2009/10/json-parsing-in-android/


text:
Q: difference -in "Create databse" and "create database if not exists" What is the actual difference between "CREATE DATABASE database_name" and "CREATE DATABASE IF NOT EXISTS database_name"?

A: CREATE DATABASE IF NOT EXISTS database_name will execute the CREATE DATABASE database_name only if the database_name does not already exist.
If the database_name does not exit, both queries will do the same job, that is they create the database_name.
If the database_name exits, CREATE DATABASE database_name will return an error similar to "the database 'database_name' already exists", while CREATE DATABASE IF NOT EXISTS database_name will not return an error (it simply does nothing).
When you write a script (let's say you create the database, then create tables, then insert some data), you don't want the execution to stop just because the database exits, so you use the second query.

A: only one thing:

An error occurs if the database exists and you did not specify IF NOT
  EXISTS.

https://dev.mysql.com/doc/refman/5.5/en/create-database.html
so basically for : error management.


text:
Q: Android: ListViews inside Gallery - how to get scrolling, clicking and swiping like in GTalk? I am writing an Android application, and I use ListViews inside a Gallery. The ListViews represent chat windows. I would really like to be able to swipe between the chat windows in the Gallery, while also being able to scroll in the ListView or click single messages.
While searching, I found a guy here on Stackoverflow that was kind enough to provide his solution to this problem:
Android - ListView inside Gallery makes the scrolling not Smooth
His BetterGallery almost works out for me. Clicking a list item works and scrolling the list view works. I currently have two issues to iron out with this implementation:
1)  When swiping in the gallery, the movement is not smooth and it is not always certain which List View it will end up displaying.
2)  You can both swipe and scroll at the same time in the same finger movement by e.g. moving your finger diagonally.
As a note to point 2: The behavior I am looking for is something similar to the chat windows that you can find in GTalk. In GTalk, you can either do scrolling inside a chat, or swiping between different chats, in one movement. That means if you start scrolling, moving your finger from side to side will not swipe. Similarly, starting a swipe will block scrolling until you release the finger and start a new gesture.
Has anyone achieved something similar to how it works in GTalk?
Best wishes!

A: I had have the same problem. And the solution is less than simple.

*

*
*

*Set the listview to be not focusable in touch mode.

listView.setFocusableInTouchMode(false);

*

*If you need focus, call it from onItemSelected listener.

2. - Use OnInterceptTouchEvent to get Touch Events from your child. And make some modification in onScroll and onTouchEvent

    OnItemSelectedListener mOnItemSelected = new OnItemSelectedListener()
            {
                @Override
                public void onItemSelected(AdapterView parent, View view,
                        int position, long id)
                {
                  view.requestFocusFromTouch();
                }
                @Override
                public void onNothingSelected(AdapterView parent)
                {
                }
            };

    @Override
    public boolean onInterceptTouchEvent(MotionEvent ev) {
        onTouchEvent(ev);
        return scrollingHorizontally;
    }

@Override
public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
    if(Math.abs(distanceX)>Math.abs(distanceY) || scrollingHorizontally == true){
        scrollingHorizontally = true;
        super.onScroll(e1, e2, distanceX, distanceY);
    }
    return scrollingHorizontally;
}

@Override
public boolean onTouchEvent(MotionEvent event) {
    switch(event.getAction()) {
    case MotionEvent.ACTION_UP:
    case MotionEvent.ACTION_CANCEL:
        scrollingHorizontally = false;
        break;
    default:
            break;
    }
    super.onTouchEvent(event);
    return scrollingHorizontally;
}


text:
Q: CSS Modal Popup with optional JavaScript How to create a CSS based modal popup with optional JavaScript? The solution should be mostly CSS based. I looked at some of the CSS only solutions, and they change the page URL. This question is intended to provide alternatives. For example, it's possible to create a CSS based modal popup with the :active and :focus selectors. It's also necessary to use the object tag for nesting anchors. A solution is posted below.

A: This solution works by using the :active, :focus css selectors to show the modal. To hide the modal, focus is transferred to a different anchor from the one which triggered it. object tag is used to nest anchors. JavaScript is optional, but preferred, for best operation.

document.addEventListener('DOMContentLoaded', e => Array.prototype.forEach.call(document.getElementsByClassName('no-drag'), l => l.addEventListener('dragstart', e => e.preventDefault())))
body {
  background: #dfd;
}
.btn {
  display: inline-block;
  box-sizing: border-box;
  margin: .2em;
  border: .2em solid;
  border-radius: .6em;
  padding: .3em;
  text-align: center;
  text-decoration: none;
  font-family: 'MS Shell Dlg 2', Arial;
  cursor: pointer;
}
.btn-green {
  border-color: #9b9;
  background-color: #686;
  color: #bdb;
}
.btn-green:hover {
  border-color: #9cb;
  background-color: #698;
  color: #bed;
}
.modal-container {
  visibility: hidden;
  position: fixed;
  top: 0;
  right: 0;
  bottom: 0;
  left: 0;
  background: rgba(0, 0, 0, .8);
  z-index: 1;
  cursor: default;
  -webkit-transition: visibility .5s;
  transition: visibility .5s;
}
.modal {
  position: absolute;
  top: 50%;
  right: 50%;
  bottom: 50%;
  left: 50%;
  border: .2em solid #9b9;
  border-radius: .6em;
  background-color: rgba(102, 136, 102, .8);
  font-size: 1rem;
  line-height: 1em;
  overflow: hidden;
  -webkit-transition: top .5s, right .5s, bottom .5s, left .5s;
  transition: top .5s, right .5s, bottom .5s, left .5s;
}
.modal-header, .modal-footer {
  position: absolute;
  right: 1em;
  left: 1em;
  height: 2em;
  border-radius: .3em;
  background-color: rgba(102, 136, 102, .8);
  padding: 0 .2em;
  overflow: hidden;
}
.modal-header {
  top: 1em;
}
.modal-footer {
  bottom: 1em;
}
.modal-text, .modal-btn {
  position: absolute;
  display: block;
  top: 0;
  bottom: 0;
  margin: .2em;
  color: #bdb;
}
.modal-text {
  left: 0;
  padding: .1em .3em;
  line-height: 1.2em;
}
.modal-btn {
  right: 0;
  border-radius: .6em;
  padding: .1em .6em;
  background-color: rgba(85, 119, 85, .8);
  line-height: 1.3em;
  text-decoration: none;
}
.modal-btn:hover, .modal-btn:active, .modal-btn:focus {
  background-color: rgba(119, 153, 136, .8);
  color: #ced;
}
.modal-body {
  position: absolute;
  top: 4em;
  right: 1em;
  bottom: 4em;
  left: 1em;
  margin-right: .5em;
  padding: 0 .5em;
  text-align: justify;
  overflow: auto;
}
.modal-body:after {
  content: "";
  display: block;
  height: .5em;
}
.modal-show:active > .modal-container, .modal-show:focus > .modal-container {
  visibility: visible;
}
.modal-show:active > .modal-container > .modal, .modal-show:focus > .modal-container > .modal {
  top: 0;
  right: 0;
  bottom: 0;
  left: 0;
}
@media (min-width: 320px) {
  /* Extra Extra Small */
  .modal-show:active > .modal-container > .modal, .modal-show:focus > .modal-container > .modal {
    top: 0;
    right: 0;
    bottom: 0;
    left: 0;
  }
}
@media (min-width: 480px) {
  /* Extra Small */
  .modal-show:active > .modal-container > .modal, .modal-show:focus > .modal-container > .modal {
    top: 0;
    right: 0;
    bottom: 0;
    left: 0;
  }
}
@media (min-width: 576px) {
  /* Small */
  .modal-show:active > .modal-container > .modal, .modal-show:focus > .modal-container > .modal {
    top: .5em;
    right: .5em;
    bottom: .5em;
    left: .5em;
  }
}
@media (min-width: 768px) {
  /* Medium */
  .modal-show:active > .modal-container > .modal, .modal-show:focus > .modal-container > .modal {
    top: 1.5em;
    right: 1.5em;
    bottom: 1.5em;
    left: 1.5em;
  }
}
@media (min-width: 992px) {
  /* Large */
  .modal-show:active > .modal-container > .modal, .modal-show:focus > .modal-container > .modal {
    top: 3em;
    right: 3em;
    bottom: 3em;
    left: 3em;
  }
}
@media (min-width: 1200px) {
  /* Extra Large */
  .modal-show:active > .modal-container > .modal, .modal-show:focus > .modal-container > .modal {
    top: 6em;
    right: 6em;
    bottom: 6em;
    left: 6em;
  }
}

  Modal

      <object class="modal-header">

Modal Dialog

        x
      </object>

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Praesent nec ornare nisi, ac aliquam erat. Vestibulum rhoncus, ipsum vitae lobortis pellentesque, odio lorem convallis lorem, nec malesuada dolor magna vitae metus. Duis varius mi vel nunc lobortis blandit. Duis eu posuere tortor. Etiam ac arcu finibus, suscipit sem nec, pulvinar enim. Aliquam pellentesque arcu nec sem iaculis, vitae convallis purus imperdiet. Aenean et dolor a nulla placerat facilisis eget non arcu.

Duis venenatis nulla nec augue vulputate, vel dapibus dui accumsan. Curabitur quis purus vitae lectus cursus fermentum at vehicula turpis. Ut vel facilisis mauris. Duis accumsan, enim sed egestas elementum, orci mi mollis tellus, vel luctus tortor augue gravida est. Nulla at lorem sed elit facilisis interdum. Duis mattis non sapien at laoreet. Sed suscipit elit ut tellus laoreet, sit amet gravida nunc mollis. Nam ullamcorper est quis facilisis scelerisque. Duis nulla diam, blandit sed commodo quis, blandit id felis. Nam eleifend elit et orci aliquet gravida. Donec at commodo diam. Proin vehicula auctor gravida.

Vivamus finibus tempus lobortis. Integer convallis neque non ex placerat porta. Fusce a purus maximus, sollicitudin libero eu, vulputate nibh. Nullam pulvinar enim et purus tincidunt porta. Mauris diam enim, volutpat quis urna sed, rhoncus convallis ante. Vestibulum mollis metus eu dui elementum varius. Vestibulum sodales massa eget viverra malesuada. Vestibulum eget lacinia nunc.

Donec mattis lobortis lorem ac tempor. Donec iaculis, felis eu imperdiet accumsan, ex neque laoreet velit, vitae egestas felis diam vitae massa. Aenean maximus magna velit, vel mattis tortor dapibus sed. Cras vehicula fringilla nulla, eget mattis nibh. Quisque lacinia convallis massa, a consectetur nibh viverra id. Donec quis mauris vitae mi rhoncus lacinia. Ut metus felis, cursus et risus at, fringilla mattis dui. Vestibulum sollicitudin facilisis hendrerit. Morbi a risus nisl. Donec sed gravida turpis. Nulla hendrerit dui mollis dui accumsan, eget facilisis metus vestibulum. Sed vel molestie eros. Quisque ut felis purus. Donec nec bibendum quam, ac accumsan risus. Donec blandit eu ante sollicitudin rutrum. In vitae iaculis est, ac molestie nunc.

Nunc eu justo id dui ultricies facilisis quis eu tortor. Phasellus eget nulla quis elit fringilla maximus. Suspendisse tortor justo, tempor vel accumsan in, suscipit non leo. Pellentesque non gravida sapien. Sed vel ex vel dui tempor pellentesque a eget elit. Pellentesque gravida ligula quis mollis vestibulum. Quisque a nibh id nibh mollis tincidunt. Proin ex eros, sagittis a tellus vel, auctor rutrum arcu. Integer quam erat, congue non tellus vitae, fermentum suscipit metus. Cras quis mi id ante maximus cursus sit amet ac libero.

      <object class="modal-footer">
        Close
      </object>

A: There is a new HTML element called <dialog>. Its support is quite recent but there is a polyfill.
https://developer.mozilla.org/fr/docs/Web/HTML/Element/dialog
Here is an example for you:
<dialog id="my-dialog">

Hello from my dialog

  <button id="hide-button">Hide dialog</button>
</dialog>

<button id="show-button">Show dialog</button>


text:
Q: Why does 'Run as administrator' change (sometimes) batch file's current directory? I have a batch file that is in the same directory as the file I want to xcopy. But for some reason the file is not being found.
I thought that current directory was always where the batch file was located.
I run batch file as administrator. This occurs on a Windows 7 64-bit desktop computer.
Batch file:
@ECHO OFF
XCOPY /y "File1.txt" "File2.txt"
PAUSE

Error:
File not found - File1.txt
0 File(s) copied

A: Which directory is current working directory on starting a batch file with context menu item Run as administrator depends on User Account Control (UAC) setting for the current user.
This can be demonstrated with following small batch file C:\Temp\Test.bat:
@echo Current directory is: %CD%
@pause

With having selected in User Account Control Settings

Default - Notify me only when programs try to make changes to my computer

*

*Don't notify me when I make changes to Windows settings

and using Run as administrator, Windows uses registry key
HKEY_CLASSES_ROOT\batfile\shell\runasuser\command

This registry key does not contain a default string for executing the batch file. Instead there is the string value DelegateExecute with the CLSID {ea72d00e-4960-42fa-ba92-7792a7944c1d}.
The result is opening a dialog window with title User Account Control and text:

Do you want to allow the following program to make changes to this computer?
Program name: Windows Command Processor
  Verified publisher: Microsoft Windows

After confirmation by the user, Windows opens temporarily a new user session like when using on command line RunAs.
In this new user session the current working directory is %SystemRoot%\System32 on executing now the command defined in Windows registry with default string of key
HKEY_CLASSES_ROOT\batfile\shell\runas\command

which is:
%SystemRoot%\System32\cmd.exe /C "%1" %*

Therefore a console window is opened with title C:\Windows\System32\cmd.exe and the 2 lines:
Current directory is: C:\Windows\System32
Press any key to continue . . .

After hitting any key, batch execution finishes which results in closing cmd.exe which results in closing the user session.

But with having selected in User Account Control Settings

Never notify me when

*

*Programs try to install software or make changes to my computer

*I make changes to Windows settings

the behavior is different as the user has already elevated privileges.
Now Windows uses directly the command
%SystemRoot%\System32\cmd.exe /C "%1" %*

according to default string of key
HKEY_CLASSES_ROOT\batfile\shell\runas\command

in current user session.
The result is opening a console window also with title C:\Windows\System32\cmd.exe, but displayed in window is:
Current directory is: C:\Temp
Press any key to continue . . .

The current working directory of the parent process (Windows Explorer as desktop) is used for executing of the batch file because no switch to a different user session was necessary in this case.

PA has posted already 2 possible solutions in his answer which I replicate here with a small improvement (pushd with directory in double quotes) and with adding a third one.

*

*Change current directory to directory of batch file using pushd and popd:
pushd "%~dp0"
%SystemRoot%\System32\xcopy.exe "File1.txt" "File2.txt" /Y
popd

This works also for UNC paths. Run in a command prompt window pushd /? for an explanation why this also works for UNC paths.

*Use directory of batch file in source and destination specifications:
%SystemRoot%\System32\xcopy.exe "%~dp0File1.txt" "%~dp0File2.txt" /Y

*Change working directory to directory of batch file using cd:
cd /D "%~dp0"
%SystemRoot%\System32\xcopy.exe "File1.txt" "File2.txt" /Y

This does not work for UNC paths because command interpreter cmd does not support a UNC path as current directory by default, see for example CMD does not support UNC paths as current directories for details.

A: The error message is very self explanatory. The file file1.txt is not found.
Because the file name does not include an absolute path, the system tries to find it on the current directory. Your current directory does not contain this file.
Your misconception is that the current directory is not the directory that contains the bat file. Those are two unrelated concepts.
You can easily check by adding this two commands in your bat file
echo BAT directory is %~dp0
echo Current directory  is %CD%

you can notice they are different, and that there is a subtle difference in the way the last backslash is appended or not.
So, there are esentially two ways to cope with this problem

*

*either change the current directory to match the expected one
pushd %~dp0
XCOPY /y "File1.txt" "File2.txt"
popd

*or specify the full path in the command
XCOPY /y "%~dp0File1.txt" "%~dp0File2.txt"

A: For the sake of completeness and obscurity, I add another workaround, confirmed as working under Windows 8.1 and expected to work elsewhere, as it relies on documented functionality:
You can change the runas command definition keys
HKEY_CLASSES_ROOT\batfile\shell\runas\command and
HKEY_CLASSES_ROOT\cmdfile\shell\runas\command into
%SystemRoot%\System32\cmd.exe /S /C "(for %%G in (%1) do cd /D "%%~dpG") & "%1"" %*

Which results in the bat or cmd file starting in its containing directory when started using the runas verb, respectively the "Run as Administrator" menu entry.
What the additions to the original command exactly do:

*

*cmd /S strips away first and last (double) quote in command string after /C

*for %%G in (%1) do enumerates its single entry, the %1 argument,
making it available for expansion as %%G in the loop body; the letter is arbitrary but some may be "reserved"

*%%~dpG expands to the drive and path of %%G, the ~ tilde stripping away quotes if present, which is why we add them back explicitly

*cd /D changes both the drive and directory to its argument, and finally

*& runs the second command "%1" %* regardless of success of the first one.

You can use pushd which will even support UNC paths, but a stray popd would land any script in the system32 directory, not a behavior I would be fond of.
It should be possible to do this for the exefile entry as well, but frankly, I'd rather live with the inconsistency than to attempt this on my system, as any error there could break a lot.
Enjoy defeating the security mechanics of your operating system :)


text:
Q: Stuck while figuring out the Bookings model for my app I'm creating a ticket booking app as my sample project using Ruby on Rails 4.1. Three are three models - Events, Tickets and Bookings. Events have many tickets and bookings. Tickets have many bookings and they belong to events. Bookings belongs to events and tickets.
Now, I am modelling the app closely along the lines of Eventbrite. In particular, the ticket booking pages will look like this https://www.eventbrite.com/e/bacon-and-beer-classic-july-26-2014-tickets-11729347795?err=29
Here's where I'm stuck. I initially figured that the Bookings show page will list the ticket tiers with a dropdown to select the number of tickets. Then, the user upon clicking the pay button will be redirected to the new Bookings page where he/she will complete the order.
However, I can't figure out how to carry that dropdown data to the bookings page. That's one issue. The second issue is to figure out a way to calculate the total amount when the user picks more than one ticket and display that in the new bookings page for checkout.
Sorry if this question sounds too dumb. I'm just wondering if this could be achieved using Ruby/Rails methods and helpers or if javascript is needed to get this done.


text:
Q: test api controller that returns json response In order to test an API controller in a Symfony2 project  that returns json response, I tried to generate a route of the action like here:
$client->getContainer()->get('router')->generate('/api/register/emailverification/', array('email' => 'email@gmail.com'), true)
$response= $client->getResponse();
$this->assertEquals(200, $response);`

But the response returns null. I don't know if have to do a specific test for this type of response like using guzzle...

A: In tests one shouldn't "generate" routes paths, they must be hard-coded:
$client = $this->createClient();
$client->request('GET', '/api/register/emailverification/email@gmail.com');
$this->assertTrue($client->getResponse()->isOk());

But if you want to test json, you can do:
$this->assertJson($client->getResponse()->getContent());

You can find additional PHPunit helpers in the rest extra bundle.

A: I believe you should try:
$controllerResponse = $client->getContainer()->get('router')->generate('_validation_email', array('email' => 'email@gmail.com'), true)
$response= $controllerResponse->getResponse();
$this->assertEquals(200, $response);


text:
Q: how to get nested json data at column level in extjs I am very new to extjs, i have strucked hear about one day, please any one do help.
How do I get nested json data at column level in extjs
For normal columns its getting exactly, but when it cums to array column at col6 was strucked.
this is how my model looks like
json data like:
[
       {
       "col1" : "abc",
       "col2" : "aasd",
       "col3" : "aasd",
       "col4" : "sad",
       "col5" : "sad",
       "col6" : [
                   {
                      "inncol1": "laksd",
                      "inncol2": "laksd"
                   },
                   {
                      "inncol1": "laksd",
                      "inncol2": "laksd"
                   }
                   ]
       },

        {
       "col1" : "abc",
       "col2" : "aasd",
       "col3" : "aasd",
       "col4" : "sad",
       "col5" : "sad",
       "col6" : [
                   {
                      "inncol1": "laksd",
                      "inncol2": "laksd"
                   },
                   {
                      "inncol1": "laksd",
                      "inncol2": "laksd"
                   }
                   ]
       }

    ]

Expecting outpoot :
====================================================================
**col1**    **col2**    **col3**    **col4**    **col5**                **col6  **
                                            ========================
                                             **inncol1**    **inncol2**
====================================================================
abc     jasd    asjd    aasd    asdjk        asdjk        asdas
                                             asdas         asdd
=====================================================================
asdas   sada    asdas   sdf     asdas       asdas           sdaas
                                            asds            daass
======================================================================

Model is :
 Ext.define('MONTHWISEMODEL',
                            {
                                extend  : 'Ext.data.Model',
                                fields  :
                                [
                                     {  name: 'col1'                }
                                    ,{  name: 'col2'                }
                                    ,{  name: 'col3'                }
                                    ,{  name: 'col4'                }
                                    ,{  name: 'col5'                }
                                    ,{  name: 'col6'                }
                                ]
                            });

Store is :
getStore : function()
            {
                var proxy = {
                         type        : 'ajax'
                        ,url         : myurl
                        ,reader      : 'jsonreader'

                return   Ext.create('Ext.data.GridStore',
                            {
                                 model      : 'MONTHWISEMODEL'
                                ,autoLoad   : false
                                ,autoDestroy: false
                                ,proxy      : proxy
                            });
            }
    }

Grid is :
getMonthlyReportGrid : function()
    {

        var me = this;
        var store = me.getStore();
        var reportsGrid =   Ext.create('Ext.custom.grid.Panel',
        {
             store          : store
            ,id             : 'monthlyGridData'
            ,overflowX      : 'scroll'
            ,overflowY      : 'scroll'
            ,forceFit       : false
            ,height         : 450
            ,cls            : 'pr-data-grid'
            ,columns        :
                [
                     {  text : 'col1'                               ,dataIndex : 'col1'             }
                    ,{  text : 'col2'                               ,dataIndex : 'col2'             }
                    ,{  text : 'col3'                               ,dataIndex : 'col3'             }
                    ,{  text : 'col4'                               ,dataIndex : 'col4'                 }
                    ,{  text : 'col5'                               ,dataIndex : 'col5'             }
                    ,{  text : 'col6'                                , columns: [
                                                                                ,{ text : 'inncol1'       ,dataIndex : 'inncol1'            }
                                                                                ,{ text : 'inncol2'       ,dataIndex : 'inncol2'        }
                                                                                ] }
                ]

        });
        return reportsGrid;
    }

A: You can use renderer method of Ext.grid.column.Column class, which can be used as a converter where you return the value you wish. Here's the FIDDLE