text:
Q: How to write if condition inside json+ajax + table I am facing the issue in writing the if condition in the td part
var output = "
" +
                "
" +
                "
" +
                    "Report Date	" +
                    "Group Name	" +
                    "Group Status	" +
                    "Plan Name	" +
                    "Plan Status	" +
                    "DC	" +
                    "CRA	" +
                    "Suspended	" +
                    "Year End	" +
                    "Effective	" +
                    "Run Out	" +
                    "Employees	" +
                    "Dependents	" +
                "
" +
                "
" +
                "
";
            for (var value in (data.queryset)) {

            output +=
            "
" +
                "" + data.queryset[value].generated_date + '	' +
                '' + data.queryset[value].group_name + '	' +
                '' + data.queryset[value].group_status + '	' +
                '' + data.queryset[value].plan_name + '	' +
                '' + data.queryset[value].plan_status + '	' +
                {#'' + data.queryset[value].debit_card + '	' +#}

                '' + if (data.queryset.debit_card === 1)
                {None}else if (data.queryset.debit_card === 2)
                {Rx } else (data.queryset.debit_card === 3)
                {Full} + '	' +

                '' + data.queryset[value].cra + '	' +
                '' + data.queryset[value].claims_suspended + '	' +
                '' + data.queryset[value].year_end + '	' +
                '' + data.queryset[value].effective_date + '	' +
                '' + data.queryset[value].termination_run_out_days + '	' +
                '' + data.queryset[value].count_of_Employees + '	' +
                '' + data.queryset[value].count_of_Dependents + "	" +
            "
";
            }
            output += "

";

            displayResources.html(output);

            displayResources.find('#report').DataTable(options);

            setTimeout(() => {
                $('#main-content').show();
                _this.html('Generate Report')
            }, 2000);
        },
        error: function(error){

A: Please check this :
var output = "
" +
                "
" +
                "
" +
                    "Report Date	" +
                    "Group Name	" +
                    "Group Status	" +
                    "Plan Name	" +
                    "Plan Status	" +
                    "DC	" +
                    "CRA	" +
                    "Suspended	" +
                    "Year End	" +
                    "Effective	" +
                    "Run Out	" +
                    "Employees	" +
                    "Dependents	" +
                "
" +
                "
" +
                "
";
            for (var value in (data.queryset)) {

                if (data.queryset.debit_card === 1){
                    var debt_crd = 'None';
                }else if (data.queryset.debit_card === 2){
                    var debt_crd = 'Rx';
                }else if(data.queryset.debit_card === 3){
                    var debt_crd = 'Full';
                }

            output +=
            "
" +
                "" + data.queryset[value].generated_date + '	' +
                '' + data.queryset[value].group_name + '	' +
                '' + data.queryset[value].group_status + '	' +
                '' + data.queryset[value].plan_name + '	' +
                '' + data.queryset[value].plan_status + '	' +
                '' + debt_crd + '	' +
                '' + data.queryset[value].cra + '	' +
                '' + data.queryset[value].claims_suspended + '	' +
                '' + data.queryset[value].year_end + '	' +
                '' + data.queryset[value].effective_date + '	' +
                '' + data.queryset[value].termination_run_out_days + '	' +
                '' + data.queryset[value].count_of_Employees + '	' +
                '' + data.queryset[value].count_of_Dependents + "	" +
            "
";
            }
            output += "

";

            displayResources.html(output);

            displayResources.find('#report').DataTable(options);

            setTimeout(() => {
                $('#main-content').show();
                _this.html('Generate Report')
            }, 2000);
        },
        error: function(error){


text:
Q: Searching strings in a single column in a datatable jquery I'm using jquery datatable, and I want to search the rows where I can find some words in a single column.
For example, I want to find the rows which contain an array of words.

A: One way to do this is to put an input element in the column you want to search. Then you need to add a listener to this input that will call a couple DataTables methods. My implementation looks something like this:
$("#searchInput").on('keyup change', function (e) {
    if(e.which == 13) {
        table
            .column($(this).parent().index() + ':visible')
            .search(this.value)
            .draw();
    }
});

The e.which == 13 makes the search only occur when enter is pressed. This was my preference, you can do it on any keyup if you prefer.
$(this).parent().index() finds the column number of the  that the input is in.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Objective C callbacks with blocks I have looked at various answers on SO for this but can't quite get my head around how it all actually works.
What I have is a GameEngine that contains touchable elements, what I want is for when an element is touched it fires off a "I have been touched" event that the GameEngine listens for and deals with appropriately.
In C# I'd do this with delegates/events but can't seem to find a decent obj c equivalent that uses blocks. - I want to use Blocks as it more akin to anonymous functions in C# which I am used to.
In C# I'd simply do something like the following, in objective c it seems I need to write a page of code to get the same thing working?
touchableObject.touched += (o) => { handler code yay }

Edit based on Driis' answer:
Declaration
typedef void (^CircleTouchedHandler)(id parameter);

@interface CircleView : UIView{
}

@property CircleTouchedHandler Touched;

How to call it and pass myself as a parameter?
[self Touched(self)]; // this doesnt work

A: In Objective-C, that would look something like:
touchableObject.touched = ^(id o) { /* handler code */ };

Assuming touched is a property of an appropiate block type. If you re-use a block type (think of Func in C#), it makes sense to typedef it, since a block declaration in ObjC tends to become difficult to read very quickly.
The block syntax gets some time to get used to in Objective-C when you are coming from another language with slightly more elegant block/lambda syntax. To learn and as a reference, see this previous answer, which has helped me a lot.
To typedef a type for touched, you would use something like:
typedef void (^Handler)(id parameter);

Then simply declare the touched property as type handler.


text:
Q: Scrapy 0 pages crawled but no visible issue? I used Portia to create a spider and then downloaded it as scrapy project. The spider runs fine but it says in the logs: Scrapy Crawled 0 pages (at 0 pages/min) and also nothing get's saved. However, it also shows all the pages crawled with 200 response, then shows the bytes of data at the end..
Spider Code
from __future__ import absolute_import

from scrapy import Request
from scrapy.linkextractors import LinkExtractor
from scrapy.loader import ItemLoader
from scrapy.loader.processors import Identity
from scrapy.spiders import Rule

from ..utils.spiders import BasePortiaSpider
from ..utils.starturls import FeedGenerator, FragmentGenerator
from ..utils.processors import Item, Field, Text, Number, Price, Date, Url, Image, Regex
from ..items import PortiaItem, AllProductsBooksToScrapeSandboxItem

class BooksToscrape(BasePortiaSpider):
    name = "books.toscrape.com"
    allowed_domains = ['books.toscrape.com']
    start_urls = [{'fragments': [{'valid': True,
                                  'type': 'fixed',
                                  'value': 'http://books.toscrape.com/catalogue/page-'},
                                 {'valid': True,
                                  'type': 'range',
                                  'value': '1-50'},
                                 {'valid': True,
                                  'type': 'fixed',
                                  'value': '.html'}],
                   'type': 'generated',
                   'url': 'http://books.toscrape.com/catalogue/page-[1-50].html'}]
    rules = [
        Rule(
            LinkExtractor(
                allow=(),
                deny=('.*')
            ),
            callback='parse_item',
            follow=True
        )
    ]
    items = [
        [
            Item(
                AllProductsBooksToScrapeSandboxItem, None, '.product_pod', [
                    Field(
                        'title', 'h3 > a::attr(title)', []), Field(
                        'price', '.product_price > .price_color *::text', [])])]]

Pipeline Code
I added openSpider and closeSpider functions to write the items to json lines upon crawling and I think it works because jl file gets created.
# -*- coding: utf-8 -*-

# Define your item pipelines here
#
# Don't forget to add your pipeline to the ITEM_PIPELINES setting
# See: https://doc.scrapy.org/en/latest/topics/item-pipeline.html
import json

class TesterPipeline(object):

    def open_spider(self, spider):
        self.file = open('items.jl', 'w')

    def close_spider(self, spider):
        self.file.close()

    def process_item(self, item, spider):
        line = json.dumps(dict(item)) + "\n"
        self.file.write(line)
        return item

Settings Code
Enabled pipeline in settings too for pipeline to work.
# -*- coding: utf-8 -*-

# Scrapy settings for Tester project
#
# For simplicity, this file contains only settings considered important or
# commonly used. You can find more settings consulting the documentation:
#
#     https://doc.scrapy.org/en/latest/topics/settings.html
#     https://doc.scrapy.org/en/latest/topics/downloader-middleware.html
#     https://doc.scrapy.org/en/latest/topics/spider-middleware.html

BOT_NAME = 'Tester'

SPIDER_MODULES = ['Tester.spiders']
NEWSPIDER_MODULE = 'Tester.spiders'

# Crawl responsibly by identifying yourself (and your website) on the user-agent
#USER_AGENT = 'Tester (+http://www.yourdomain.com)'

# Obey robots.txt rules
ROBOTSTXT_OBEY = True

# Configure maximum concurrent requests performed by Scrapy (default: 16)
#CONCURRENT_REQUESTS = 32

# Configure a delay for requests for the same website (default: 0)
# See https://doc.scrapy.org/en/latest/topics/settings.html#download-delay
# See also autothrottle settings and docs
#DOWNLOAD_DELAY = 3
# The download delay setting will honor only one of:
#CONCURRENT_REQUESTS_PER_DOMAIN = 16
#CONCURRENT_REQUESTS_PER_IP = 16

# Disable cookies (enabled by default)
#COOKIES_ENABLED = False

# Disable Telnet Console (enabled by default)
#TELNETCONSOLE_ENABLED = False

# Override the default request headers:
#DEFAULT_REQUEST_HEADERS = {
#   'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
#   'Accept-Language': 'en',
#}

# Enable or disable spider middlewares
# See https://doc.scrapy.org/en/latest/topics/spider-middleware.html
#SPIDER_MIDDLEWARES = {
#    'Tester.middlewares.TesterSpiderMiddleware': 543,
#}

# Enable or disable downloader middlewares
# See https://doc.scrapy.org/en/latest/topics/downloader-middleware.html
#DOWNLOADER_MIDDLEWARES = {
#    'Tester.middlewares.TesterDownloaderMiddleware': 543,
#}

# Enable or disable extensions
# See https://doc.scrapy.org/en/latest/topics/extensions.html
#EXTENSIONS = {
#    'scrapy.extensions.telnet.TelnetConsole': None,
#}

# Configure item pipelines
# See https://doc.scrapy.org/en/latest/topics/item-pipeline.html
ITEM_PIPELINES = {
    'Tester.pipelines.TesterPipeline': 300,
}

# Enable and configure the AutoThrottle extension (disabled by default)
# See https://doc.scrapy.org/en/latest/topics/autothrottle.html
#AUTOTHROTTLE_ENABLED = True
# The initial download delay
#AUTOTHROTTLE_START_DELAY = 5
# The maximum download delay to be set in case of high latencies
#AUTOTHROTTLE_MAX_DELAY = 60
# The average number of requests Scrapy should be sending in parallel to
# each remote server
#AUTOTHROTTLE_TARGET_CONCURRENCY = 1.0
# Enable showing throttling stats for every response received:
#AUTOTHROTTLE_DEBUG = False

# Enable and configure HTTP caching (disabled by default)
# See https://doc.scrapy.org/en/latest/topics/downloader-middleware.html#httpcache-middleware-settings
#HTTPCACHE_ENABLED = True
#HTTPCACHE_EXPIRATION_SECS = 0
#HTTPCACHE_DIR = 'httpcache'
#HTTPCACHE_IGNORE_HTTP_CODES = []
#HTTPCACHE_STORAGE = 'scrapy.extensions.httpcache.FilesystemCacheStorage'

When I run the spider, the following log is created:
(scrape) C:\Users\da74\Desktop\tester>scrapy crawl books.toscrape.com
2018-07-24 12:18:15 [scrapy.utils.log] INFO: Scrapy 1.5.0 started (bot: Tester)
2018-07-24 12:18:15 [scrapy.utils.log] INFO: Versions: lxml 4.2.2.0, libxml2 2.9.8, cssselect 1.0.3, parsel 1.4.0, w3lib 1.19.0, Twisted 17.5.0, Python 3.6.6 |Anaconda, Inc.| (default, Jun 28 2018, 11:27:44) [MSC v.1900 64 bit (AMD64)], pyOpenSSL 18.0.0 (OpenSSL 1.0.2o  27 Mar 2018), cryptography 2.2.2, Platform Windows-10-10.0.17134-SP0
2018-07-24 12:18:15 [scrapy.crawler] INFO: Overridden settings: {'BOT_NAME': 'Tester', 'NEWSPIDER_MODULE': 'Tester.spiders', 'ROBOTSTXT_OBEY': True, 'SPIDER_MODULES': ['Tester.spiders']}
2018-07-24 12:18:15 [scrapy.middleware] INFO: Enabled extensions:
['scrapy.extensions.corestats.CoreStats',
 'scrapy.extensions.telnet.TelnetConsole',
 'scrapy.extensions.logstats.LogStats']
2018-07-24 12:18:16 [scrapy.middleware] INFO: Enabled downloader middlewares:
['scrapy.downloadermiddlewares.robotstxt.RobotsTxtMiddleware',
 'scrapy.downloadermiddlewares.httpauth.HttpAuthMiddleware',
 'scrapy.downloadermiddlewares.downloadtimeout.DownloadTimeoutMiddleware',
 'scrapy.downloadermiddlewares.defaultheaders.DefaultHeadersMiddleware',
 'scrapy.downloadermiddlewares.useragent.UserAgentMiddleware',
 'scrapy.downloadermiddlewares.retry.RetryMiddleware',
 'scrapy.downloadermiddlewares.redirect.MetaRefreshMiddleware',
 'scrapy.downloadermiddlewares.httpcompression.HttpCompressionMiddleware',
 'scrapy.downloadermiddlewares.redirect.RedirectMiddleware',
 'scrapy.downloadermiddlewares.cookies.CookiesMiddleware',
 'scrapy.downloadermiddlewares.httpproxy.HttpProxyMiddleware',
 'scrapy.downloadermiddlewares.stats.DownloaderStats']
2018-07-24 12:18:16 [scrapy.middleware] INFO: Enabled spider middlewares:
['scrapy.spidermiddlewares.httperror.HttpErrorMiddleware',
 'scrapy.spidermiddlewares.offsite.OffsiteMiddleware',
 'scrapy.spidermiddlewares.referer.RefererMiddleware',
 'scrapy.spidermiddlewares.urllength.UrlLengthMiddleware',
 'scrapy.spidermiddlewares.depth.DepthMiddleware']
2018-07-24 12:18:16 [scrapy.middleware] INFO: Enabled item pipelines:
['Tester.pipelines.TesterPipeline']
2018-07-24 12:18:16 [scrapy.core.engine] INFO: Spider opened
2018-07-24 12:18:16 [scrapy.extensions.logstats] INFO: Crawled 0 pages (at 0 pages/min), scraped 0 items (at 0 items/min)
2018-07-24 12:18:16 [scrapy.extensions.telnet] DEBUG: Telnet console listening on 127.0.0.1:6023
2018-07-24 12:18:16 [scrapy.core.engine] DEBUG: Crawled (404) <GET http://books.toscrape.com/robots.txt> (referer: None)
2018-07-24 12:18:16 [scrapy.core.engine] DEBUG: Crawled (200) <GET http://books.toscrape.com/catalogue/page-1.html> (referer: None)
2018-07-24 12:18:17 [scrapy.core.engine] DEBUG: Crawled (200) <GET http://books.toscrape.com/catalogue/page-2.html> (referer: None)
2018-07-24 12:18:17 [scrapy.core.engine] DEBUG: Crawled (200) <GET http://books.toscrape.com/catalogue/page-7.html> (referer: None)
2018-07-24 12:18:17 [scrapy.core.engine] DEBUG: Crawled (200) <GET http://books.toscrape.com/catalogue/page-4.html> (referer: None)
2018-07-24 12:18:17 [scrapy.core.engine] DEBUG: Crawled (200) <GET http://books.toscrape.com/catalogue/page-3.html> (referer: None)
2018-07-24 12:18:17 [scrapy.core.engine] DEBUG: Crawled (200) <GET http://books.toscrape.com/catalogue/page-9.html> (referer: None)
2018-07-24 12:18:17 [scrapy.core.engine] DEBUG: Crawled (200) <GET http://books.toscrape.com/catalogue/page-5.html> (referer: None)
2018-07-24 12:18:17 [scrapy.core.engine] DEBUG: Crawled (200) <GET http://books.toscrape.com/catalogue/page-8.html> (referer: None)
2018-07-24 12:18:17 [scrapy.core.engine] DEBUG: Crawled (200) <GET http://books.toscrape.com/catalogue/page-6.html> (referer: None)
2018-07-24 12:18:17 [scrapy.core.engine] DEBUG: Crawled (200) <GET http://books.toscrape.com/catalogue/page-10.html> (referer: None)
2018-07-24 12:18:17 [scrapy.core.engine] DEBUG: Crawled (200) <GET http://books.toscrape.com/catalogue/page-12.html> (referer: None)
2018-07-24 12:18:17 [scrapy.core.engine] DEBUG: Crawled (200) <GET http://books.toscrape.com/catalogue/page-11.html> (referer: None)
2018-07-24 12:18:17 [scrapy.core.engine] DEBUG: Crawled (200) <GET http://books.toscrape.com/catalogue/page-14.html> (referer: None)
2018-07-24 12:18:17 [scrapy.core.engine] DEBUG: Crawled (200) <GET http://books.toscrape.com/catalogue/page-15.html> (referer: None)
2018-07-24 12:18:17 [scrapy.core.engine] DEBUG: Crawled (200) <GET http://books.toscrape.com/catalogue/page-16.html> (referer: None)
2018-07-24 12:18:17 [scrapy.core.engine] DEBUG: Crawled (200) <GET http://books.toscrape.com/catalogue/page-17.html> (referer: None)
2018-07-24 12:18:17 [scrapy.core.engine] DEBUG: Crawled (200) <GET http://books.toscrape.com/catalogue/page-13.html> (referer: None)
2018-07-24 12:18:17 [scrapy.core.engine] DEBUG: Crawled (200) <GET http://books.toscrape.com/catalogue/page-18.html> (referer: None)
2018-07-24 12:18:17 [scrapy.core.engine] DEBUG: Crawled (200) <GET http://books.toscrape.com/catalogue/page-19.html> (referer: None)
2018-07-24 12:18:17 [scrapy.core.engine] DEBUG: Crawled (200) <GET http://books.toscrape.com/catalogue/page-21.html> (referer: None)
2018-07-24 12:18:17 [scrapy.core.engine] DEBUG: Crawled (200) <GET http://books.toscrape.com/catalogue/page-20.html> (referer: None)
2018-07-24 12:18:17 [scrapy.core.engine] DEBUG: Crawled (200) <GET http://books.toscrape.com/catalogue/page-22.html> (referer: None)
2018-07-24 12:18:17 [scrapy.core.engine] DEBUG: Crawled (200) <GET http://books.toscrape.com/catalogue/page-23.html> (referer: None)
2018-07-24 12:18:17 [scrapy.core.engine] DEBUG: Crawled (200) <GET http://books.toscrape.com/catalogue/page-25.html> (referer: None)
2018-07-24 12:18:17 [scrapy.core.engine] DEBUG: Crawled (200) <GET http://books.toscrape.com/catalogue/page-24.html> (referer: None)
2018-07-24 12:18:17 [scrapy.core.engine] DEBUG: Crawled (200) <GET http://books.toscrape.com/catalogue/page-26.html> (referer: None)
2018-07-24 12:18:17 [scrapy.core.engine] DEBUG: Crawled (200) <GET http://books.toscrape.com/catalogue/page-27.html> (referer: None)
2018-07-24 12:18:17 [scrapy.core.engine] DEBUG: Crawled (200) <GET http://books.toscrape.com/catalogue/page-32.html> (referer: None)
2018-07-24 12:18:17 [scrapy.core.engine] DEBUG: Crawled (200) <GET http://books.toscrape.com/catalogue/page-29.html> (referer: None)
2018-07-24 12:18:17 [scrapy.core.engine] DEBUG: Crawled (200) <GET http://books.toscrape.com/catalogue/page-30.html> (referer: None)
2018-07-24 12:18:17 [scrapy.core.engine] DEBUG: Crawled (200) <GET http://books.toscrape.com/catalogue/page-33.html> (referer: None)
2018-07-24 12:18:17 [scrapy.core.engine] DEBUG: Crawled (200) <GET http://books.toscrape.com/catalogue/page-28.html> (referer: None)
2018-07-24 12:18:17 [scrapy.core.engine] DEBUG: Crawled (200) <GET http://books.toscrape.com/catalogue/page-31.html> (referer: None)
2018-07-24 12:18:18 [scrapy.core.engine] DEBUG: Crawled (200) <GET http://books.toscrape.com/catalogue/page-34.html> (referer: None)
2018-07-24 12:18:18 [scrapy.core.engine] DEBUG: Crawled (200) <GET http://books.toscrape.com/catalogue/page-35.html> (referer: None)
2018-07-24 12:18:18 [scrapy.core.engine] DEBUG: Crawled (200) <GET http://books.toscrape.com/catalogue/page-36.html> (referer: None)
2018-07-24 12:18:18 [scrapy.core.engine] DEBUG: Crawled (200) <GET http://books.toscrape.com/catalogue/page-39.html> (referer: None)
2018-07-24 12:18:18 [scrapy.core.engine] DEBUG: Crawled (200) <GET http://books.toscrape.com/catalogue/page-40.html> (referer: None)
2018-07-24 12:18:18 [scrapy.core.engine] DEBUG: Crawled (200) <GET http://books.toscrape.com/catalogue/page-38.html> (referer: None)
2018-07-24 12:18:18 [scrapy.core.engine] DEBUG: Crawled (200) <GET http://books.toscrape.com/catalogue/page-41.html> (referer: None)
2018-07-24 12:18:18 [scrapy.core.engine] DEBUG: Crawled (200) <GET http://books.toscrape.com/catalogue/page-37.html> (referer: None)
2018-07-24 12:18:18 [scrapy.core.engine] DEBUG: Crawled (200) <GET http://books.toscrape.com/catalogue/page-42.html> (referer: None)
2018-07-24 12:18:18 [scrapy.core.engine] DEBUG: Crawled (200) <GET http://books.toscrape.com/catalogue/page-43.html> (referer: None)
2018-07-24 12:18:18 [scrapy.core.engine] DEBUG: Crawled (200) <GET http://books.toscrape.com/catalogue/page-44.html> (referer: None)
2018-07-24 12:18:18 [scrapy.core.engine] DEBUG: Crawled (200) <GET http://books.toscrape.com/catalogue/page-47.html> (referer: None)
2018-07-24 12:18:18 [scrapy.core.engine] DEBUG: Crawled (200) <GET http://books.toscrape.com/catalogue/page-45.html> (referer: None)
2018-07-24 12:18:18 [scrapy.core.engine] DEBUG: Crawled (200) <GET http://books.toscrape.com/catalogue/page-46.html> (referer: None)
2018-07-24 12:18:18 [scrapy.core.engine] DEBUG: Crawled (200) <GET http://books.toscrape.com/catalogue/page-48.html> (referer: None)
2018-07-24 12:18:18 [scrapy.core.engine] DEBUG: Crawled (200) <GET http://books.toscrape.com/catalogue/page-49.html> (referer: None)
2018-07-24 12:18:18 [scrapy.core.engine] DEBUG: Crawled (200) <GET http://books.toscrape.com/catalogue/page-50.html> (referer: None)
2018-07-24 12:18:18 [scrapy.core.engine] INFO: Closing spider (finished)
2018-07-24 12:18:18 [scrapy.statscollectors] INFO: Dumping Scrapy stats:
{'downloader/request_bytes': 12168,
 'downloader/request_count': 51,
 'downloader/request_method_count/GET': 51,
 'downloader/response_bytes': 299913,
 'downloader/response_count': 51,
 'downloader/response_status_count/200': 50,
 'downloader/response_status_count/404': 1,
 'finish_reason': 'finished',
 'finish_time': datetime.datetime(2018, 7, 24, 4, 18, 18, 598891),
 'log_count/DEBUG': 52,
 'log_count/INFO': 7,
 'response_received_count': 51,
 'scheduler/dequeued': 50,
 'scheduler/dequeued/memory': 50,
 'scheduler/enqueued': 50,
 'scheduler/enqueued/memory': 50,
 'start_time': datetime.datetime(2018, 7, 24, 4, 18, 16, 208142)}
2018-07-24 12:18:18 [scrapy.core.engine] INFO: Spider closed (finished)

I don't understand why it isn't gathering items. I says first that 0 items crawled and then shows 200 success response for pages..
Please if anyone has any idea what to try to make it crawl will be helpful.
Thankyou


text:
Q: Using Stanford Dependencies in python stanfordnlp (rather than Universal Dependencies) I'm trying to reproduce a study into sentiment analysis which uses dependency structures which were generated using the Stanford NLP library, the issue is that the study is from 2011 and I've found that than the Standford library used Stanford Dependencies but it now uses Universal Dependencies which gives different results (see https://nlp.stanford.edu/software/stanford-dependencies.shtml#English). My query is whether one can still use Stanford dependencies in the stanfordnlp library in Python?

A: There isn't a native Python model, but you could launch a Java Stanford CoreNLP server and get the older dependencies.
This model should use Stanford Dependencies for instance:
edu/stanford/nlp/models/parser/nndep/wsj_SD.gz


text:
Q: Is mathematics really true? I'm reading Learning to Reason by Nancy Rodgers, and she says:

"Truth cannot be absolute in mathematics. Truth is relative, relative to the system that we construct for it."
"Today we consider an axiom to be nothing more than a sentence that is assumed true for a particular system. The same sentence could possibly be false in another system"

then she gives an example (you don't need to read it all, it's just an example):

The axioms for Euclidean geometry were based on the
human visual perception of straight lines, but our visual perception is limited to very small distances. Our intuitive notion of straightness is based completely on light rays. Einstein predicted that a ray of light would be curved over large distances. Light rays are distorted by a gravitational field. The gravitational field comes from all the mass hanging out in that vicinity. The mass is hanging out there because of the curvature of space. An axiomatic system that models space as curved is different from Euclidean geometry. Even though we have curves in Euclidean geometry, space itself is not curved. Euclidean geometry is a good model of physical space when we are only concerned with small distances, when cosmic distances are involved, non-Euclidean geometry may provide a better model.

Now, I don't know if I'm misinterpreting things, but if "truth cannot be absolute in mathematics" does it mean that it can't be true "for everyone in the universe"? I've always thought about math like the realest thing someone can know, something that everyone in the universe must know (for example, if an ant doesn't have any food, it understands that it has $0$ food, so it knows about quantities).

So my question is, do these paragraphs mean that an axiom or a rule in general is not always true in every system, or it means that math is true only "in our heads" because we think of it in this way?

A: Mathematics is absolute truth. But people tend to be wrong about how mathematics is absolute truth. They learn about numbers and shapes, and are eventually introduced to Euclidean geometry and its axioms, and they think "these axioms are universal truths, and everything follows from them logically".
And then, the horror sets in. They hear rumors about ... non-euclidean geometry. And they think "but that isn't real - it's just playing around". But then the physicists say "it is real". And their world falls about. There are no absolute truths! Everything is relative!
What they fail to realize is that they were misunderstanding the nature of mathematics all along. Mathematics isn't "real" and it never was. That is, it never deals with the physical world. It instead exists within a realm of thought only. Now, it has applications to the real world. It was invented (or discovered) exactly to describe things in the real world. But those applications are not part of mathematics itself. Whether or not those applications provide accurate or fallacious descriptions of the real world is not a mathematical question. Perfectly good mathematics has often been used for both. Those are questions for scientists and philosophers.
Yes, mathematical theories start with axioms. And yes, you can choose other axioms that disagree, and get another mathematical theory that is just as valid as the original. Which is correct? Both are! If you grew up only seeing and eating red apples, then one day went to a grocery store and saw green apples, should you recoil in horror and think your entire world has been turned upside down? Obviously, a better response would be "Neat! We get variety in apples!" The same is true here. Hyperbolic geometry is just a different variety of mathematics from Euclidean geometry. It is a whole new playground we can explore! Which is the "real geometry"? Well, what does "real geometry" even mean? The geometry of the physical world? That is a physics question, not a mathematical one.
So we abandon absolute truth? No. The axioms were never absolute. They are just definitions. They define the particular theory we are working in. But you are always free to define a different theory. What is absolute is not the axioms, but rather that the theorems in a theory follow from its axioms (based on its logic system - that can be redefined too). So I can't claim once and for all and ever more that through a point not on a line, there is exactly one other line parallel to the first. But I can say once and for all and ever more that in that system where there is only one parallel (amongst various other defining axioms), the interior angles of a triangle will add up to a straight line.


text:
Q: Show/hide content using jquery in multiple DIVs I have a single page with, say 5 posts, all in the #article. Following is the jQuery code used to toggle hide/show:
$(".click-show-more").click(function () {
    if($(".content").hasClass("show-more")) {
        $(this).text("(Show Less)");
    } else {
        $(this).text("(Show More)");
    }
    $(".content").toggleClass("show-more");
});

The HTML structure is :

Some text here. Some text here. Some text here. Some text here. Some text here. Some text here. Some text here. Some text here. Some text here. Some text here. Some text here. Some text here. Some text here. Some text here. Some text here.

Some text here. Some text here. Some text here. Some text here. Some text here. Some text here. Some text here. Some text here.

(Show More)

Now, I have the above structure, 5-6 times on a single page, and whenever I click Show More, all the 5-6 posts expand.
How do I modify my code to expand only that particular post?

A: Change this line
$(".content").hasClass("show-more")

to
$(this).closest('.article').find('.content').hasClass("show-more")

Your click should only affect the content of the particular article. So use the this context to your advantage.
Also this line
$(".content").toggleClass("show-more");

should be
$(this).closest('.article').find('.content').toggle();

Unless .show-more {  display: none } is already defined.
Code
$(".click-show-more").click(function () {
    var $closestContent = $(this).closest('.article').find('.content');

    if($closestContent.hasClass("show-more")) {
        $(this).text("(Show Less)");
    } else {
        $(this).text("(Show More)");
    }
    $closestContent.toggleClass('show-more');
});

Check Fiddle

A: Instead of finding any div with class content, you need to find the one within the same article div.
So it would look something like this:
$(".click-show-more").click(function () {
    var content = $(this).closest('.article').find('.content');
    if(content.hasClass("show-more")) {
        $(this).text("(Show Less)");
    } else {
        $(this).text("(Show More)");
    }
    content.toggleClass("show-more");
});

What's actually happening is we're taking the div that was clicked on:
$(this)

Finding the closest parent that has the article class:
$(this).closest('.article')

And then finding any children of that article div that have the content class:
$(this).closest('.article').find('.content')


text:
Q: Provision classic cloud service via ARM template In one of our project, we are trying to automate deployment of cloud components on Azure. For majority of components (basically all ARM components like Redis, Service bus, App Service etc.) we were able to achieve it using ARM templates and Powershell script.
However, we are stuck at Cloud Service (classic) component. Cloud service component contains only WebRole in it and no VM needs to be provisioned.
We can go via classic deployment model i.e. using ASM commands in power shell. But since, ARM model supports provisioning and deployment from azure portal so I was wondering ARM REST API's must have out of box support for this component as well. I try to figure out but couldn't find any related documentation to it.

What I have tried so far
Azure template (AzureDeploy.json)
{
    "$schema": "http://schema.management.azure.com/schemas/2014-04-01-preview/deploymentTemplate.json#",
    "parameters": {
        "name": {
            "type": "string"
        },
        "location": {
            "type": "string"
        }
    },
    "resources": [
         {
            "apiVersion": "2014-06-01",
            "name": "[parameters('name')]",
            "location": "[parameters('location')]",
            "type": "Microsoft.ClassicCompute/domainNames"
        }
    ]
}

Powershell script:
Param(
    [string] $ResourceGroupLocation = 'South India',
    [string] $ResourceGroupName = 'FreeTrial',
    [string] $TemplateFile = 'AzureDeploy.json'
)

$TemplateFile = [System.IO.Path]::GetFullPath([System.IO.Path]::Combine($PSScriptRoot, $TemplateFile))

New-AzureRmResourceGroup -Name $ResourceGroupName -Location $ResourceGroupLocation -Verbose -Force -ErrorAction Stop
New-AzureRmResourceGroupDeployment -Name ((Get-ChildItem $TemplateFile).BaseName + '-' + ((Get-Date).ToUniversalTime()).ToString('MMdd-HHmm')) `
                                   -ResourceGroupName $ResourceGroupName `
                                   -TemplateFile $TemplateFile `
                                   -Force -Verbose

If I try to execute the above script, execution gets stuck at Checking deployment for an hour or so and have to manually kill the script execution.
.

However, if I ran following command in power shell, it succesfully creates a resource in portal:

New-AzureRmResource -Location "South India" -ResourceName
  "cloudsmplservice" -ResourceType
  "Microsoft.ClassicCompute/domainNames" -ResourceGroupName "FreeTrial"

But I do not understand what's an issue with ARM template approach. Can someone please direct me to the problem in first approach?

Addendum:
I found a strange behaviour. If I hardcode the resource name value in the resource definition OR pass it when powershell prompt for it, deployment works fine.
However, if I set some default Value for parameter OR pass it via parameter file, its not working.
{
  "$schema": "http://schema.management.azure.com/schemas/2014-04-01-preview/deploymentTemplate.json#",
  "contentVersion": "1.0.0.0",
  "parameters": {
    "cloudName": {
      "type": "string",
      "defaultValue": "cloudsrvc"
    }
  },
  "resources": [
    {
      "apiVersion": "2015-06-01",
      "name": "[parameters('cloudName')]",
      "location": "[resourceGroup().location]",
      "type": "Microsoft.ClassicCompute/domainNames"
    }
  ]
}

Addendum2:
Seems like some powershell configuration issue. Will report it to Azure team with more details. So, far was able to reproduce it with simple steps:

*

*Created a fresh VM in azure.

*Imported AzureRM modules.

*Try to provision cloud service with default value template. (Stuck as mentioned)

*Try to provision now by passing the parameter from powershell. (Worked fine)

*Now try again with default value template. (Worked fine)

A: I will recommend you to validate your Cloud Service ARM Template from the Template Deployment in the Azure portal.
I am able to deploy a bare metal Cloud Service using the template below and the deployment is successful within seconds.
You can also "reverse engineer" the Cloud Service ARM Template by clicking on the Automation option when try to create a new Cloud Service from the Azure portal.
I didn't see the problem in automating Cloud Service by the ARM Template approach.
Note:
I have deployed this in South India location and it works.
Addendum:
I have deployed the template as below using your PowerShell script and it works as well.
Azure PowerShell version is 4.3.1 (August 2017).
Screenshot as below.

{
    "$schema": "http://schema.management.azure.com/schemas/2014-04-01-preview/deploymentTemplate.json#",
    "contentVersion": "1.0.0.0",
    "parameters": {
        "name": {
            "type": "string"
        },
        "location": {
            "type": "string"
        }
    },
    "resources": [
        {
            "apiVersion": "2016-11-01",
            "name": "[parameters('name')]",
            "location": "[parameters('location')]",
            "type": "Microsoft.ClassicCompute/domainNames"
        }
    ]
}

Addendum 2:
Try with template with default param values and the deployment is also working successful.
Note: I notice your api version is older and the api version for my cloud service is 2016-11-01

{
  "$schema": "http://schema.management.azure.com/schemas/2014-04-01-preview/deploymentTemplate.json#",
  "contentVersion": "1.0.0.0",
  "parameters": {
    "name": {
      "type": "string",
      "defaultValue": "[resourceGroup().name]"
    },
    "location": {
      "type": "string",
      "defaultValue": "[resourceGroup().location]"
    }
  },
  "resources": [
    {
      "apiVersion": "2016-11-01",
      "name": "[parameters('name')]",
      "location": "[parameters('location')]",
      "type": "Microsoft.ClassicCompute/domainNames"
    }
  ]
}

A: We also could use the REST API to do that,I test it with fiddler.
https://management.azure.com/subscriptions/{subscriptionid}/resourceGroups/{resourcegroupname}/providers/Microsoft.ClassicCompute/domainNames/{cloudservicename}?api-version=2016-04-01

Note: please make sure that your subcription support to create the cloudservice in that location. If it is not supported, we will get the following error.

The location constraint is not valid


text:
Q: angularjs 'back' inside iframe I have an angularjs project that is opened inside an iframe. Currently when someone hits back I use 'window.history.back();' however it seems this makes the parent window go back.
Using angular how can I make only the content inside the iframe move back?


text:
Q: Assign a FrameworkElement to a control template programatically I'm trying to custom draw a GridSplitter, and I have the following XAML code:
<GridSplitter Grid.Column="1" Width="50" HorizontalAlignment="Stretch">
    <GridSplitter.Template>
        <ControlTemplate TargetType="{x:Type GridSplitter}">
            <custom:DiffSplitterCanvas />
        </ControlTemplate>
    </GridSplitter.Template>
</GridSplitter>

DiffSplitterCanvas inherits from Canvas.
I need to write it programatically. And I also need it to use a given already created instance of the DiffSplitterCanvas. Simplifying the code, it would be something like this:
GridSplitter mySplitter = new GridSplitter();
ControlTemplate myTemplate = new ControlTemplate(typeof(GridSplitter));
DiffSplitterCanvas myCanvas = new DiffSplitterCanvas();
AddElementToTemplate(myCanvas, myTemplate);
mySplitter.Template = myTemplate;

void AddElementToTemplate(FrameworkElement element, ControlTemplate template)
{
  // how could achieve this?
}

EDIT: The reason I ask this question is because I need to change some properties in the DiffSplitterCanvas instance while the user interacts with the UI. Maybe this is not the way to implement it using WPF, but I'm really lost here.

A: The correct way is to use bindings and dependency properties. You could do this in pure procedural code, but this will be over-complicated and error-prone.
You can get an overview of dependency properties in the official documentation. There is also some good tutorials.
Assuming you declare a dependency property called MyProperty in DiffSplitterCanvas, in the end you will have something like:
<GridSplitter Grid.Column="1" Width="50" HorizontalAlignment="Stretch">
    <GridSplitter.Template>
        <ControlTemplate TargetType="{x:Type GridSplitter}">
            <custom:DiffSplitterCanvas
                 MyProperty="{Binding Path=SomeOtherPropertyFromDataContext}"/>
        </ControlTemplate>
    </GridSplitter.Template>
</GridSplitter>

Whenever the value of SomeOtherPropertyFromDataContext changed it will be reflected on the DiffSplitterCanvas. Note that you will need to configure the Source attribute of the binding accordingly, depending on what is holding the SomeOtherPropertyFromDataContext property (might be the context of the column, the parent control, the view model, etc.).


text:
Q: Creating regex restriction on OWL class I'm trying to create a simple ontology that has two classes: class1 and class2,- and two instances that have simple text data property with the same name (hasName: "string1"^^xsd:string and hasName "string2"^^xsd:string respectivly). I want to classify these instances with reasoner to the respective classes based on regular expression (for example, the restriction for class 1 would be hasName some xsd:string[pattern "string1"], and such, the reasoner should infer that instance1 belongs to class1, but instance2 is not). How can it be done?

A: Using Openllet(2.6.2-SNAPSHOT) you can do things like that :
    final OWLNamedIndividual x1 = OWL.Individual("#I1");
    final OWLNamedIndividual x2 = OWL.Individual("#I2");

    owl.addAxiom(OWL.equivalentClasses(ClsA, OWL.some(propB, OWL.restrict(XSD.STRING, OWL._factory.getOWLFacetRestriction(OWLFacet.PATTERN, OWL.constant("A.A"))))));
    owl.addAxiom(OWL.propertyAssertion(x1, propB, OWL.constant("AAA")));
    owl.addAxiom(OWL.propertyAssertion(x2, propB, OWL.constant("BBB")));

    owl.addAxiom(OWL.differentFrom(x1, x2));

    final OpenlletReasoner r = owl.getReasoner();
    assertTrue(r.isEntailed(OWL.classAssertion(x1, ClsA)));
    assertFalse(r.isEntailed(OWL.classAssertion(x2, ClsA)));

As you can see the line :
OWL.restrict(XSD.STRING, OWL._factory.getOWLFacetRestriction(OWLFacet.PATTERN, OWL.constant("A.A"))))));

is the one that add the "regexp" to the classification algorithm.
Here the pattern is 'A.A', pattern follow 'java-regexp'enter link description here rules.


text:
Q: Problems with \addtocontent and \addcontentsline I am trying to add a heading in the list of figures and list of tables. I found a solution here:
Include chapters in List of Figures with titletoc?
However, this looks pretty complicated and I after some more googling I found this webpage:
http://www.personal.ceu.hu/tex/toc.htm
which show how to add a single line to toc, lof and lot using just 1 command. This seemed to be my solution however when I add the following line:
\addtocontents{lof}{Heading}

I get an error message: ! LaTeX Error: Something's wrong--perhaps a missing \item.
I googled and found this webpage which shows a solution for this problem:
https://groups.google.com/forum/?fromgroups=#!topic/comp.text.tex/2IE68-IJJ6U
I tried different approaches such as:
\addtocontents{lof}{\protect\contentsline{chapter}{Heading 1}{}}
\addtocontents{lof}{\protect\contentsline{figure}{Heading 2}{}}

\addcontentsline{lof}{chapter}{\protect\numberline{}{Heading 3}}
\addcontentsline{lof}{figure}{\protect\numberline{}{Heading 4}}

The one which looks closest to what I want is the first command ...{Heading 1}
However, using this command latex adds an extra line or extra vertical space so that
there is a new line after Heading 1 in the lof.
This would be fixed by using:
\addtocontents{lof}{\textbf{Heading}}

However, as already written this results in an error. I don't understand why this simple command results in an error even though I am quite sure I got the syntax right.
So just to clarify how I would like to have my lof here is a short example:
\textbf{1 Chapter}
          1.1 Figure 1
          1.2 Figure 2

\textbf{2 Chapter}
          2.1 Figure 3
          2.2 Figure 4

Can anyone help?
Here is my working example:
\documentclass[10pt,DIV=12,a4paper,numbers=noenddot]{scrreprt}
\begin{document}

\tableofcontents
\listoffigures

%
\addtocontents{lof}{\protect\contentsline{figure}{Heading 1}{}}
\addcontentsline{lof}{chapter}{\protect\numberline{}{Heading 2}}
\addcontentsline{lof}{figure}{\protect\numberline{}{Heading 3}}

% Closest to what I would prefer
\addtocontents{lof}{\textbf{Heading 4}\protect\par}
\addtocontents{lof}{\protect\contentsline{chapter}{Heading 5}{}}

\chapter{Introduction}
\section{s1}

\begin{figure}
\caption{figure 1}
\end{figure}

\begin{figure}
\caption{figure 2}
\end{figure}

\section{s2}

\chapter{Content}
\section{c1}
\section{c2}

\end{document}

I basically want the lof to look like the toc. There is no newline after "1 Introduction" and "2  Content". I also just realized that the font for "Heading 4" and "Heading 5" looks different. So I think I would prefer the font of "Heading 5" which I think is the one used in the toc. So "Heading 5" would be perfect if there would not be a newline afterwards. Is it possible to somehow suppress this newline?

A: The answer to the question linked provides and automated solution; if you, for some reason, decide to do this manually (which might be a cause for problems: for example, the automated solution won't add heading if there's no figures in a chapter and manually you can overlook this), you can proceed as in the xample below.
Using a variation of Martin Scharrer's answer to Table of Contents with additional description of entries, I defined a \headinginfo command which typesets its mandatory argument in the LoF, using the same formatting as chapter entries in the ToC (since a KOMA class is used, this is easily achieved using \usekomafont{disposition}); the \headinginfo command must be used before the first figure environment of a chapter (I would suggest immediately after the corresponding \chapter):
\documentclass{scrreprt}

\makeatletter
% A modification of the kernel's \@dottedtocline,
% suppressing the leaders (dots) and page number
% A variation of Martin Scharrer's answer:
% https://tex.stackexchange.com/a/10189
\def\@nodottedtocline#1#2#3#4#5{%
    \vskip \z@ \@plus.2\p@
    {\leftskip #2\relax \rightskip \@tocrmarg \parfillskip -\rightskip
     \parindent #2\relax\@afterindenttrue
     \interlinepenalty\@M
     \leavevmode
     \@tempdima #3\relax
     \advance\leftskip \@tempdima \null\nobreak\hskip -\leftskip
     {#4}\hfill\null\par}}
\newcommand*\l@heading{\@nodottedtocline{0}{0em}{0em}}
\makeatother
\newcommand\headinginfo[1]{%
  \addcontentsline{lof}{heading}{{\usekomafont{disposition}#1}}%
  \addtocontents{lof}{\vspace{5pt}}}

\begin{document}
\listoffigures

\chapter{Test Chapter One}
\headinginfo{Some Text for Chapter One}
\begin{figure}
\centering
A
\caption{A test figure}
\end{figure}
\begin{figure}
\centering
B
\caption{Another test figure}
\end{figure}

\chapter{Test Chapter Two}
\headinginfo{Some Text for Chapter Two}
\begin{figure}
\centering
C
\caption{A test figure}
\end{figure}
\begin{figure}
\centering
D
\caption{Another test figure}
\end{figure}

\end{document}


text:
Q: Autosave option in Office 2007? Is there any auto save option in Office 2007 applications like we have in Google Docs?

A: Yep, it's been a feature since at least office 2000:
http://www.technipages.com/word-2007-enabledisable-autosave.html


text:
Q: python scrape webpage and parse the content I want to scrape the data on this link
http://www.realclearpolitics.com/epolls/json/5491_historical.js?1453388629140&callback=return_json
I am not sure what type of this link is, is it html or json or something else. Sorry for my bad web knowledge. But I try to use the following code to scrape:
import requests

url='http://www.realclearpolitics.com/epolls/json/5491_historical.js?1453388629140&callback=return_json'
source=requests.get(url).text

The type of the source is unicode. I also try to use the urllib2 to scrape like:
source2=urllib2.urlopen(url).read()

The type of source2 is string. I am not sure which method is better. Because the link is not like the normal webpage contains different tags. If I want to clean the scraped data and form the dataframe data (like the pandas dataframe), what method or process I should follow/
Thanks.

A: The returned response is text containing valid JSON data within it. You can validate it on your own using a service like http://jsonlint.com/ if you want. For doing so just copy the code within the brackets

return_json("JSON code to copy")

In order to make use of that data you just need to parse it in your program. Here an example: https://docs.python.org/2/library/json.html

A: The response is text. It does contain JSON, just need to extract it
import json

strip_len = len("return_json(")

source=requests.get(url).text[strip_len:-2]
source = json.loads(source)


text:
Q: Error creating Lambda function - The subnet is out of IP addresses We have a terraform script to create a lambda function in aws. This lambda function uses a custom bucket from S3.
The script below runs perfectly when I put "Resource": "*".
We need to specify a custom resource that aws lambda function can access on S3.
Our aws_iam_policy is configured this way:
resource "aws_iam_policy" "lambda_policy" {
  name = "lambda-s3-policy"
  policy = <<EOF
{
  "Version": "2012-10-17",
  "Statement": [
    {
        "Effect": "Allow",
        "Action": [
            "s3:*",
            "ec2:CreateNetworkInterface",
            "ec2:DescribeNetworkInterfaces",
            "ec2:DeleteNetworkInterface",
            "ec2:DescribeSecurityGroups",
            "ec2:DescribeSubnets",
            "ec2:DescribeVpcs"
        ],
        "Resource": "arn:aws:s3:::my-mock-bucket/example-folder/*"
    }
  ]
}
 EOF
}

When the script runs, this error appears:
Error: Error applying plan:
1 error(s) occurred:
* aws_lambda_function.func_loader: 1 error(s) occurred:
* aws_lambda_function.func_loader: Error creating Lambda function: InvalidParameterValueException: The subnet subnet-xxxxxxxxxxxxxxxx is out of IP addresses.
{
  RespMetadata: {
    StatusCode: 400,
    RequestID: "xxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
  },
  Message_: "The subnet subnet-xxxxxxxxxxxxxxxx is out of IP addresses.",
  Type: "User"
}
Terraform does not automatically rollback in the face of errors.

I already checked the permissions, the subnet ip range limits, but it is all good to go.

A: These permissions:
   "ec2:CreateNetworkInterface",
   "ec2:DescribeNetworkInterfaces",
   "ec2:DeleteNetworkInterface",
   "ec2:DescribeSecurityGroups",
   "ec2:DescribeSubnets",
   "ec2:DescribeVpcs"

Can't be restricted to this resource:
"Resource": "arn:aws:s3:::my-mock-bucket/example-folder/*"

What you have done is given your Lambda function permission to call those EC2 actions, as long as it is calling those actions on an S3 bucket, which obviously makes no sense. You probably need to split the IAM policy into multiple statements, like so:
{
  "Version": "2012-10-17",
  "Statement": [
    {
        "Effect": "Allow",
        "Action": [
            "s3:*",
        ],
        "Resource": "arn:aws:s3:::my-mock-bucket/example-folder/*"
    },
    {
        "Effect": "Allow",
        "Action": [
            "ec2:CreateNetworkInterface",
            "ec2:DescribeNetworkInterfaces",
            "ec2:DeleteNetworkInterface",
            "ec2:DescribeSecurityGroups",
            "ec2:DescribeSubnets",
            "ec2:DescribeVpcs"
        ],
        "Resource": "*"
    }
  ]
}


text:
Q: FSEvents: kFSEventStreamCreateFlagWatchRoot flag: not getting 'root rename' events I'm creating FSEvents stream and passing the kFSEventStreamCreateFlagWatchRoot flag. From Apple's documentation:

kFSEventStreamCreateFlagWatchRoot :
  Request notifications of changes along the path to the path(s) you're watching. For example, with this flag, if you watch "/foo/bar" and it is renamed to "/foo/bar.old", you would receive a RootChanged event. The same is true if the directory "/foo" were renamed. The event you receive is a special event: the path for the event is the original path you specified, the flag kFSEventStreamEventFlagRootChanged is set and event ID is zero.

So when "/foo/bar" renamed to "/foo/bar.old" I'm getting the event as expected. But when "/foo" directory is renamed, I'm not getting the event as I should've. What might be a possible reason?

A: This is a known "FSEvents" bug in OS X: http://www.openradar.me/8342264


text:
Q: clearInterval() is not working when called more than once I am building a React App and I have implemented a slider in my app. By default my slider is automatically but I made a toggle button so the user can stop the automatization at any tine.
Of course I ușe setInterval to make this auto-sliding effect. When I press the toggle first time it stops, but when I start it again and try to stop it another time it doesn't work and the auto-sliding continues when it should stop.
This is my code:
const toggle = document.querySelector(".toggle-container");
const toggleDot = document.querySelector(".toggle");
let autoSliding = true;

let slidingInterval = setInterval(() => {
    nextButton.click();
}, 2500);

const stopAutoSliding = () => {
    toggleDot.style.left = "10%";
    toggle.style.background = "#ccc";
    autoSliding = false;

    clearInterval(slidingInterval);
}

const restartAutoSliding = () => {
    toggleDot.style.left = "calc(90% - 20px)";
    toggle.style.background = "#0c46b3";
    autoSliding = true;
    let slidingInterval = setInterval(() => {
        nextButton.click()
    }, 2500);
}

toggle.addEventListener("click", () => {
    if (autoSliding) {
        stopAutoSliding();
    } else {
        restartAutoSliding();
    }
});

nextButton is just a button for which I set an addEventListener method for click events and it just simply makes the slider to move to the next slide.
If you wanna see it working follow this link.


text:
Q: How to use a hidden page item within an SQL report query without submitting Using: Oracle ApEx 3.0.1
I have a SQL report region that contains a hidden page item as part of the "where clause". My problem is, based on a value entered by the user, I need to assign this value entered to my hidden item, so that it can be used within the where condition of my SQL but this would need to be done without actually submitting the form.
At the moment, I can set the value via an on-demand process but my SQL is still not returning any values as the hidden page item within the query is not set (as page has not been submitted).
I am not sure how to do this and whether in actual fact, this is possible to do, without having submitted the page.

A: Since you are on Apex 3, you don't have dynamic actions, but that doesn't hinder so much.
I've set up an example on apex.oracle.com. To get in the workspace, use workspace 'tompetrusbe' + apex_demo / demo.
 There is a dynamic action there, which can do the work too, but i've disabled it.
What you need to make it work:
an ajax callback process, with the following line:
apex_util.set_session_state('P2_PAR_ENAME', apex_application.g_x01);

Give your report region a static id, i called mine 'report_emp'. This so i can easily retrieve it.
In the javascript region of the page, you then need to call the app process, and then refresh the region. Also bind the event which needs to trigger this action. I've done it here through the onchange event of the parameter textfield.
function refresh_report(oTrgEl){
   //alert('refresh: ' + $v(oTrgEl));
   //calling the application process which sets the session state of P2_PAR_ENAME
   var oGet = new htmldb_Get(null, &APP_ID., 'APPLICATION_PROCESS=set_session_state', &APP_PAGE_ID.);
   oGet.addParam("x01", $v(oTrgEl));
   oGet.get(); //the app process just sets something, it returns nothing

   //refresh the report region
   $("#report_emp").trigger("apexrefresh");
};

function bind_events(){
   //call this onload
   $("#P2_PAR_ENAME").change(function(){refresh_report(this);});
};

In the query of the report i use where ename like '%'||UPPER(:P2_PAR_ENAME)||'%'.
When you type (for example) 'bl' in, and tab out (to trigger the onchange), the region will refresh and will be filtered.
You'll just need to adapt to your solution :)


text:
Q: Laravel - Stripe Integration - Applying a discount coupon to an Invoice object at creation time I´m trying to apply a Stripe Coupon to a Stripe Invoice object at creation time in my Laravel 5.8 application, with no luck so far.
This is the code in my controller:
$options = [
    'api_key' => 'sk_test_xxxxxxxxxxxxxxxx',
    'stripe_version' => "2019-08-14"
];

$coupon = \Stripe\Coupon::retrieve('xfpwySG1'); // I´m retrieving the coupon solely to use it for testing.

// $parameters = ['customer' => Auth::user()->stripe_id]; // This works fine (no discounts applied)
//This are all the different versions of parameters array I´ve tried, none of them work
// $parameters = ['customer' => Auth::user()->stripe_id, ['discounts' => ['coupon' => 'xfpwySG1']] ]; //Invalid array
// $parameters = ['customer' => Auth::user()->stripe_id, 'discounts' => ['coupon' => 'xfpwySG1'] ]; //Invalid array
// $parameters = ['customer' => Auth::user()->stripe_id, 'discounts' => ['coupon' => $coupon] ]; //Invalid array
// $parameters = ['customer' => Auth::user()->stripe_id, 'discounts' => ['coupon' => 'xfpwySG1'] ]; //Invalid array
// $parameters = ['customer' => Auth::user()->stripe_id, 'discounts' => $coupon ]; //Invalid array
// $parameters = ['customer' => Auth::user()->stripe_id, ['discounts' => ['xfpwySG1']] ]; //Invalid object
$parameters = ['customer' => Auth::user()->stripe_id, ['discounts' => 'xfpwySG1'] ]; //Invalid object
// $parameters = ['customer' => Auth::user()->stripe_id, 'discounts' => ['xfpwySG1'] ]; //Invalid object
// $parameters = ['customer' => Auth::user()->stripe_id, 'discounts' => 'xfpwySG1' ]; //Invalid array

// This is where I create the invoice object, using the info above.
$invoice = \Stripe\Invoice::create($parameters, $options);

Notice if I don´t try to include the 'discounts' parameter, as in the first $parameters line, everything works fine; just as soon as I try to give away free stuff, my app fails... haha! Also, I tried applying the coupon to the InvoiceItem object, with similar results.
I´m having some difficulties understanding the Stripe Ecosystem and how all the pieces fit together, so any help will be appreciated.
Thanks in advance

A: You should use an array of array for 'discounts' key. Try this.
$parameters = ['customer' => Auth::user()->stripe_id, [['coupon' => 'xfpwySG1', 'discount' => null]];


text:
Q: htaccess problem on laravel, can't load css js and other routes I have some problem with .htaccess on Laravel 7.16.1,

*

*i have laravel installed on root folder something like this : /var/www/user/

*i have renamed server.php on root folder to index.php

the problem is, laravel is index route is working fine but cannot access other route (eg. login, register, and my routes) also can't load assets (css,js) so the web is bare bone because it can't load css and js. but it can load css and js on public folder, like mydomain.com/public/asset.js. etc
i have tried several solution on stack overflow before by changing the .htaccess on root folder and public path, but none of them working !
here is my default htaccess on root folder
<IfModule mod_rewrite.c>
    <IfModule mod_negotiation.c>
        Options -MultiViews -Indexes
    </IfModule>

    RewriteEngine On

    # Handle Authorization Header
    RewriteCond %{HTTP:Authorization} .
    RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}]

    # Redirect Trailing Slashes If Not A Folder...
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteCond %{REQUEST_URI} (.+)/$
    RewriteRule ^ %1 [L,R=301]

    # Send Requests To Front Controller...
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteRule ^ index.php [L]
</IfModule>

what is the correct .htaccess to solve this problem ? thank you.


text:
Q: std::underlying_type : Does SFINAE prevent undefined behavior? std::underlying_type invokes undefined behavior when used with a non enum type.
But where does the undefined behavior appears?
In this code :
template<typename E>
constexpr std::enable_if_t<std::is_enum<E>::value, std::underlying_type_t<E>> IntEnum(E e)
{
    return static_cast<std::underlying_type_t<E>>(e);
}

I tried to use std::enable_if to prevent the user from calling IntEnum with non-enum types. But as enable_if is evaluated before deciding if the function can be called, its template arguments get evaluated too, including std::underlying_type_t<E>. So is this UB if called with a non-enum type? How can i change it?

A: typename std::underlying_type<E>::type is evaluated even for non-enum type (and is not SFINAE friendly).
You may use one indirection to delay the evaluation and be SFINAE friendly:
template<typename E>
constexpr
typename std::enable_if_t<std::is_enum<E>::value, std::underlying_type<E>>::type
IntEnum(E e)
{
    return static_cast<std::underlying_type_t<E>>(e);
}

Demo

A: You can prevent compilation with static_assert
template<typename E>
constexpr auto IntEnum(E e)
{
    static_assert(std::is_enum<E>::value, "E must be an enum");
    return static_cast<std::underlying_type_t<E>>(e);
}


text:
Q: simple Elasticsearch nested search query I have documents in ES (Tweepy JSON) like this
{
  "_source": {
    "id": 792477813014224900,
    "metadata": {
      "iso_language_code": "en",
      "result_type": "recent"
    },
    "retweeted": false,
    "retweet_count": 330,
    "user": {
      "id": 149250899,
      "listed_count": 0,
      "protected": false,
      "followers_count": 347,
      "entities": {
        "description": {
          "urls": []
        }
      },
      "screen_name": "Zwido_"
}

And I would like to search and query one full document based by user_name field.
I tryied this code
{
            "nested": {
                "path": "_source",
                "score_mode": "avg",
                "query": {
                    "bool": {
                        "must": [
                            {
                                "text": {"_source.user.user_name": user}
                            }
                        ]
                    }
                }
            }
}

But it doesn't work and I received error
TransportError(400, 'search_phase_execution_exception', 'failed to parse search source. unknown search element [nested]

What I am doing wrong?
Thanks for help.

A: You don't need to specify the _source field + you're missing a query at the top-level, do it like this instead.
{
    "query": {
        "nested": {
            "path": "user",
            "score_mode": "avg",
            "query": {
                "bool": {
                    "must": [
                        {
                            "match": {"user.screen_name": user}
                        }
                    ]
                }
            }
        }
    }
}

UPDATE
If your user field is not of nested type, then you can simply do it like this:
{
  "query": {
    "bool": {
      "must": [
        {
          "match": {
            "user.screen_name": user
          }
        }
      ]
    }
  }
}

A: as mentioned in the elasticsearch documentation here you should change the mapping of your data to tell elasticsearch that it is nested object. Once that is done then you can query the object.


text:
Q: Update target button is disabled after schema comparison I have created database project using VS 2012. Once the schema comparison is done, the update target button should be enabled to sync with target.
But it's not getting enabled. Any help plz.
I'm using VS 2012 with sp 3, SQL Server 2012,

A: Check the Error List if you have any error, I had a non recognized word in VS (but it did in SQL Server), I commented it out, re-compared and it was enabled successfully.

A: Workaround:
In my case. Fixing Error was not priority task. Also i was not able to find any Error in Error List.
Its just you dont have to use your "Visual Studio Database Project" in source or target. Instead of using project, create a temp DataBase using script already with you.
Select this (or these) temp database(s) in source and (or) other in target.
Button must be Enabled.
For me getting difference was far more important than fixing the issue. Hope it helps you. With some more improvisation.

A: It seems your database project has sqlcmd variables without default values.
See:
http://www.andrewburrow.net/vs2012-schema-compare-buttons-disabled/
Hope this helps.

A: See if you have a "warning" message stating "Cannot generate deployment plan due to an internal error". If so, the Update and Generate Script buttons will be disabled.
Close Visual Studio, navigate to the folder containing the Database project and remove all (*.dbmdl) files. Then restart Visual Studio, re-run the compare schema at which point the Update button should be enabled.

A: I couldn't see any errors in Error List, but I could see the errors in the Output tab

A: the everytime you open the "options" on "schema comparison" you must click on "compare" button again to activate the "update" button. However if it doesn't work at the first time, just close and reopen the Schema comparison file again.

A: For me, there were no errors visible in the Error List.  This was because I had the "Show Issues Generated" drop down was set to "Build Only"; changing it to "Build + IntelliSense" allowed me to see the SQL errors that needed to be fixed to enable the Generate Script and Update buttons.

A: In SSDT I had the case where the update button was enabled but the generate script was not enabled. This was because my destination schema was my local solution (the *.sqlproj vs project).
It took a few minutes to dawn on me that the destination needed to be a real database to correctly generate the script.

A: And after all, when you have the available Update Target button and the disabled Generate Script button.
See if your source is a database and your target is your SSDT project.
If so then click "Switch source and target" button.
The Generate Script button will become available.
I.e. a SSDT project must be the source and a database must be the target in the Schema Compare window.

A: Workaround 2:
In my case, the Update button was greyed out because of there were errors warnings about a view that I created and added to the project earlier.
The problem was that the view was scripted to use full database qualified object naming. E.g. [databasename].[schemaname].[objectname], which works fine in SSMS, but causes a problem when it is checked in a DB Project.
If you use three part naming for referring an object in same DB project results in a error/warning in Visual Studio.
By changing the code to [schemaname].[objectname] in the definicion of the view removed the error warnings and enable the Update option. Happy days!
Credits:
https://visualstudio.uservoice.com/forums/121579-visual-studio-ide/suggestions/3577074-allow-three-part-naming-for-referring-a-db-object
https://visualstudio.uservoice.com/forums/121579-visual-studio-ide/suggestions/17396128-keep-update-and-generate-update-script-buttons

A: Typically the update button is grayed out when the database objects are available in the separate sql files physically inside the database project but are not included in the database project itself. I simply added those sql scripts into the project and the update button got enabled after comparing the schema.

A: In my case, the Update button was disabled because there was a scalar function that was modified and that function was used in a computed column definition.
My solution was to:

*

*Manually drop the computed column(s) in the database

*

*ALTER TABLE <your table> DROP COLUMN <your computed column>

*Re-run the schema compare

*The Update button was enabled, and the update completed successfully


text:
Q: Tags semânticas para citação e autor Estou fazendo uma landing page como challenge do Frontend Mentor e gostaria de saber quais as melhores tags semânticas para fazer esse bloco abaixo. Utilizei o
 para a citação, porém não sei qual tag usar para o autor da frase.

A: Estou me baseando nessa resposta no SO.

"Money is the real cause of poverty,"

        The Ragged-Trousered Philanthropists, page 89.

Isto está de acordo com o exemplo da especificação. Mas não tem nada na específica que só assim é certo.
E que antes se fazia assim, o que particularmente achei mais bonito:

        "This is what I think"

        — My Name, My Company

Coloquei no GitHub para referência futura.
Tem uma outra resposta que usou esta forma:

This is a really insightful sentence.

    Darko Z

E nela cita que em HTML5 a citação não deve usar o nome do autor, então é um pouco confuso.
A MDN que é meio que uma documentação "oficial" que as pessoas usam dá este exemplo:

It was a bright cold day in April, and the clocks were striking thirteen.

        First sentence in Nineteen Eighty-Four by George Orwell (Part 1, Chapter 1).

Mas já vi coisas erradas na MDN.
Um trecho importante da específica:

User agents may allow users to follow such citation links, but they are primarily intended for private use (e.g: by server-side scripts collecting statistics about a site's edits), not for readers

Está dizendo que o uso disto não é para o leitor e sim para algo interno, privado, para uso de ferramentas.
Seu uso parece mais interessante para os indexadores que podem usá-lo como quiserem, não tem um padrão estabelecido.
Tem outra perguntas que tem respostas, mas não achei elas tão fundamentas.
Procurei e não achei um jeito certo de fazer, tem a ver com gosto, principalmente se a citação não envolve um aspecto científico, mas é bom usar o cite de uma forma ou outra para dar semântica e pelo menos os buscadores indexarem de forma adequada. Provavelmente ajudará na acessibilidade, e algumas ferramentas pode ter seu trabalho melhor.
Obviamente o visual é algo que você dará com CSS e outras formas do HTML que nada tem a ver com a citação em si.

A: Numa blockquote podes usar tag footer para mencionar a origem da mesma, exemplo:

You know the golden rule, don't you boy? Those who have the gold make the rules.

— Crazy hunch-backed old guy in Aladdin


text:
Q: Exponential CD burn times in iTunes 10.6.1 (7) on OS X 10.6.8 The more I try put on a CD and the closer I get to the 80 minute mark, the longer it takes to burn with it on occasion never finishing, the time rises exponentially. I never try and burn more than 80 minutes (not sure it will let you anyway).
Is this a known issue?
I'm using the standard 'burn from playlist' method.
Also sometimes it goes nuts and starts generating random 'time remaining' times, changing every couple of seconds (see below).

A: According to Wikipedia, the original playing time of an audio CD is 74 minutes.
Longer play durations are achieved by "squeezing" the data tracks closer together. Also, because CDs are written from the inside out, the write speed is much faster on the outer sides of the disc — bigger diameter means more distance travelled in the same time.
So squeezing plus faster writing needs more precision. It's likely that an older CD writer will struggle (on a pre-OS-level) with the precision requirements, leading to claims of absurd burning times. I think you will be on the safe side when burning shorter CDs. I hope this helps!


text:
Q: Add SAN or Local disk to already provisioned Server in Softlayer I am new to the softlayer rest APIs. We have a requirement where user will be allowed to add a additional SAN or Local Disk to the existing provisioned server in softlayer. For that I was referring to the REST API guide Our project is build on Ruby on Rails and we are using softlayer_api gem and so I was looking at the api ruby doc. But none of these links helped me. Are there any ruby examples for adding a disk ?

A: Please try the following example to upgrade a Virtual Guest in order to add a disk:
require 'rubygems'
require 'softlayer_api'

# Your SoftLayer API username.
SL_API_USERNAME = 'set me'

# Your SoftLayer API key.
SL_API_KEY = 'set me'

# Set the server id that you wish to upgrade.
server_id = 17850400

# Set the new item price id to upgrade the VSI
price_id = 51733  # 10 GB (SAN) "categoryCode": "guest_disk1", "name": "Second Disk"

# Order Template with all new item configurations
object_template = {'packageId'=> 0,
                   'prices'=> [
                       {
                           'id'=> price_id
                       }
                   ],
                   'virtualGuests'=> [
                       {
                           'id'=> server_id
                       }
                   ],
                   'properties'=> [
                       {
                           'name'=> 'NOTE_GENERAL',
                           'value'=> 'Adding a SAN disk'
                       },
                       {
                           'name'=> 'MAINTENANCE_WINDOW',
                           'value'=> 'now'
                       }
                   ],
                   'complexType'=> 'SoftLayer_Container_Product_Order_Virtual_Guest_Upgrade'
}

softlayer_client = SoftLayer::Client.new(:username => SL_API_USERNAME,
                                         :api_key => SL_API_KEY)
product_order_service = softlayer_client.service_named('SoftLayer_Product_Order')

begin
  result = product_order_service.verifyOrder(object_template)
  puts 'Result:  '
  puts result.inspect
rescue Exception => e
  puts 'Unable to add the new SAN Disk ...'
  $stdout.print(e.inspect)
end

Note: Once your script is ready, please change from verifyOrder to placeOrder.
To get valid prices for upgrade, please review:
SoftLayer_Virtual_Guest::getUpgradeItemPrices
References:
SoftLayer_Product_Order
SoftLayer_Container_Product_Order_Virtual_Guest_Upgrade
upgrade_examples


text:
Q: ASP.NET 5 MVC 6 Beta 8 - Do I have to use kestrel with IIS Express? Working with ASP.NET 5 MVC 6, Beta 8.   Using IIS Express in a local dev windows 10 environment with IE Edge as my browser, but I noticed that IIS Express won't server the page without have a reference to Microsoft.AspNet.Server.Kestrel in my project.
I thought Kestrel was the cross platform web server and not necessarily what you needed to work with IIS Express, so can someone explain why the reference is needed now?

A: Microsoft made changes to the hosting model, because having two different hosting models for IIS introduced inconsistencies.

Hosting ASP.NET 5 applications in IIS will now be achieved using the
  IIS HttpPlatformHandler configured to forward through to the ASP.NET 5
  Kestrel server. The HttpPlatformHandler is a native IIS module that
  needs to be installed by an administrator on the server running IIS.

This blog post describes it further under the headline Changes to IIS Hosting Model.


text:
Q: How to route all VPN traffic via specific hardware interface? I have a computer with two eth interfaces and one wlan interface. It is also connected to a VPN (openvpn), so it has a tun0 interface too. Now, I'd like to make sure that all VPN traffic is sent using the wlan interface, and not over ethernet. By default, it gets sent over eth1, as far as I can see from running iftop. My routing table is below.
$ route
Kernel IP routing table
Destination     Gateway         Genmask         Flags Metric Ref    Use Iface
default         Teltonika.lan   0.0.0.0         UG    100    0        0 eth1
default         192.168.222.1   0.0.0.0         UG    600    0        0 wlan0
link-local      *               255.255.0.0     U     1000   0        0 eth0
172.89.0.0      *               255.255.255.0   U     0      0        0 tun0
192.0.2.1       192.168.222.1   255.255.255.255 UGH   600    0        0 wlan0
192.168.0.0     *               255.255.0.0     U     100    0        0 eth1
192.168.3.0     *               255.255.255.0   U     100    0        0 eth0
192.168.222.0   *               255.255.255.0   U     600    0        0 wlan0

A: On Linux you can adjust the routing rules using ip rule and ip route commands. The latter one is a more advanced equivalent for the route command.
In your case you might obtain the desired behavior by having a separate routing table where the default gateway on wlan0 interface is the only (or anyway preferred) default gateway present, and then set a routing rule stating that all traffic coming from the tun0 interface is to use this separate routing table.
That is obtainable for example through the following two commands:
ip route add default via 192.168.222.1 table 100  # <-- 100 is an arbitrary number for the separate routing table
ip rule add iif tun0 table 100

while to clear them up, use:
ip rule del iif tun0 table 100
ip route flush table 100

You can test the commands live, after establishing the VPN, and see that everything works as intended.
Then you might want to have those commands (or their best equivalent for your overall setup) executed by openvpn when needed. To do so the simplest way is to put those commands in two scripts (respectively), and then call them via OpenVPN's route-up and route-pre-down hooks.
Depending on how you actually use OpenVPN, you need to either run openvpn specifying --route-up script-that-adjusts-routing.sh and --route-pre-down script-that-undoes-routing.sh (and possibly also --script-security 2) from the command line, or add these configurations in the OpenVPN .conf file of your tunnel.
If you already have route-up and route-pre-down scripts, then you need to add the adjusting commands to your pre-existing scripts instead, and this may require additional care depending on what these scripts do.


text:
Q: Get custom post type category and list all posts with the same category The problem I have is as follows:

*

*I have custom post type named 'X'.

*It has few categories named 'Category_1', 'Category_2', 'Category_3'
etc.

*By the logic of my website, one post can only have one category or no category at all.

On page single-x.php (single-posttypename.php) I want to check, if post has a category at all, if it has, I want to get all other posts with the same category, and provide them as a sub-navigation. If post does not have a category just do nothing.

post1

post2

  ...

For the current post, I want to add class active so it would act as a navigation.

A: you can have a check like this
$x= $_POST['x'];
if(isset($x) && $x!='')
{
 $customise_category = $x;
}

else
       {
       $customise_category = '';
       }

you can use this $customise_category where it is needed.


text:
Q: Why is DataStage writing NULL string values as empty strings, while other data types correctly have NULL values I have a DataStage parallel job that writes to Hive as the final stage in a long job. I can view the data that is about to be written and there are many NULL strings that I want to see in the Hive table.
However, when I view the table that is created, there are no NULL strings, they all get converted into empty strings '' instead. I can see other datatypes, like DECIMAL(5,0) have NULL values and I can select these, e.g.
SELECT * FROM mytable WHERE decimal_column IS NULL;
The process for writing to Hive is to store the data in a staging table in a delimited text format. This is then pushed through a generic CDC process and results in data being written to a new partition in an ORC format table.
The only option I can see for handling NULL values is "Null Value" in the HDFS File Connector Stage. If I leave this blank then I get empty strings and if I type in 'NULL' then 'NULL' is what I get, i.e. not a NULL, but the string 'NULL'.
I can't change the process as it's in place for literally thousands of jobs already. Is there any way to get my string values to be NULL or am I stuck with empty strings?

A: According to the IBM documentation, an empty String in double-quotation "" should help.

Null value
Specify the character or string that represents null values in the data. For a source stage, input data that has the value
that you specify is set to null on the output link. For a target
stage, in the output file that is written to the file system, null
values are represented by the value that is specified for this
property. To specify that an empty string represents a null value,
specify "" (two double quotation marks).

Source: https://www.ibm.com/docs/en/iis/11.7?topic=reference-properties-file-connector


text:
Q: Angular add class to component from component css file I want to add a class to my component when I click a button. So I do it with Renderer2 as following:
this.renderer.addClass(this.elRef.nativeElement, 'photo-removing');

The class only applies when I add the css class in a global css file. It doesn't work when I add it to the component css file. Any idea why does this happen?
Update: Here is my component html:

And css:
.photo-removing {
    opacity: 0.4;
    border:1px solid red;
}

A: You can use [ngClass] with *ngIf instead
In .html:
<button (click)="buttonClicked()"></button>

And in .ts file:
export class Home{

  checker:boolean = false;
  constructor(){}

  buttonClicked() {
   this.checker = !this.checker;
  }
}

A: This is a perfect example of when to use [ngClass] directive.
If you're simply using the button to toggle some variable, you can do this...
In your component.ts file:
public clicked: boolean = false;

click() {
     this.clicked ? false : true;
}

In your component.html file:
<button (click)="click()">Set to {{!clicked}}</button>

If you really want to use a renderer, the you need to set this code in your angular app:
encapsulation: ViewEncapsulation.None.

By setting this value to None, you are telling Angular not to encapsulate your views. That way, the default scoping rules, isolations, and protections for styling won't apply. So, Angular adds the CSS to the global styles. This is essentially the same as pasting the component's styles into the HTML.
https://angular.io/api/core/ViewEncapsulation

A: Try:-
Stackblitz Link:- https://stackblitz.com/edit/renderer2-example-2-wdz4og?file=src/app/app.component.css
.html

  test

<button type="button" (click)="addClass()">asasas</button>

.ts
  @ViewChild('test') test: ElementRef;
  imgMainUrl = true;
  constructor(private renderer: Renderer2) { }
  addClass() {
    this.renderer.addClass(this.test.nativeElement, 'photo-removing');
  }


text:
Q: Sort-of-multiplicative functions on the group algebra Let $G$ be a finite group.  Which functions $f:G \to \mathbf{C}$ obey the equation
$$
\sum_{g \in C_1,h \in C_2} f(gh) = \left(\sum_{g \in C_1} f(g) \right)\left(\sum_{h \in C_2} f(h)\right)
$$
for all conjugacy classes $C_1,C_2 \subset G$?  Can you determine all such functions from the character table of $G$?


text:
Q: How to center div when printed I am building a solution that includes printing an invoice out of the web browser. I am willing to live with a few browser quarks.
I would like to make my content center in the printed page instead of on the left side as the browser is wanting to do. I have tried setting right and left margins to auto but to no avail.  I have also tried googling around but based on the very little I was able to find, I'm fearing  that it won't be possible.

A: Use a printing style sheet:
<link rel="stylesheet" type="text/css" media="print" href="print.css" />

Note the media="print".
In print.css, you can add margins and centering and whatnot.

A: I suppose, to make the margin:auto; work, we need to provide approximate width. So, it is rendered at the center.
<style type="text/css">
#content{ margin: 0 auto; width:500px;}
</style>


text:
Q: "How to pass GregorianCalendar class object to a different class method ?"
*

*I want to create a student record using a method that is able to
take input from user about student details . My class Student should
consists of following fields : short semester,
                       full name,
                       registration number etc
    .registration number of a student = concatenation of year and student number.
    Eg year at which student joined = 2023,
       student no. = 80,
       So registration number = 2380

Plus I have been tasked to input date using class GregorianCalendar
INSIDE STUDENT CLASS:
import java.util.*;

class Student2{

    String fullname;
    GregorianCalendar date;
    short semester;

    Student2()
    {

    }

    Student2(String name,short sem, GregorianCalendar Date)
    {
        fullname = name;
        semester=sem;
        date = Date;
    }

    int years = date.get(Calendar.YEAR);

    String year = Integer.toString(years);
    String Studno = Integer.toString(80);

    String y1= year.substring(0,3);
    String Reg = y1.concat(Studno);

    int reg = Integer.parseInt(Reg);

    void Studarry()
    {
         int n=5,i;
         Student2[] stuarry = new Student2[10];
         for(i=0;i<n;i++)
         {
             System.out.println("Enter name sem year month day gpa cgpa\n");
             Scanner sc = new Scanner(System.in);
             String name = sc.nextLine();

             short sem2 = sc.nextShort();
             int year2 = sc.nextInt();
             int month2 = sc.nextInt();
             int day2=sc.nextInt()

             GregorianCalendar gc2 = new GregorianCalendar(year2,month2,day2);

             stuarry[i] = new Student2(name,sem2,gc2);

         }
    }

    void Display()
    {

    }

}

INSIDE DRIVER CLASS:
public class Greg2{

    public static void main(String[] args)
    {
         Student2 starr = new Student2();
         starr.Studarry();
    }

}

ERRORS :

*

*Exception in thread "main" java.lang.NullPointerException
at oop2/lab5.Student2.<init>(Greg2.java:23)

at oop2/lab5.Greg2.main(Greg2.java:68)

A: Class name versus variable name

date = Date;

Date with an uppercase D is the name of a class, not a variable. Instead you should have defined the name of the argument being passed as date not Date. This line becomes date = date ;. The compiler can distinguish between the argument and the member variable. If you want more clarity for the reader, you can say this.date = date ;.
But that is a poor name for a variable. Because there is indeed two classes bundled with Java named Date, both related to GregorianCalendar, I suggest avoiding the use of date as a variable name for GregorianCalendar object – just too confusing.
java.time
The GregorianCalendar is a terrible class. It was supplanted entirely years ago by the java.time classes. Specifically, ZonedDateTime. Both classes represent a moment as seen through the wall-clock time of some particular region (a time zone).
However, both classes are not meant for your purpose. You want only a date, without a time-of-day and without the context of a time zone or offset-from-UTC. So LocalDate fits your needs.
LocalDate ld = LocalDate.of( year , month , day ) ;

Constructor
int years = date.get(Calendar.YEAR);

String year = Integer.toString(years);
String Studno = Integer.toString(80);
…

These lines are floating around, not placed inside a method. They should have been put inside the constructor of your method.
Why is there a class named Greg2? Did you mean a specific student? If so, Greg should be represented by values assigned to an instance of a Student class.
What is with all the 2 characters at the end of names? Naming is important; get that straight and you will be half-way to a solution.
So most of this code is a mess. Try again from scratch. Look up other code examples, such as on Stack Overflow, in the Oracle Tutorial, or in the textbook for your class of this homework assignment.
Learn about separation of concerns. One class should be just about representing a student. Another class should represent your app, and hold the main method. Use a Collection to gather the newly instantiated Student classes into a roster, possibly making a class Roster if you have other roster-related responsibilities.
Lastly, take baby steps. Add one little thing at a time, see that it runs properly. Use System.out.println to verify values. Do not try to write all the code at once.

A: Your NullPointerException comes from this line:
    int years = date.get(Calendar.YEAR);

Field initializers like this one are executed before the constructor. So when you create a Student2 object using new Student2(), the above line is created while the date field is still null, and therefore the call to date.get() throw the exception.
Instead move the initialization of years into the constructor, after you have assigned an object to date.
As others have said too, the GregorianCalendar class is poorly designed and long outdated. If it wasn't for a lazy teacher apperently with no clue of what has been going on with Java the last more than 5 years, you shouldn't use it. Never ever.

A: Mistakes corrected as-
1) Bought field initializers inside my constructor to get rid of NullpointerException as said by ( Basil Bourque , Ole V.V. )
2) created array of student objects in main and called method Stduarry on them .
3) Variable name Date changed to gc
import java.util.*;

INSIDE STUDENT CLASS:
class Student22{

    String fullname;
    GregorianCalendar date;
    short semester;
    int reg;

    Student22()
    {

    }

    Student22(String name,short sem, GregorianCalendar gc)
    {
        fullname = name;
        semester=sem;
        date = gc;

         int years = date.get(Calendar.YEAR);

         String year = Integer.toString(years);
         System.out.println(year);
         String Studno = Integer.toString(80);

         String y1= year.substring(2,4);

         System.out.println(y1);
         String Reg = y1.concat(Studno);
         System.out.println(Reg);

         reg = Integer.parseInt(Reg);
         System.out.println(reg);
    }

     void Studarry(int n)
    {

             System.out.println("Enter name sem year month day \n");
             Scanner sc = new Scanner(System.in);

             fullname = sc.nextLine();
             System.out.println(fullname);

             semester = sc.nextShort();
             int year2 = sc.nextInt();
             int month2 = sc.nextInt();
             int day2=sc.nextInt();

             GregorianCalendar gc2 = new GregorianCalendar(year2,month2,day2);
             date= gc2;

             int years = date.get(Calendar.YEAR);

             String year = Integer.toString(years);
             String Studno = Integer.toString(n);

             String y1= year.substring(0,3);
             String Reg = y1.concat(Studno);

             reg = Integer.parseInt(Reg);

             Display();
     }

    void Display()
    {
         System.out.println(fullname);
         System.out.println(semester);
         System.out.println(reg);
         System.out.println(date.get(Calendar.YEAR));

    }

}

INSIDE DRIVER CLASS:
 public class Greg2{

    public static void main(String[] args)
    {

         System.out.println("Please enter a Firstname , MiddleName & Lastname separated by spaces");
         Scanner sc = new Scanner(System.in);
         String name = sc.nextLine();

         GregorianCalendar gc = new GregorianCalendar(2018,7,22);
         Student22 s = new Student22(name,(short)3,gc);
         s.Display();

         int i,j,n;
         System.out.println("Enter n\n");
         n = sc.nextInt();
         Student22[] starr = new Student22[n+1];
         for(j=1;j<=n;j++)
         {
             starr[j]= new Student22();
             starr[j].Studarry(j);
         }

    }

}


text:
Q: Using Wordpress as a CMS - advice on doing it for localhost? I have a plain-vanilla install of Wordpress on localhost, virtual host in Apache set to:
127.0.0.1 myradiostationhere.com
127.0.0.1 www.myradioanytown.co.uk

and the virtual host works.
However, I don't want to use it as a blog, but as a CMS like here:
http://www.brmb.co.uk/
and
http://www.brmb.co.uk/schedule/
(basically, any pages on that site are database-driven Wordpress pages, not blogs).
I'm not asking how to create pages etc. - I understand that - but rather if anyone knows of the best way to do this.
I'm trying to emulate their look, but with similar CSS stylesheets, as per:

Fair dealing in a work for the purposes of private study or research (s. 29)

under Copyright, Design and Patents Act 1988 (that's the legal bit out the way).
Would I need to edit the PHP files in order to get this to work in the way I intend to?
Anyone here had experience of custom Wordpress CMS design/installs, and how would you recommend I go about this?
(note: This isn't for a live radio station site, it's a development/testing site on localhost!)

A: You basically want to create WordPress theme.
You will need a bit of PHP editing, but mostly of the copy-and-paste variety (to get you started).
Another option is to download a similar free theme or even buy one.


text:
Q: Allow host down while under nagios watch We're using nagios to watch our servers health. Now we have a task to add server which will be up only for certain time. And during that time we have to ensure that all services are up and running. Unfortunately we don't know when will be the host down. So we need some automatic way to achieve this.

*

*Is there a way (configuration directive) to not report if host goes down. I mean even in nagios clients like nagstamon. I don't like the idea of black icon in systray all day.

*Is there a way to not report any of services running on a host, while the host is down?

*While achieving points 1. and 2. is there a way to monitor all host services when and only when the host is up?

A: Let me take the points in the wrong order.
2) NAGIOS should already do this; if a host is down, service alerts will not be sent.
1) I was thinking you could do this with flexible downtime: this is downtime of a given window duration which doesn't start at a known time; instead, the window starts automatically when the host goes down.
But then it occurred to me: all you really need to do is send no alerts when the host is down.  If you manage that, then

*

*When the host is down, service alerts will not be sent.  You don't care that the host is down, because as you say, you don't know when it'll come and go, so the absence of a host alert is immaterial.  The HOST DOWN will still be logged, allowing you to retrospectively see what has gone on, but alerts will not be sent.

*When the host is up, service alerts will be sent anyway.
That's what you want, isn't it?  If so, you need to add to the host definition
notification_options   n

I think that's also dealt with problem 3, as that's what happens normally.  I can't speak for non-core clients like nagstamon.  In my experience, these are usually screen-scrapers, and their decisions about what to notify aren't based on NAGIOS' notification logic.  If your client honours NAGIOS' built-in rules, it should be fine; otherwise, you'll have to work with that particular tool to add a similar logic.

A: You can define custom time periods using the timeperiod definition in your timeperiods.cfg. Here is an example
# Here is a slightly friendlier period during work hours
define timeperiod{
    timeperiod_name workhours
    alias           Standard Work Hours
    monday          09:00-17:00
    tuesday         09:00-17:00
    wednesday       09:00-17:00
    thursday        09:00-17:00
    friday          09:00-17:00
    }

Then use this for the check_period value in your host and service definitions.

A: This answer will not cover third-party monitoring addins like nagstamon or the firefox nagios plugin, because it will vary wildly.
A few ways that I can think of off the top of my head:

*

*Disable host checks for the server. However, this will leave the host in a permanent state of "UP", and services will begin to alert.

*Constantly set floating downtime. Floating downtime starts the next time the host is seen "DOWN" and runs for the duration you specify. You could perhaps do this with a cronjob issuing the "SCHEDULE_HOST_DOWNTIME" for 2 floating hours every two hours. ( See NAGIOS Developer - External Commands ).

*Schedule downtime for the host and all services (see above link).

*What you could also do is put service dependencies to use. If you check the host via PING, then add a PING service, and a service_dependency for all other services on that host to depend on PING, and then shut the ping notifications off. This will look something like;
define servicedependency {
    dependent_host_name             flaky_biscuit
    dependent_service_description   service1, service2, service3, service4, service5
    host_name                       flaky_biscuit
    service_description             PING
    execution_failure_criteria      w,u,c
    notification_failure_criteria   w,u,c
}

What this means in essence is that when PING is in warning, unknown or critical, PING will notify, none of the dependent services will. (And again, shut notifications off for PING!) Also, when PING is in warning, unknown, or critical state, the dependent services will not even execute.
I can't speak for NagStaMon, but the Firefox NAGIOS plugin has preferences that essentially says "ignore acknowledged services", meaning that if you acknowledge or schedule a service in downtime, have notifications off, or any other modification to a service, it will not render as "warning/critical" in the status bar even if it's in that state. I don't know what NagStaMon does or doesn't have in this manner.

A: Here is my idea for using passive checks for this, but I need to state an assumptions first. That you don't want to monitor host uptime at all. Just that when the host is up, that the appropriate services are running.
On your random uptime hosts, you can run something like the following shell script https://gist.github.com/746998. This example would monitor SMTP but it's fairly simple. You will need to have this run as a user that can ssh into your nagios host using a keypair, and securing that is left as an exercise to the reader (or post a new question). I haven't tested this but it should work. The Passive check documentation ( http://nagios.sourceforge.net/docs/3_0/passivechecks.html ) should be helpful.
This won't automate provisioning the hosts on your Nagios server, but you can use something like puppet for that.

A: For alerting you should check out Nagios BPI (Business Process Intelegence) Nagios Enterprises just released this new addon. go to Nagios dot come, and check out there roadmap.