text:
Q: Crawler4j With Grails App I am making a crawler application in Groovy on Grails. I am using Crawler4j and following this tutorial.

*

*I created a new grails project

*Put the BasicCrawlController.groovy file in controllers->package

*Did not create any view because I expected on doing run-app, my crawled data would appear in my crawlStorageFolder (please correct me if my understanding is flawed)

After that I just ran the application by doing run-app but I didn't see any crawling data anywhere.

*

*Am I right in expecting some file to be created at the crawlStorageFolder location that I have given as C:/crawl/crawler4jStorage?

*Do I need to create any view for this?

*If I want to invoke this crawler controller from some other view on click of a submit button of a form, can I just write <g:form name="submitWebsite" url="[controller:'BasicCrawlController ']">?

I asked this because I do not have any method in this controller, so is it the right way to invoke this controller?
My code is as follows:
//All necessary imports

    public class BasicCrawlController {
        static main(args) throws Exception {
            String crawlStorageFolder = "C:/crawl/crawler4jStorage";
            int numberOfCrawlers = 1;
            //int maxDepthOfCrawling = -1;    default
            CrawlConfig config = new CrawlConfig();
            config.setCrawlStorageFolder(crawlStorageFolder);
            config.setPolitenessDelay(1000);
            config.setMaxPagesToFetch(100);
            config.setResumableCrawling(false);
            PageFetcher pageFetcher = new PageFetcher(config);
            RobotstxtConfig robotstxtConfig = new RobotstxtConfig();
            RobotstxtServer robotstxtServer = new RobotstxtServer(robotstxtConfig, pageFetcher);
            CrawlController controller = new CrawlController(config, pageFetcher, robotstxtServer);
            controller.addSeed("http://en.wikipedia.org/wiki/Web_crawler")
            controller.start(BasicCrawler.class, 1);

        }
    }

    class BasicCrawler extends WebCrawler {

    final static Pattern FILTERS = Pattern
    .compile(".*(\\.(css|js|bmp|gif|jpe?g"+ "|png|tiff?|mid|mp2|mp3|mp4" +
             "|wav|avi|mov|mpeg|ram|m4v|pdf" +"|rm|smil|wmv|swf|wma|zip|rar|gz))\$")

    /**
     * You should implement this function to specify whether the given url
     * should be crawled or not (based on your crawling logic).
     */
    @Override
    boolean shouldVisit(WebURL url) {
        String href = url.getURL().toLowerCase()
        !FILTERS.matcher(href).matches() &&       href.startsWith("http://en.wikipedia.org/wiki/Web_crawler/")
    }

    /**
     * This function is called when a page is fetched and ready to be processed
     * by your program.
     */
    @Override
    void visit(Page page) {
        int docid = page.getWebURL().getDocid()
        String url = page.getWebURL().getURL()
        String domain = page.getWebURL().getDomain()
        String path = page.getWebURL().getPath()
        String subDomain = page.getWebURL().getSubDomain()
        String parentUrl = page.getWebURL().getParentUrl()
        String anchor = page.getWebURL().getAnchor()

        println("Docid: ${docid} ")
        println("URL: ${url}  ")
        println("Domain: '${domain}'")
        println("Sub-domain: ' ${subDomain}'")
        println("Path: '${path}'")
        println("Parent page:${parentUrl}  ")
        println("Anchor text: ${anchor} " )

        if (page.getParseData() instanceof HtmlParseData) {
            HtmlParseData htmlParseData = (HtmlParseData) page.getParseData()
            String text = htmlParseData.getText()
            String html = htmlParseData.getHtml()
            List<WebURL> links = htmlParseData.getOutgoingUrls()

            println("Text length: " + text.length())
            println("Html length: " + html.length())
            println("Number of outgoing links: " + links.size())
        }
        Header[] responseHeaders = page.getFetchResponseHeaders()
        if (responseHeaders != null) {
            println("Response headers:")
            for (Header header : responseHeaders) {
                println("\t ${header.getName()} : ${header.getValue()}")
            }
        }
        println("=============")
    }
}

A: I'll try to translate your code into a Grails standard.
Use this under grails-app/controller
class BasicCrawlController {

   def index() {
        String crawlStorageFolder = "C:/crawl/crawler4jStorage";
        int numberOfCrawlers = 1;
        //int maxDepthOfCrawling = -1;    default
        CrawlConfig crawlConfig = new CrawlConfig();
        crawlConfig.setCrawlStorageFolder(crawlStorageFolder);
        crawlConfig.setPolitenessDelay(1000);
        crawlConfig.setMaxPagesToFetch(100);
        crawlConfig.setResumableCrawling(false);
        PageFetcher pageFetcher = new PageFetcher(crawlConfig);
        RobotstxtConfig robotstxtConfig = new RobotstxtConfig();
        RobotstxtServer robotstxtServer = new RobotstxtServer(robotstxtConfig, pageFetcher);
        CrawlController controller = new CrawlController(crawlConfig, pageFetcher, robotstxtServer);
        controller.addSeed("http://en.wikipedia.org/wiki/Web_crawler")
        controller.start(BasicCrawler.class, 1);

        render "done crawling"

    }
}

Use this under src/groovy
class BasicCrawler extends WebCrawler {

final static Pattern FILTERS = Pattern
.compile(".*(\\.(css|js|bmp|gif|jpe?g"+ "|png|tiff?|mid|mp2|mp3|mp4" +
         "|wav|avi|mov|mpeg|ram|m4v|pdf" +"|rm|smil|wmv|swf|wma|zip|rar|gz))\$")

/**
 * You should implement this function to specify whether the given url
 * should be crawled or not (based on your crawling logic).
 */
@Override
boolean shouldVisit(WebURL url) {
    String href = url.getURL().toLowerCase()
    !FILTERS.matcher(href).matches() &&       href.startsWith("http://en.wikipedia.org/wiki/Web_crawler/")
}

/**
 * This function is called when a page is fetched and ready to be processed
 * by your program.
 */
@Override
void visit(Page page) {
    int docid = page.getWebURL().getDocid()
    String url = page.getWebURL().getURL()
    String domain = page.getWebURL().getDomain()
    String path = page.getWebURL().getPath()
    String subDomain = page.getWebURL().getSubDomain()
    String parentUrl = page.getWebURL().getParentUrl()
    String anchor = page.getWebURL().getAnchor()

    println("Docid: ${docid} ")
    println("URL: ${url}  ")
    println("Domain: '${domain}'")
    println("Sub-domain: ' ${subDomain}'")
    println("Path: '${path}'")
    println("Parent page:${parentUrl}  ")
    println("Anchor text: ${anchor} " )

    if (page.getParseData() instanceof HtmlParseData) {
        HtmlParseData htmlParseData = (HtmlParseData) page.getParseData()
        String text = htmlParseData.getText()
        String html = htmlParseData.getHtml()
        List<WebURL> links = htmlParseData.getOutgoingUrls()

        println("Text length: " + text.length())
        println("Html length: " + html.length())
        println("Number of outgoing links: " + links.size())
    }
    Header[] responseHeaders = page.getFetchResponseHeaders()
    if (responseHeaders != null) {
        println("Response headers:")
        for (Header header : responseHeaders) {
            println("\t ${header.getName()} : ${header.getValue()}")
        }
    }
    println("=============")
  }
}


text:
Q: how to detect file change VBS i want to make a Visual basic script console app that prints edited if a file has been modified. for example if i have a text file with some notes in and i add it to a folder when its edited the program checks the folder its in and the files then prints the name of the file and modified or not modified
how would i go about doing this i am relatively new to Visual basic script i probably have 4 months basic experience.
    console.writeline("what do i do?")
    console.writeline("and how do i do it")

and I'm trying to do it as a console app so the preferred outcome i would like to see would be
    File Checker
    test.txt - Edited
    test2.pptx - Un-edited
    etc etc etc

A: If you need an immediate notification, WMI is probably the best route. But WMI will also require your process to be running (in a blocked state) all of the time. Alternatively, you could schedule a VBScript to be launched at some interval and it could check each file's last-modified date against a text file or database that you use to store the modification date the last time the script was run.
An even easier solution would be to just check if the modification time changed since the last run. For example, if your script runs every 10 minutes and you discover a file that was changed within the last 10 minutes, report it.
With CreateObject("Scripting.FileSystemObject")
    For Each File In .GetFolder("c:\folder").Files
        If DateDiff("n", File.DateLastModified, Now) < 10 Then
            ' File has been modified in past 10 minutes.
        End If
    Next
End With

redpajama_set_name: RedPajamaStackExchange


text:
Q: How can I add button on notification FCM Android How I add button on notification FCM and how I add click event on that buttons. I need two buttons on notification
How I add click event on button on notification FCM Android like this image Dismiss and Answer

public class MyFirebaseMessagingService extends FirebaseMessagingService {

    private static final String TAG = "FCM Service";

    @Override
    public void onMessageReceived(RemoteMessage remoteMessage) {
        // TODO: Handle FCM messages here.
        Log.d(TAG, "From: " + remoteMessage.getFrom());
        Log.d(TAG, "Notification Message Body: " + remoteMessage.getNotification().getBody());
        createNotification(remoteMessage.getNotification().getBody());
    }

    private void createNotification( String messageBody) {
        Intent intent = new Intent( this , ResultActivity. class );
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        PendingIntent resultIntent = PendingIntent.getActivity( this , 0, intent, PendingIntent.FLAG_ONE_SHOT);

        Intent intent1 = new Intent(this, ResultActivity.class);
        PendingIntent resultIntents = PendingIntent.getActivity( this , 0, intent1, PendingIntent.FLAG_ONE_SHOT);

        Uri notificationSoundURI = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
        NotificationCompat.Builder mNotificationBuilder = new NotificationCompat.Builder(this)
                .setSmallIcon(R.mipmap.ic_launcher)
                .setContentTitle("Android Tutorial Point FCM Tutorial")
                .setContentText(messageBody)
                .setDefaults(Notification.DEFAULT_ALL)
                .setPriority(NotificationCompat.PRIORITY_HIGH)
                .setAutoCancel(true)
                .addAction(R.drawable.switches, "Hello", resultIntents)
                .addAction(R.drawable.call, "Call", resultIntent)
                .setSound(notificationSoundURI)
                .setContentIntent(resultIntent);
        NotificationManager notificationManager =
                (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
        notificationManager.notify(0, mNotificationBuilder.build());
    }
}

public class FirebaseIDService extends FirebaseInstanceIdService {
    private static final String TAG = "FirebaseIDService";

    @Override
    public void onTokenRefresh() {
        // Get updated InstanceID token.
        String refreshedToken = FirebaseInstanceId.getInstance().getToken();
        Log.d(TAG, "Refreshed token: " + refreshedToken);

        // TODO: Implement this method to send any registration to your app's servers.
        sendRegistrationToServer(refreshedToken);
    }

    private void sendRegistrationToServer(String token) {
        // Add custom implementation, as needed.
    }
}

A: From API level 4.1 you can add action buttons to notification. To see the basics about notification check the android doc
and for some more help you can check this so answer and this tutorial
//Here in intent your will need provide the class which you want to open on button click in notification
Intent intent = new Intent(this, NotificationReceiverActivity.class);
PendingIntent pIntent = PendingIntent.getActivity(this, (int) System.currentTimeMillis(), intent, 0);

// Build notification
// Actions are just fake
Notification noti = new Notification.Builder(this)
        .setContentTitle("New mail from " + "test@gmail.com")
        .setContentText("Subject").setSmallIcon(R.drawable.icon)
        .setContentIntent(pIntent)
        .addAction(R.drawable.icon, "Call", pIntent)
        .addAction(R.drawable.icon, "More", pIntent)
        .addAction(R.drawable.icon, "And more", pIntent).build();

A:     NotificationCompat.Builder builder = new NotificationCompat.Builder(this)
            // Set Icon
            .setSmallIcon(R.drawable.icon)
            // Set Ticker Message
            .setTicker("notification received")
            // Dismiss Notification
            .setAutoCancel(true)
            //.setWhen(0)
            // Set PendingIntent into Notification
            .setContentIntent(pIntent)
            // Set RemoteViews into Notification
            // .setContent(remoteViews)
            // Set Title
            .setContentTitle("App")
            // show big notification hint when app is open
            //.setPriority(Notification.PRIORITY_MAX)
            // Set Text
             .setContentText(messageBody)
            // Set Sound
            .setSound(defaultSoundUri)
            // notification button 1
            .addAction(viewAction)
            // notification button 2
            .addAction(rejectAction)
            // notification button 3
            .addAction(approveAction);

Here I have added 3 buttons as ".addAction". We can give individual actions for every button it is as follows
    NotificationCompat.Action viewAction = new NotificationCompat.Action.Builder(R.drawable.view_icon, "View", viewIntentPending).build();


text:
Q: Naive Bayes Classifier for Disease recognition won't work i was trying out a naive bayes algorithm i found on github and i cant seem to make it work
the modification that i made to the code was changing a code from "lines = file.next().split(",")" to "lines = next(file).split(",")"
import json,os,sys,re
from naiveBayesClassifier import tokenizer
from naiveBayesClassifier.trainer import Trainer
from naiveBayesClassifier.classifier import Classifier
##IMPORTS

'''
Usage:

    python GuessDisease.py "symptomA symptomB symptomC"
Example INPUT:
    python GuessDisease.py "agitation exhaustion vomit"
Example OUTPUT:

    {
    "disease": "influenza"
    }

'''

##SETTING UP
diseaseclassifier = Trainer(tokenizer) #STARTS CLASIFIERS
with open("Dataset.csv", "r") as file: #OPENS DATASET
    for i in file: #FOR EACH LINE
       lines = next(file).split(",") #PARSE CSV <DISEASE> <SYMPTOM>
       diseaseclassifier.train(lines[1],  lines[0]) #TRAINING
diseaseclassifier = Classifier(diseaseclassifier.data, tokenizer)
classification = diseaseclassifier.classify(sys.argv[1]) #CLASIFY INPUT
print (classification[0]) #PRINT CLASIFICATION

here are some of the datasets:
hypertensive disease,pain chest
hypertensive disease,shortness of breath
hypertensive disease,dizziness
hypertensive disease,asthenia
hypertensive disease,fall
hypertensive disease,syncope
hypertensive disease,vertigo
hypertensive disease,sweat sweating increased
hypertensive disease,palpitation
hypertensive disease,nausea
hypertensive disease,angina pectoris
hypertensive disease,pressure chest
diabetes,polyuria
diabetes,polydypsia
diabetes,shortness of breath
diabetes,pain chest
diabetes,asthenia
diabetes,nausea
diabetes,orthopnea
diabetes,rale
diabetes,sweat sweating increased
diabetes,unresponsiveness
diabetes,mental status changes
diabetes,vertigo
diabetes,vomiting
diabetes,labored breathing
"depression mental , depressive disorder",feeling suicidal
"depression mental , depressive disorder",suicidal
"depression mental , depressive disorder",hallucinations auditory
"depression mental , depressive disorder",feeling hopeless
"depression mental , depressive disorder",weepiness
"depression mental , depressive disorder",sleeplessness
"depression mental , depressive disorder",motor retardation
"depression mental , depressive disorder",irritable mood
"depression mental , depressive disorder",blackout
"depression mental , depressive disorder",mood depressed
"depression mental , depressive disorder",hallucinations visual
"depression mental , depressive disorder",worry
"depression mental , depressive disorder",agitation
"depression mental , depressive disorder",tremor
"depression mental , depressive disorder",intoxication
"depression mental , depressive disorder",verbal auditory hallucinations
"depression mental , depressive disorder",energy increased
"depression mental , depressive disorder",difficulty
"depression mental , depressive disorder",nightmare
"depression mental , depressive disorder",unable to concentrate
"depression mental , depressive disorder",homelessness
"coronary arteriosclerosis ,coronary heart disease",pain chest
"coronary arteriosclerosis ,coronary heart disease",angina pectoris
"coronary arteriosclerosis ,coronary heart disease",shortness of breath
"coronary arteriosclerosis ,coronary heart disease",hypokinesia
"coronary arteriosclerosis ,coronary heart disease",sweat sweating increased
"coronary arteriosclerosis ,coronary heart disease",pressure chest
"coronary arteriosclerosis ,coronary heart disease",dyspnea on exertion
"coronary arteriosclerosis ,coronary heart disease",orthopnea
"coronary arteriosclerosis ,coronary heart disease",chest tightness
pneumonia,cough
pneumonia,fever
pneumonia,decreased translucency
pneumonia,shortness of breath
pneumonia,rale
pneumonia,productive cough
pneumonia,pleuritic pain
pneumonia,yellow sputum
pneumonia,breath sounds decreased
pneumonia,chill
pneumonia,rhonchus
pneumonia,green sputum
pneumonia,non-productive cough
pneumonia,wheezing
pneumonia,haemoptysis
pneumonia,distress respiratory
pneumonia,tachypnea
pneumonia,malaise
pneumonia,night sweat
failure heart congestive,shortness of breath
failure heart congestive,orthopnea
failure heart congestive,jugular venous distention
failure heart congestive,rale
failure heart congestive,dyspnea
failure heart congestive,cough
failure heart congestive,wheezing
accident cerebrovascular,dysarthria
accident cerebrovascular,asthenia
accident cerebrovascular,speech slurred
accident cerebrovascular,facial paresis
accident cerebrovascular,hemiplegia
accident cerebrovascular,unresponsiveness
accident cerebrovascular,seizure
accident cerebrovascular,numbness
asthma,wheezing
asthma,cough
asthma,shortness of breath
asthma,chest tightness
asthma,non-productive cough
asthma,pleuritic pain
asthma,productive cough
asthma,symptom aggravating factors
asthma,distress respiratory
myocardial infarction,pain chest
myocardial infarction,st segment elevation
myocardial infarction,sweat sweating increased
myocardial infarction,shortness of breath
myocardial infarction,st segment depression
myocardial infarction,hypokinesia
myocardial infarction,angina pectoris
myocardial infarction,pressure chest
myocardial infarction,t wave inverted
myocardial infarction,orthopnea
myocardial infarction,rale
myocardial infarction,chest tightness
myocardial infarction,presence of q wave
myocardial infarction,palpitation
myocardial infarction,dyspnea
myocardial infarction,chest discomfort
myocardial infarction,bradycardia
myocardial infarction,syncope
hypercholesterolemia,pain
hypercholesterolemia,pain chest
hypercholesterolemia,sweat sweating increased
hypercholesterolemia,nonsmoker
hypercholesterolemia,pressure chest
hypercholesterolemia,syncope
hypercholesterolemia,numbness
hypercholesterolemia,chest discomfort
hypercholesterolemia,shortness of breath
hypercholesterolemia,st segment depression
hypercholesterolemia,worry
hypercholesterolemia,t wave inverted
hypercholesterolemia,bradycardia
hypercholesterolemia,dyspnea
infection,fever
infection,erythema
infection,decreased translucency
infection,hepatosplenomegaly
infection,chill
infection,pruritus
infection,diarrhea
infection,abscess bacterial
infection,swelling
infection,pain
infection,apyrexial
infection,cough
infection urinary tract,fever
infection urinary tract,dysuria
infection urinary tract,hematuria
infection urinary tract,renal angle tenderness
infection urinary tract,lethargy
infection urinary tract,asthenia
infection urinary tract,hyponatremia
infection urinary tract,hemodynamically stable

the program runs fine but the output is always the same


text:
Q: Unable to use on click function on list element within modal I am trying to make list elements in a bootstrap modal clickable.
My modal has the ID: crModal, My list has the id crtList and my elements have the class CRT.
I am using this script to activate a function when an element is clicked
$("#crtList").on("click", "li.CRT", function(event){
    alert("It worked")
});

For some reason this script isn't activating when I click an element of the list within the modal

A: You're correct in that you need to use a delegated event handler as the modal is dynamically created in the page. However the event needs to be bound to an element that exists in the DOM when the page loads. Given that you state #crtList is part of the modal this would seem to not be the case.
To fix this you can change $('#crtList') to $(document) to get the code working:
$(document).on("click", "li.CRT", function(event){
  console.log("It worked")
});


text:
Q: Как правильно использовать asyncgur в python? Пытаюсь загрузить на фотохостинг картинку с компьютера, но при её передаче возникает ошибка:
Возникло исключение: TypeError
Can not serialize value type: <class 'NoneType'>
 headers: {}
 value: None

Код который использую:
from asyncgur import Imgur
from os import getcwd
import asyncio

client_id = 'your client id'
imgur_app = Imgur(client_id)

async def main():
    f = open(getcwd() + '\\' + '434312.jpg', 'rb')
    image, response = await imgur_app.upload_image(image=f.read()) # тут ошибка
    assert response.success == True and response.status == 200
    print(image)

loop = asyncio.get_event_loop()
loop.run_until_complete(main())

Ссылка на библиотеку, которую пытаюсь использовать - https://pypi.org/project/asyncgur/
В документации написано, что можно передать ссылку либо байты фотографии, с ссылкой работает всё на отлично, но с байтами - нет.
Полная ошибка:
Возникло исключение: TypeError
Can not serialize value type: <class 'NoneType'>
 headers: {}
 value: None

During handling of the above exception, another exception occurred:

The above exception was the direct cause of the following exception:

  File "C:\Users\Maxim\Desktop\upp.py", line 10, in main
    image, response = await imgur_app.upload_image(image=f.read())
  File "C:\Users\Maxim\Desktop\upp.py", line 15, in <module>
    loop.run_until_complete(main())


text:
Q: My website won't let me scroll down far enough, cuts off part of an image I'm working on making myself a personal website and on one of my tabs I have a png of my resume.  The problem is only about the top 2/3 of the png is actually visible. I've tried messing with the height and overflow and a few other things of body and that img but I can't seem to fix it or find anything on the web.  I know it's probably something simple but I can't figure it out and its getting frustrating. Here is a link to my site http://adamphillips.us
Here is my code for the png:

      Download my resume as a PDF file.

And Here is my css for it:
.resume img {
    width: calc(100% - 60px);
    margin-top: 10px;
    border: medium solid black;
}

A: do it...you can change in this class from old height to this new height

.clear-backend{
    height: 1550px;
}

A: Your
 has overflow:hidden. As the name suggests, this will hide the overflow. Delete overflow and the page will let you scroll down to see the rest of the image.

A: this will work fine. try it
.resume{
        height: 1650px;
        overflow-y: scroll;
}

A: Whenever you start designing your page(using CSS). Always give some properties to body.
So the actual reason here is you have overflow:hidden for .tab-content and no height property given to body.
To Do:
i) Add 2 properties to body.
ii) Remove 1 property from .tab-content.
Try this and it will work like charm.
body
{
    height:auto;
    overflow-x:hidden;
}

.tab-content
{
    position: absolute;
    top: 0;
    right: 0;
    width: calc(100% - 200px);
    height: 100%;
    padding-top: 60px;
    /* JUST REMOVE OVERFLOW PROPERTY
    overflow:hidden
    */
}


text:
Q: Should flags only be binary? I may be erring towards pedantry here, but say I have a field in a database that currently has two values (but may contain more in future). I know I could name this as a flag (e.g. MY_FLAG) containing values 0 and 1, but should more values be required (e.g. 0,1,2,3,4), is it still correct to call the field a flag?
I seem to recall reading something previously, that a flag should always be binary, and anything else should be labelled more appropriately, but I may be mistaken. Does anyone know if my thinking is correct? If so, can you point me to any information on this please? My googling has turned nothing up!!
Thanks very much :o)

A: Flags are usually binary because when we say flag it means either it is up(1) or down(0).
Just like it is used in military to flag up and down in order to show the war-signs. The concept of flagging is taken from there.
Regarding what you are saying
"your words : values be required (e.g. 0,1,2,3,4)"

In such a situation use Enum. Enumerations are build for such cases or sometimes what we do is , we justify the meaning of these numeric values in comments or in separate file so that more memory could be saved(we use tinyInt or bit field). But never name such a situation Flag.
Flags have standard meaning that is either Up or Down. It doesn't mean that you will get error or something but it is not a good practice. Hope you get it.

A: It's all a matter of conventions and the ability to maintain your database/code effectively. Technically, you can have a column called my_flag defined as a varchar and hold values like "batman" and "barak obama".
By convention, flags are boolean. If you intend to have other values there, it's probably a better idea to call the column something else, like some_enum, or my_code.

A: Very occasionally, people talk about (for example) tri-state flags, but Wikipedia and most of the dictionary definitions that I read reserve "flag" for binary / two state uses1.
Of course, neither Wikipedia or any dictionary has the authority to say some English usage is "incorrect".  "Correct" usage is really "conventional" usage; i.e. what other people say / write.
I would argue that saying or writing "tri-state flag" is unconventional, but it is unambiguous and serves its purpose of communicating a concept adequately.  (And the usage can be justified ...)

1 - Most, but not all; see http://www.oxforddictionaries.com/definition/english/flag.

A: Don't call anything "flag". Or "count" or "mark" or "int" or "code". Name it like everything else in code: after what it means.
workday {mon..fri}
tall {yes,no}
zip_code {00000..99999}
state {AL..WY}

Notice that (something like) yes/no plays the 'flag' role of indicating a permanent dichotomy. (In lieu of boolean, which does that in the rest of the universe outside SQL). For when the specification/contract really is whether something is so. If a design might add more values you should use a different type.
Of course if you want to add more info to a name you can. Add distinctions that are meaningful if you can.
workday {monday..friday}
workday_abbrev {mon..fri}
is_tall {yes,no}
zip_plus_5 {00000-99..99999-99}
state_name {Alabama..Wyoming}
state_2 {AL..WY}


text:
Q: Is it important to have common ground between you microcontoller and high-power devices on the same PCB? I noticed that there are more N-channel mostfets than P-channel mosfets on the market.
Then I realised that probably in many applications, the high powered device runs on a higher voltage and therefore a P-channel mosfet cannot be used.
An N-channel mostfet connects the ground lines of the high-power device to ground. However this is not "common" ground. Its ground + the potential of the mosfet.
I actually have a lot of components (all 5V) to be controlled by one MOSFET switch including digital logic. I need this to isolate out that part of the board when my board is only being powered by PC USB. (ie: 500mA limited, and this part of the board draws 1.5A and should only work when on USB charger)
I was thinking of putting in a P-channel mosfet into my design so that my microcontroller is controlling the highrail of my high-powered device (a light, a motor, etc), rather than the ground rail. It feels like that would make sense because then one maintains a solid ground plane on the entire board. Perhaps this is not as important as I was lead to beleive in school?

A: I think we'd need to see the exact situation you're thinking about to give you a real answer, but in general,

*

*getting the grounding scheme right can be VERY important, and

*Sometimes getting the grounding scheme right can mean separating your grounds, or even isolating part of your circuit such that one part does not share a common ground with the rest of your circuit.


text:
Q: Element.shadowRoot in firefox How can we workaround Element.shadowRoot in Firefox since it is not available yet ?
About Element.shadowRoot
https://developer.mozilla.org/en-US/docs/Web/API/Element/shadowRoot

A: You need to load the polyfills. But the shadowDOM Polyfill comes with some limitations.
Personally I don't use shadowDOM yet unless I know I am going Chrome only.
I am waiting for all of the major browsers to support it in their current version and previous version before I start using it all the time. That is probably a year to 18 months out.
Here is info on the polyfills: https://www.webcomponents.org/polyfills


text:
Q: public variables - need of properties C#
Possible Duplicate:
C#: Public Fields versus Automatic Properties

I read properties in C# are declared or used to provide access of private members to others. In that case, when we are declaring public members, do we still have to declare properties for them.
In the following example, they have declared properties for public members. I don't know why ?
class Customer
{
     public double TotalPurchases { get; set; }
     public string Name { get; set; }
     public int CustomerID { get; set; }
}

thanks!

A: Using properties instead of public fields allows non-breaking changes in how these properties are implemented in the next release - with public fields any change is breaking.
For example you could change the implementation of TotalPurchases to perform a calculation instead of returning the value of a backing field directly. From the point of view of the consumer of the class this change is non-breaking and does not affect how your application works.
 public double TotalPurchases
 {
   get
   {
     return CalculatePurchases();
   }
 }

A: This article gives you a good overview to properties and its overuse
http://www.codinghorror.com/blog/2006/08/properties-vs-public-variables.html

A: So first of all, properties in C# are declared for many reasons, and it's not about being private at all.
You can, for example, make the getter public and the setter private:
public double TotalPurchases
{
   get;
   private set;
}

Also, for some frameworks backed up by reflection, they look for properties and not fields.
In this case, properties are a must, even if it looks useless when nothing is done in the getter/setter.


text:
Q: How to filter accelerometer+magnetometer orientation from sensors? I'm using Kotlin. I just tried to get orientation from device sensors just like Google advice:
https://developer.android.com/guide/topics/sensors/sensors_position#sensors-pos-orient
But when i try to visualize it my azimuth orientationAngles[0] rattling and values are jumping with margin of error in 10-15 degrees. Can we filter this values somehow? I found Kalman filter but it is hard and i didn't find any references on Kotlin


text:
Q: English Subject-auxiliary inversion In normal declarative English sentences, let's call them 'canonical' sentences, the verb comes after the subject.

*

*Bob is walking the Great Wall of China.

*Bob likes elephants.

But in other types of construction and in certain other situations the auxiliary verb comes before the subject. One notable instance is in questions:

*

*Is Bob walking the Great Wall of China?

Here we se the auxiliary verb BE occurring before the Subject. If there is no auxiliary verb in the normal declarative version of the sentence then we need to insert the auxiliary DO:

*

*Does Bob like elephants?

My question here is twofold. Firstly:

*

*What are the different constructions or environments in which  either we require subject-auxiliary inversion in modern English, or can optionally use it?*

Secondly, and more importantly:

*Is there any generalisaton we can make about these constructions. Does subject-auxiliary inversion have some kind of meaning in all of these, or a subset of these?

*Not including poetry, for obvious reasons.

A: The only time outside of poetry that I can think of where it is not optional would be in the so-called tag question.

Bob likes elephants, doesn't he?

A: Offhand, I can only think of two, uh, constructions ... or environments:

Not only did they dislike verismo opera intensely, they weren't even
  remotely interested in music as an art form.

And this, from Robert Louis Stevenson's Heather Ale:

The king rode, and was angry.
  Black was his brow and pale:
  To rule in a land of heather
  And lack the Heather Ale.

A:
Bob likes elephants.

Sure, this is in canonical order with an S/V/O pattern.   It's also indicative and declarative.

Does Bob like elephants?

This isn't declarative.   It's interrogative.

Should Bob like elephants, we can plan a visit to the zoo.

This isn't indicative, although it might not be fashionable to call it subjunctive anymore.

Not only does Bob like elephants, he practically worships them.

This still feels indicative and declarative, but the entire clause is negated from the outside.   It's not as straightforward an indicative declaration as it is when it stands on its own.   If the clause including its external negation seems indicative, then the clause per se, excluding that qualification, may well be something else.

One thing that traditional grammar gets wrong is the way it lumps its declarative/interrogative distinction in along with its indicative/subjunctive distinction.   There's a tangle of two or three orthogonal properties that are traditionally labeled mode: indicative, interrogative, subjunctive, exclamatory and imperative are values that all leap to mind.
Something pulled that snarl together.   This inversion marks some non-default value in that tangled mess.   Do I think that it's a likely candidate?   Do I ever!


text:
Q: MySQL GROUP BY with subquery (ies) I'm trying to count the number of orders in a date range, grouping by date but also counting some other records which occurred on the same date.
I have a query which looks something like this:
SELECT
order_date,
DATE_FORMAT(order_date,'%W') AS day,
DATE_FORMAT(order_date,'%d-%m-%Y') AS orderdate,
COUNT(orderID) As orders,
a.something AS something
b.something AS something_else,
a.something + b.something AS total_somethings
FROM orders,
(SELECT COUNT(*) AS something FROM other_table) AS a,
(SELECT COUNT(*) AS something FROM another_table) AS b,
GROUP BY order_date
HAVING order_date >= '2014-01-01' AND order_date <= '2014-01-31'
ORDER BY order_date ASC

It works OK but obviously, the subqueries count every single row.  The tables 'other_table' and 'another_table' both have date fields which I would like to use to limit the results for each row.
I tried changing the subqueries to something like :
(SELECT COUNT(*) AS something FROM other_table WHERE date_field = order_date) AS a,

but it's still counting every single row.
Any advice appreciated.
Thanks

A: In the following query, I grouped the date_field in other_table and another_table tables. Then, I joined with the orders table using the date_field. Does the following query work for you?
SELECT
order_date,
DATE_FORMAT(order_date,'%W') AS day,
DATE_FORMAT(order_date,'%d-%m-%Y') AS orderdate,
COUNT(orderID) As orders,
a.something AS something
b.something AS something_else,
a.something + b.something AS total_somethings
FROM orders,
(SELECT date_field, COUNT(*) AS something FROM other_table GROUP BY date_field) AS a,
(SELECT date_field, COUNT(*) AS something FROM another_table GROUP BY date_field) AS b
WHERE order_date >= '2014-01-01' AND order_date <= '2014-01-31'
AND order_date = a.date_field AND order_date = b.date_field
GROUP BY order_date
ORDER BY order_date ASC;


text:
Q: Can I share same application files between multiple applications where only web.config is different? I have multiple applications on the same server where only some sections of web config are different. Since everything else is the same; is it possible to map somehow the aspx and other files and to have the single app to share the common files? This will make much easier to manage (es update a file)

A: In general you might want to use continuous deployment to minimize the effort of updating web apps, see this question for an example.
You could try using symbolic links to handle the duplicate files, see the following answers for futher information: https://stackoverflow.com/a/3070093, https://stackoverflow.com/a/51679624.

A: In my opinion, if you want to make much easier to manage (es update a file, I suggest you could write web deploy command line to deploy the web application to the multiple web sites at once.
I don't suggest you share the files for mutiple IIS server.
Details about how to achieve write web deploy command line to deploy the web application to the multiple web sites at once, I suggest you could refer to this article.

A: You write the settings in "ini" text file in App_Data folder.
For example, if you have the following sub domains which use the same application folder:
http://sub1.myweb.com
http://sub2.myweb.com
http://sub3.myweb.com

Then you can store the settings or configuration parameters in following folders:
/root/App_Data/sub1/settings.ini
/root/App_Data/sub2/settings.ini
/root/App_Data/sub3/settings.ini

Then, in the Global.asax in Application_Start, where your site starts, load the settings from the App_Data sub-folder into a public static class file.
Besides, storing files in App_Data/Sub-folder, you can also store it in a separated database which stores all settings for different sub-domain.

update 2
All the apps can be identified with their sub-domain, therefore you can write a function to get the sub-domain, for example:
string[] sa = HttpContext.Current.Request.Url.Host.Split('.');
string SubDomain = sa[0];

You may wrap it in a class:
public class config
{
    private static string _subdomain = null;
    public static string SubDomain
    {
        get
        {
            if (_subdomain == null)
            {
                string[] sa = HttpContext.Current.Request.Url.Host.Split('.');
                _subdomain = sa[0];
            }
            return _subdomain;
        }
    }
}

This will allow you to obtain the Sub-Domain like this:
config.SubDomain

Next, is the physical file path of the settings file:
HttpContext.Current.Server.MapPath($"~/App_Data/{config.SubDomain}/settings.ini");

Assume this is your settings class object:
public class AppSettings
{
    public string BranchOfficeName { get; set; }
    public string ManagerName { get; set; }
    public string Address { get; set; }
    public DateTime ExpiryDate { get; set; }
    public int MemberLimit { get; set; }
}

You can load the settings like this:
private static AppSettings _appset = null;
public static void LoadSettings()
{
    string settingsFilePath = HttpContext.Current.Server.MapPath($"~/App_Data/{config.SubDomain}/settings.ini");
    _appset = ConvertIniToClassObject(settingsFilePath);
}

Make it as a public static object:
private static AppSettings _appset = null;
public static AppSettings Settings
{
    get
    {
        if (_appset == null)
        {
            LoadSettings();
        }
        return _appset;
    }
}

public static void LoadSettings()
{
    string settingsFilePath = HttpContext.Current.Server.MapPath($"~/App_Data/{config.SubDomain}/settings.ini");
    _appset = ConvertIniToClassObject(settingsFilePath);
}

Therefore, in your Global.Application_Start, load the settings:
public class Global : System.Web.HttpApplication
{
    protected void Application_Start(object sender, EventArgs e)
    {
        config.LoadSettings();
    }
}

Then in the rest of your application, you may call the settings parameters something like this:
string output = $@"

{config.Settings.BranchOfficeName}

Manager: {config.Settings.ManagerName}

Address: {config.Settings.Address}

Sub-Domain: {config.SubDomain}
";
HttpContext.Current.Response.Write(output);

Below is an example of saving the settings file:
public static void SaveSettings()
{
    string ini = ConvertObjectToIni(_appset);
    string settingsFilePath = HttpContext.Current.Server.MapPath($"~/App_Data/{config.SubDomain}/settings.ini");
    System.IO.File.WriteAllText(settingsFilePath, ini);
}

Therefore, in the application, just call:
config.SaveSettings();

Besides storing settings in physical ini file, you can also store it in database:
SELECT * FROM appsettings WHERE subdomain={config.SubDomain}

The key point here is config.SubDomain. Therefore, beside settings, you can now store other files separately according to the sub-domain, for example:
/images/{config.SubDomain}/logo.jpg
/files/{config.SubDomain}/rules.pdf

well, you get the idea.


text:
Q: Change XML opener(reader) to JSON I have followed a good tutorial that shows how to make an Automation Framework in C# Selenium.
The config file is in XML at the moment, but I wanted some more practice and change it to a .json file.
At the moment we are using the namespace System.Xml.XPath; and my question is, are there a similar for JSON? Lets say "System.Json;" that works the same as my XML reader. So I don't need to refactor to much code, or is it unavoidably?
This is how it works at the moment.
//Initialize
ConfigReader.SetFrameworkSettings();

public class ConfigReader
{

        public static void SetFrameworkSettings()
        {
            XPathItem aut;

            string strFilename = Environment.CurrentDirectory.ToString() + "\\Config\\GlobalConfig.xml";
            FileStream stream = new FileStream(strFilename, FileMode.Open);
            XPathDocument document = new XPathDocument(stream);
            XPathNavigator navigator = document.CreateNavigator();

            //Get XML Details and pass it in XPathItem type variables
            aut = navigator.SelectSingleNode("AutoFramework/RunSettings/AUT");
            Settings.AUT = aut.Value.ToString();
        }
    }

public class Settings
{
    public static string AUT { get; set; }
}

Would be awesome if you could just change this two lines
XPathDocument document = new XPathDocument(stream);
XPathNavigator navigator = document.CreateNavigator()

And the XpathItem
Cheers

A: I would recommend using Newtonsoft.Json which is available from Nuget.
To "reuse" your current code you would have to make some basic SettingsConverter first:
public static class SettingsConverter
{
    public static string FromXmlToJson(string xml)
    {
        Settings settings = null;
        // read your xml file and assign values to the settings object
        // now you can "serialize" settings object into Json
        return JsonSerialization.Serialize(settings);
    }

    public static string FromJsonToXml(string json)
    {
        Settings settings = JsonSerialization.Deserialize<MeSettings>(json);
        // save settings using your "xml" serialization
        return xmlString; // return xml string
    }
}

To use these methods I'm using this JsonSerialization helper class :
public static class JsonSerialiation
{
    public static string Serialize<T>(T obj)
    {
        using (MemoryStream stream = new MemoryStream())
        {
            using (JsonTextWriter writer = new JsonTextWriter(new StreamWriter(stream))
            {
                JsonSerializer serializer = new JsonSerializer();
                serializer.Serializer(writer, obj);
                writer.Flush();
                stream.Position = 0;
                using (StreamReader reader = new StreamREader(stream))
                {
                    return reader.ReadToEnd();
                }
            }
        }
    }

    public static T Deserialize<T>(string jsonString)
    {
        using (JsonTextReader reader = new JsonTextReader(new StringReader(str)))
        {
            JsonSerializer serializer = new JsonSerializer();
            return serializer.Deserialize<T>(reader)
        }
    }
}

Above example requires from you to change your Settings class from static :
public class Settings
{
    public static string AUT { get; set; }
}

To instance :
public class Settings
{
    public string AUT { get; set; }
}

If you prefer to keep it as static. You should use JObject from Newtonsoft.Json library :
JObject obj = JObject.Parse(jsonString);
Settings.AUT = obj.SelectToken("AUT").Value<string>();

You can always use JsonConvert.Serialize<T>() and JsonConvert.Deserialize<T>() methods instead of the JsonSerialization helper class that I've made but in my opinion the less control you have over your code the bigger the problems will be.


text:
Q: "Batch op errors occurred" on insert_many for list of dict I am trying to insert a list of dict to a collection in MongoDB. I can correctly insert a specified dict using:
all_results_id = all_results.insert_one(json_data[0]).inserted_id

When trying to insert each of the dictionaries contained with list json_data using:
all_results_id = all_results.insert_many(json_data).inserted_id

I get this error:
  File "D:\Program Files (x86)\Microsoft Visual Studio\Shared\Python37_64\lib\site-packages\pymongo\collection.py", line 753, in insert_many
    blk.execute(write_concern, session=session)
  File "D:\Program Files (x86)\Microsoft Visual Studio\Shared\Python37_64\lib\site-packages\pymongo\bulk.py", line 521, in execute
    return self.execute_command(generator, write_concern, session)
  File "D:\Program Files (x86)\Microsoft Visual Studio\Shared\Python37_64\lib\site-packages\pymongo\bulk.py", line 349, in execute_command
    _raise_bulk_write_error(full_result)
  File "D:\Program Files (x86)\Microsoft Visual Studio\Shared\Python37_64\lib\site-packages\pymongo\bulk.py", line 140, in _raise_bulk_write_error
    raise BulkWriteError(full_result)
pymongo.errors.BulkWriteError: batch op errors occurred

In other questions related to this, people have mentioned that this is caused by a duplicated _id however the MongoDB documentation states:
"If an inserted document omits the _id field, the MongoDB driver automatically generates an ObjectId for the _id field."
Can anyone advise where I'm going wrong? I'd rather not iterate over the list and call insert_one on each.


text:
Q: What is SQL Server statement to get day and month ignoring the current year? I have table HD_Case_Master with a column cm_date_created.
The example value is 2011-05-13 10:07:36.000.
I manage to get the current year but how to get record for all day and month.
SQL statement:
SELECT
    cm_create_date
FROM
    HD_Case_Master
WHERE
    YEAR(cm_create_date) = YEAR(GETDATE()) AND ???

A: If you want the current date:
SELECT cm_create_date
FROM HD_Case_Master
WHERE cm_create_date >= CAST(GETDATE() as date) AND
      cm_create_date < CAST(DATEADD(day, 1, GETDATE()) as date)

A: If you want to check if cm_date_created is equal to the current date, ignoring the time component, you just need to CAST both dates to DATE:
SELECT *
FROM HD_Case_Master
WHERE
    CAST(cm_create_date AS DATE) = CAST(GETDATE() AS DATE)

Alternatively, you can use >= and < to check if cm_date_created falls within the current date:
SELECT *
FROM HD_Case_Master
WHERE
    cm_create_date >= CAST(GETDATE() AS DATE)
    AND cm_create_date < CAST(DATEADD(DAY, 1, GETDATE()) AS DATE)

A: You can use DATEPART function of tsql.
... Where DATEPART(day, cm_create_date) = DATEPART(day, getdate()) AND DATEPART(month, cm_create_date) = DATEPART(month, getdate())

A: You were really close! To add just the month (but ignoring the year), just use this:
SELECT
    cm_create_date
FROM
    HD_Case_Master
WHERE
    YEAR(cm_create_date) = YEAR(GETDATE())
    AND MONTH(cm_create_date) = MONTH(GETDATE())


text:
Q: Xamarin Android create and write to a file I am new to Xamarin. I have VS2017 and have my device (Samsung note4 ) connected
 tested and it works. But I want to create and write to a file
 string path = Environment.GetFolderPath(Environment.SpecialFolder.Personal);
        string filename = Path.Combine(path, "myfile.txt");

        using (var streamWriter = new StreamWriter(filename, true))
        {
            streamWriter.WriteLine(DateTime.UtcNow);
        }

I run this on the device and no error or anything. debugger is not  throwing any error. but when I search for this file on  my phone, I can't find it any where at all. did it create a file, and wrote to it? if so, where would that be?

A: Your code should work, try to read it to make sure where it is; This is how you can do it, for more details please see the xamarin forum post, hope it helps;
        string path = Environment.GetFolderPath(Environment.SpecialFolder.Personal);

        string filename = Path.Combine(path, "myfile.txt");

        using (var streamWriter = new StreamWriter(filename, true))
        {
            streamWriter.WriteLine(DateTime.UtcNow);
        }

        using (var streamReader = new StreamReader(filename))
        {
            string content = streamReader.ReadToEnd();
            System.Diagnostics.Debug.WriteLine(content);
        }


text:
Q: Unity3D - Rotate Decal Particle from ParticleSystem to Match Normal I am trying to use a ParticleSystem for Decals as a cheap alternative but am unable to align the particles with all normal surfaces.
This is the nearest I've got that gets all axis correct except for an inverted x axis. (I can see it's the wrong way round on building windows)
if (Physics.Raycast(Camera.main.transform.position, Camera.main.transform.forward, out RaycastHit hit))
{
    Quaternion rot = Quaternion.LookRotation(hit.normal);

    ParticleSystem.EmitParams emitParams = new ParticleSystem.EmitParams
    {
        position = hit.point + 0.01f * hit.normal,
        applyShapeToPosition = true,
        rotation3D = rot.eulerAngles
    };

    _particleSystem.Emit(emitParams, 1);
}

ParticleSystem Settings

ParticleSystem Renderer Settings

I have tried multiple methods over the past 24 hours and have now got myself lost even though it may be something simple.
Sorry about the image sizes - scaling them down messed with the text.
Edit: The editor and project settings are 2020.3.15F2 using URP.

A: I finally managed to figure it out and as no-one was able to answer I will add the solution in case it can help someone else.
1: I inverted the hit.normal when gettting the rotation.
if (Physics.Raycast(Camera.main.transform.position, Camera.main.transform.forward, out RaycastHit hit))
{
    Quaternion rot = Quaternion.LookRotation(-hit.normal);
    ParticleSystem.EmitParams emitParams = new ParticleSystem.EmitParams
    {
        position = hit.point + 0.01f * hit.normal,
        rotation3D = rot.eulerAngles
    };

    _bloodshotParticles.Emit(emitParams, 1);
}

2: Changed the render type from Billboard to Mesh with a Quad set.


text:
Q: Does Doctor Doofenschmirtz ever get back at bellhops? In the Phineas and Ferb S1 episode "Tree to Get Ready", Doctor Doofenschmirtz lists a lot of people he wants to take revenge on, besides his brother Roger and Perry the platypus.

I bear lots of animosity to bellhops,
  They never bring my luggage up on time
  And taxi drivers really tax my patience,
  If they vanished, would it really be a crime?
I don't like meter maids or underwater welders,
  Health fanatic cooks or camera crews!
  Not fond of monks or yoga teachers,
  Or sports fans in the bleachers!

Does Doctor Doofenschmirtz have a scheme targeting any of the people listed here any time in the show?

A: I personally don't remember him getting "revenge" on other people that you listed in your question any time later in the show.
I think that ultimate point of this song is just to show that Dr. D hates those people.
In-Universe he probably got his "revenge" on them, but it was never shown on-screen. We can't judge, because we don't have enough information.


text:
Q: close jquery autocomplete if query is not like data I have a script which allows to display Google suggestions. The problem is that it STILL displays the list even when the value of input is different than the data available, I rather have it closed. Take a look at this Fiddle: JsFiddle
Type a letter than some rubbish like 'cjfsdkcrdvhcxrbsks' You will see the list is still showing. So how do I close it if the value does not match the suggestions?

A: You actually got an error if you have a look in the console.
When the search does not return results, the object data.query.results.toplevel is null. As you don't check for that, there is an exception when trying to access data.query.results.toplevel.CompleteSuggestion and the menu does not close simply because the code just stops working.
Check for null for data.query.results.toplevel and in case it is null, use response([]); to close the menu:
success: function(data) {

    if (typeof data == 'string') {
        data = $.parseJSON(data);
    }

    if (data.query.results.toplevel === null) {
        // passing an empty array to response callback closes the menu
        response([]);
        return;
    }

    response(
        $.map(
        data.query.results.toplevel.CompleteSuggestion,
            function(item) {
                return {
                    label: item.suggestion.data,
                    value: item.suggestion.data
                };
        }));
}

DEMO

A:  success: function(data) {

          if (typeof data == 'string') data = $.parseJSON(data);
          if (data.query.results.toplevel == null){
                   $(this).autocomplete("close"); return;
          }

just checked what the page returns using firebug and this should work, hopefully


text:
Q: Using GET for a non-idempotent request Simply put, I have a website where you can sign up as a user and add data.  Currently it only makes sense to add specific data once, so an addition should be idempotent, but theoretically you could add the same data multiple times.  I won't get into that here.
According to RFC 2616, GET requests should be idempotent (really nullipotent).  I want users to be able to do something like visit
http://example.com/<username>/add/?data=1

And this would add that data.  It would make sense to have a PUT request do this with REST, but I have no idea how to make a PUT request with a browser and I highly doubt most people do or would want to bother to.  Even using POST would be appropriate, but this has a similar problem.
Is there some technically correct way to allow users to add data using only GET (e.g. by visiting the link manually, or allowing external websites to use the link).  When they visit this page I could make my own POST/PUT request either with javascript or cURL, but this still seems to violate the spirit of idempotent GET requests.

A:
Is there some technically correct way to allow users to add data using
  only GET ... ?

No matter how you go about letting clients access it, you'll end up violating RFC2616. It's ultimately up to you how you handle requests (nothing's going to stop you from doing this), but keep in mind that if you go against the HTTP specification, you might cause unexpected side-effects to clients and proxies who do abide by it.
Also see: Why shouldn't data be modified on an HTTP GET request?

As far as not being able to PUT from the browser, there are workarounds for that [1], [2], most of which use POST but also pass some sort of _method request parameter that's intercepted by the server and routes to the appropriate server-side action.


text:
Q: Header not displaying correctly on chapter page due to subsection (Complete source code below.)
(Note: Not sure if I am using LaTeX or just TeX. I am editing with TeXworks, as TeXStudio was not rendering what I typed without +20 seconds of lag.)
I apologize if this question has already been asked. I searched tex.stackexchange.com, the internet, and the fancyhdr documentation, but could not find the solution.
Simply put, I used fancyhdr to setup headers, however the chapter pages are not displaying correctly, despite using fancyhdr to redefine the plain style.
The best clue I could get from the fancyhdr documentation was the following:

Another problem with the marks in the standard LATEX classes is that
  the higher level sectioning commands (e.g. \chapter) call \markboth
  with an empty right argument. This means that on the first page of a
  chapter (or a section in article style) the \rightmark will be empty.
  If this is a problem you must manually insert extra \markright
  commands or redefine the \chaptermark (\sectionmark) commands to issue
  a \markboth command with two decent parameters.

I am not clear how to implement this solution, despite many attempts.

In detail, this is what I am trying to do (the bold items are causing problems):

*

*Left Header: [Author's Name]

*Right Header: [Book Author's Name]>["Chapter"+Chapter#]>[Subsection Name]

*The same Header must show on all pages, including the chapter pages, and excluding the Table of Contents. [For solution, see egreg's response.]

*Subsections must not be automatically numbered, i.e., they must be "* commands".

*Subsections must appear in Table of Contents, despite being "* commands".

P.S. [Solved, see solution below:] Is there a way (1) to not have the subsections automatically numbered and (2) included in the Table of Contents, yet not have to input each subsection title three times? Just curious. See below:
\subsection*{Title of Subsection 3\markright{Title of Subsection 3}{}}
\addcontentsline{toc}{subsection}{Title of Subsection 3}

Solution #1 (Simplest):
In preamble, write \setcounter{secnumdepth}{1}.
Solution#2:
In preamble, create a new command by writing:
\newcommand{\newsubsection}[1]{\subsection*{#1\markright{#1}}%
    \addcontentsline{toc}{subsection}{#1}}

To save everyone some time compiling, on the left is the chapter page, and on the right shows what the chapter page header should look like this:

\documentclass{report}

% PACKAGES
\usepackage{fancyhdr}
\usepackage{lastpage} % Allows referencing of the last page to allow footer to read: "Page [Current page] of [Total number of pages]."
\usepackage{comment} % Allows comments of the type: \begin{comment}This text is commented out.\end{comment}
%\usepackage[colorlinks=true]{hyperref} % Turns table of contents and labels into clickable links. Commented out to speed up compiling.
\usepackage[T1]{fontenc} % Allows use of ">" symbol.
\usepackage{lmodern} %Not really sure what this is for.

% FORMATTING
% Header and Footer
\pagestyle{fancy}

% Allows calling chapter and section names in headers and footers.
\renewcommand{\chaptermark}[1]{\markboth{\chaptername\ \thechapter}{}}
\renewcommand{\subsectionmark}[1]{\markright{#1}{}}

% General Header and Footer
\lhead{\DocumentAuthor}
\chead{}
\rhead{\BookAuthor>\leftmark>\rightmark}
\lfoot{}
\cfoot{}
\rfoot{Page \thepage\ of \pageref{LastPage}}

% Chapter Header and Footer
\fancypagestyle{plain}{%
\lhead{\DocumentAuthor}
\chead{}
\rhead{\BookAuthor>\leftmark>\rightmark}
\lfoot{}
\cfoot{}
\rfoot{Page \thepage\ of \pageref{LastPage}}}

% Header/Footer Separation-line Width
\renewcommand\headrulewidth{0.5pt}
\renewcommand\footrulewidth{0.5pt}

\setlength\parindent{0pt} % Remove paragraph indentation.

% NAME AND CLASS SECTION
\newcommand{\DocumentAuthor}{Author Name}
\newcommand{\BookAuthor}{Book Author}

%DOCUMENT
\begin{document}

\tableofcontents{}
\thispagestyle{empty}

\chapter{Title of Chapter 1}
\section{Sample Problems}
\subsection*{Title of Subsection 1\markright{Title of Subsection 1}{}}
\addcontentsline{toc}{subsection}{Title of Subsection 1}
\pagebreak{}
\subsection*{Title of Subsection 2\markright{Title of Subsection 2}{}}
\addcontentsline{toc}{subsection}{Title of Subsection 2}
\subsection*{Title of Subsection 3\markright{Title of Subsection 3}{}}
\addcontentsline{toc}{subsection}{Title of Subsection 3}
\pagebreak{}
\subsection*{Title of Subsection 4\markright{Title of Subsection 4}{}}
\addcontentsline{toc}{subsection}{Title of Subsection 4}

\end{document}

A: We must give more structure to the right mark emitted by the \chapter command; so we do
\renewcommand{\chaptermark}[1]{%
  \markboth{\chaptername\ \thechapter}
           {\noexpand\firstsubsectiontitle}}

The \subsectiontitle macro will be defined by the \subsection command; of course it won't work if no subsection starts in the first page:
\renewcommand{\subsectionmark}[1]{%
  \markright{#1}\gdef\firstsubsectiontitle{#1}}

Here's an example; notice some changes I've made to your code. For instance I've redefined the \sectionmark command so it doesn't emit any mark.
The solution to the numbering problem of subsection is to \setcounter{secnumdepth}{1}.
\documentclass{report}

% PACKAGES
\usepackage{fancyhdr}
\usepackage{lastpage} % Allows referencing of the last page to allow footer to read: "Page [Current page] of [Total number of pages]."
\usepackage{comment} % Allows comments of the type: \begin{comment}This text is commented out.\end{comment}
%\usepackage[colorlinks=true]{hyperref} % Turns table of contents and labels into clickable links. Commented out to speed up compiling.
\usepackage[T1]{fontenc} % Allows use of ">" symbol.
\usepackage{lmodern} %Not really sure what this is for.

% FORMATTING
% Header and Footer
\pagestyle{fancy}

% Allows calling chapter and section names in headers and footers.
\renewcommand{\chaptermark}[1]{%
  \markboth{\chaptername\ \thechapter}
  {\noexpand\firstsubsectiontitle}}
\renewcommand{\sectionmark}[1]{}
\renewcommand{\subsectionmark}[1]{%
  \markright{#1}\gdef\firstsubsectiontitle{#1}}
\newcommand\firstsubsectiontitle{}

% General Header and Footer
\fancyhf{}
\fancyhead[L]{\DocumentAuthor}
\fancyhead[R]{\BookAuthor>\leftmark>\rightmark}
\fancyfoot[C]{Page \thepage\ of \pageref{LastPage}}

% Chapter Header and Footer
\fancypagestyle{plain}{%
  \fancyhf{} \fancyhead[L]{\DocumentAuthor}%
  \fancyhead[R]{\BookAuthor>\leftmark>\rightmark}%
  \fancyfoot[C]{Page \thepage\ of \pageref{LastPage}}%
}

% Header/Footer Separation-line Width
\renewcommand\headrulewidth{0.4pt}
\renewcommand\footrulewidth{0.4pt}

\setlength\parindent{0pt} % Remove paragraph indentation.

% NAME AND CLASS SECTION
\newcommand{\DocumentAuthor}{Author Name}
\newcommand{\BookAuthor}{Book Author}

\setcounter{secnumdepth}{1}

%DOCUMENT
\begin{document}

\tableofcontents
\thispagestyle{empty}

\chapter{Title of Chapter 1}
\section{Sample Problems}
\subsection{Title of Subsection 1}
\pagebreak{}
\subsection{Title of Subsection 2}
\subsection{Title of Subsection 3}
\pagebreak{}
\subsection{Title of Subsection 4}

\end{document}

With this code the first subsection in the page will be put in the header.

What's \noexpand\firstsubsectiontitle doing? The \markboth and \markright commands must record the current values of the counters and titles, so their arguments are passed through an \edef; this, in the case of the first chapter and English language, would set a left mark with value Chapter\ 1. If we said only \firstsubsectiontitle in the second argument, it would be expanded leaving a wrong right mark because it would be empty for the first chapter and would contain the last subsection in the preceding chapter!
So we say "dear TeX, don't expand \firstsubsectiontitle right now, but only when you'll set the header."
Actually, if there can be more than one subsection in the chapter pages, a different solution should be used:
% Allows calling chapter and section names in headers and footers.
\renewcommand{\chaptermark}[1]{%
  \markboth{\chaptername\ \thechapter}
           {\noexpand\firstsubsectiontitle}%
  \global\firstsubsectionmarktrue}
\renewcommand{\sectionmark}[1]{}
\renewcommand{\subsectionmark}[1]{%
  \markright{#1}%
  \iffirstsubsectionmark
    \gdef\firstsubsectiontitle{#1}%
  \fi
  \global\firstsubsectionmarkfalse}
\newif\iffirstsubsectionmark
\def\firstsubsectiontitle{}

so that the first subsection would set the mark.

A: For unnumbered subsections that are nevertheless included in the ToC, add \setcounter{secnumdepth}{1} to the preamble and use \subsection instead of \subsection* in the text body. Together with the fact that you've already redefined \subsectionmark (BTW, \markright only takes one argument), this also (mostly) removes the need to use \markright in the text body.
A workaround for your main question is to add \clearpage\markright{Title of subsection 1} before  the chapter start.
\documentclass{report}

% PACKAGES
\usepackage{fancyhdr}
\usepackage{lastpage} % Allows referencing of the last page to allow footer to read: "Page [Current page] of [Total number of pages]."
\usepackage{comment} % Allows comments of the type: \begin{comment}This text is commented out.\end{comment}
%\usepackage[colorlinks=true]{hyperref} % Turns table of contents and labels into clickable links. Commented out to speed up compiling.
\usepackage[T1]{fontenc} % Allows use of ">" symbol.
\usepackage{lmodern} %Not really sure what this is for.

% FORMATTING
% Header and Footer
\pagestyle{fancy}

% Allows calling chapter and section names in headers and footers.
\renewcommand{\chaptermark}[1]{\markboth{\chaptername\ \thechapter}{}}
\renewcommand{\subsectionmark}[1]{\markright{#1}}

% General Header and Footer
\lhead{\DocumentAuthor}
\chead{}
\rhead{\BookAuthor>\leftmark>\rightmark}
\lfoot{}
\cfoot{}
\rfoot{Page \thepage\ of \pageref{LastPage}}

% Chapter Header and Footer
\fancypagestyle{plain}{%
\lhead{\DocumentAuthor}
\chead{}
\rhead{\BookAuthor>\leftmark>\rightmark}
\lfoot{}
\cfoot{}
\rfoot{Page \thepage\ of \pageref{LastPage}}}

% Header/Footer Separation-line Width
\renewcommand\headrulewidth{0.5pt}
\renewcommand\footrulewidth{0.5pt}

\setlength\parindent{0pt} % Remove paragraph indentation.

% NAME AND CLASS SECTION
\newcommand{\DocumentAuthor}{Author Name}
\newcommand{\BookAuthor}{Book Author}

\setcounter{secnumdepth}{1}

%DOCUMENT
\begin{document}

\tableofcontents{}
\thispagestyle{empty}

\clearpage
\markright{Title of Subsection 1}

\chapter{Title of Chapter 1}
\section{Sample Problems}
\subsection{Title of Subsection 1}
\clearpage
\subsection{Title of Subsection 2}
\subsection{Title of Subsection 3}
\clearpage
\subsection{Title of Subsection 4}

\end{document}


text:
Q: Comunicar com Arduíno pela porta COM4 Criei um código em c# para me comunicar com o Arduíno uno.  Ele tem que me passar qual a tag passou pelo leitor rfid e mostre em uma textbox o valor.
Adicionei a serialport1.
Código:
        serialPort1.Open();
        string entrada = serialPort1.ReadLine();
        serialPort1.Close();
        txtIDTag.Text = entrada;

Erro quando executo:
An unhandled exception of type 'System.UnauthorizedAccessException' occurred in System.dll
Additional information: A porta 'COM4' não existe.


text:
Q: How should I store some custom attributes for an item in Sitecore? I'm importing thousands of products from an XML feed, into Sitecore. So I created a template for the Product, which contains about 20 fields like Identification, Name, Price and so on.
But also, in the XML, a product can have some custom attributes, that look like this:
<custom-attribute name="AC_Information_1_Name" dt:dt="string" xml:lang="nl-NL">PDF</custom-attribute>

At first, I created a new template that would hold these fields and store a Sitecore item for each of these Custom Attributes, in a folder and link them to the Product. But this made the import really really slow, as the folder containing the Custom Attribute items had over 100 000 of them and everytime it had to save another one, it would look into all of the existing ones to check if it's not a duplicate.
So I thought I needed to change the whole structure of how I was saving these.
Another idea was to save them directly in the Product somehow, but a Name Value List was not sufficient, as there was also the DataType and Language, that needed to be saved.
Do you know any data type that could hold all the values? Or maybe some other ideas?

A: Some suggestions:

*

*Increase performance by doing your lookups against the index.

*Look at using a bucket for your custom attributes, which will automatically create a hidden tree structure for your items to optimize Sitecore performance.

*Consider storing it on the product as a custom field type (possibly storing XML as the raw value), much like how presentation details work. You can build a UI on top of this to show the data however you would like. This will mean duplicate data, however, but will be efficient to import.

A: Suggestions :
1 - Create a template for custom attribute with (Name, Value, Language, Type) and add xml's custom attributes as child item for the product.  You shouldn't need to do the look-up as the attributes should only be for the product and having them in a general folder location adds no value. So your tree might look like
Product 1 > attribute 1 | attribute 2 | .... | attribute n
Product 2 > attribute 1 | ...
...
Product N
2 - Create Custom field type for the xml's attribute so that your field should have 4 input boxes as one field. For example, your product template will look like
Identification
[input box]
Price
[input box]
Custom Attribute
Name        | Value       | Type        | Lang
[input box] | [input box] | [input box] | [input box]
This approach will take more time and you can check out sdn documentation for creating custom field types.
Thanks
Naveed.


text:
Q: NGINX/SWAG: Rewrite URL to remove .php extension there are dozens of similar question in the internet (stackoverflow and other sites), but none of them worked for me.
I am trying to rewrite my URL to get rid of the .php extension at the end. I already tried the common rewrites in my config.
I hope somebody knows an answer i did not use yet.

A: you can use .htaccess
make a new file in the directory which your PHP files are there, make a new file called .htaccess, put in the following in there:
RewriteCond %{THE_REQUEST} ^.*/*\.php
RewriteRule ^(.*).php$ /$1 [R=301,L]

A: In your vhost config file or nginx.conf file, add the following lines in the inside server block :
location / {
    try_files $uri $uri.html $uri/ @extensionless-php;
    index index.html index.htm index.php; }

location ~ \.php$ {
    try_files $uri =404; }

location @extensionless-php {
    rewrite ^(.*)$ $1.php last; }

Need to restart Nginx before use.


text:
Q: Front-end glitch when interacting with dynamic content This is now bugging me too much to ignore it anymore. When I interact with a notebook that has dynamic content, for example moving a slider, Mathematica regularly brings other open notebook windows to the front. This means that while I am interacting with the given notebook, some other notebook (already opened, but in the background) pops up in the front, either blocking my view or just staying in the lower-left corner (if it was minimized before). The focus is not changed, so I can still interact with the content of the original notebook now in the back. When I continue manipulation, the front notebook disappears, just to reappear again a few seconds later. This is extremely annoying and happens "if the Manipulate [or other dynamic content] contains something that's computationally expensive" (Sjoerd's comment below, and I can confirm this), mostly when complex 2D or 3D plots are manipulated directly (e.g. 3D rotate with mouse) or indirectly (mouse driven slider changes parameters of dynamic plot).
For example rotating the following 3D figure with the mouse causes the behaviour to present itself.
Plot3D[Sin[x + y^2], {x, -3, 3}, {y, -2, 2}]

Reproducibility is occasional, sometimes it happens fairly frequently, sometimes not at all. A more or less solid way to reproduce the error:

*

*open a fresh Mathematica

*open a new notebook (by e.g. ctrl+N; this will be the one that will pop to the front; this can be any notebook window)

*open another notebook, paste above code

*evaluate code (dragging the 3D plot now won't trigger the glitch, or only very rarely)

*bring in front any other application, e.g. Firefox (though the glitch could happen even if no other application is running)

*get back to Mathematica (by e.g. minimizing Firefox)

*dragging the 3D plot around for some time (~5-10 sec) has a high chance to trigger the glitch, which can manifest as short "jumps" of open Mathematica windows where one gets in the front for a fraction of a second)

Does anyone else experience this annoyance?
What causes this behaviour?

This is still reproducible under Mathematica 9.0.1, Windows 7.

A: Upgrading to a newer computer solved the problem. Perhaps it was RAM- or grpahics-card-related, we'll never know.


text:
Q: Postfix: Name service error for name=domain.com type=MX: Host not found, try again I'm stuck with a Postfix MX related problem.
I've just migrated a very old Centos 5 server to v7 so I'm using postfix-2.10.1-7.el7.x86_64. I've upgraded the legacy postfix configuration (maybe the cause of this hell) and other supplementary stuff which seems to work:

*

*postfix-perl-scripts-2.10.1-7.el7.x86_64

*postgrey-1.34-12.el7.noarch

*amavisd-new-2.11.1-1.el7.noarch

*spamassassin-3.4.0-4.el7_5.x86_64

*perl-Mail-SPF-2.8.0-4.el7.noarch

*perl-Mail-DKIM-0.39-8.el7.noarch

*dovecot-2.2.36-3.el7.x86_64

After many tribulations I think I got most of the system running except the annoying MX related problems, as (from /var/log/maillog):
Mar 28 14:26:48 tormento postfix/smtpd[1021]: warning: Unable to look up MX host for spmailtechn.com: Host not found, try again
Mar 28 14:26:51 tormento postfix/smtpd[1052]: warning: Unable to look up MX host for inlumine.ual.es: Host not found, try again
Mar 28 14:31:38 tormento postfix/smtpd[1442]: warning: Unable to look up MX host for aol.com: Host not found, try again
Mar 28 13:07:53 tormento postfix/smtpd[26556]: warning: Unable to look up MX host for hotmail.com: Host not found, try again
Mar 28 13:12:06 tormento postfix/smtpd[26650]: warning: Unable to look up MX host for facebookmail.com: Host not found, try again
Mar 28 13:12:31 tormento postfix/smtpd[26650]: warning: Unable to look up MX host for joker.com: Host not found, try again
Mar 28 13:13:02 tormento postfix/smtpd[26650]: warning: Unable to look up MX host for bounce.linkedin.com: Host not found, try again

and:
Mar 28 14:50:36 tormento postfix/smtp[1700]: 7B6C69C6A2: to=<ismael.olea@gmail.com>, orig_to=<ismael@olea.org>, relay=none, delay=1142, delays=1142/0.07/0/0, dsn=4.4.3, status=deferred (Host or domain name not found. Name service error for name=gmail.com type=MX: Host not found, try again)
Mar 28 14:32:05 tormento postfix/smtp[1383]: 721A19C688: to=<XXXXX@yahoo.com>, orig_to=<XXXX@olea.org>, relay=none, delay=4742, delays=4742/0/0/0, dsn=4.4.3, status=deferred (Host or domain name not found. Name service error for name=yahoo.com type=MX: Host not found, try again)

as examples.
The first suspect is DNS resolution but this is working both using Hetztner DNS servers (where machine is host) or 8.8.8.8 or 9.9.9.9.
$ cat /etc/resolv.conf
; generated by /usr/sbin/dhclient-script
nameserver 213.133.100.100
nameserver 213.133.98.98
nameserver 213.133.99.99

and /etc/hosts:
195.201.24.84 tormento tormento.olea.org
127.0.0.1 localhost.localdomain localhost
127.0.0.1 localhost4.localdomain4 localhost4

# The following lines are desirable for IPv6 capable hosts
::1 tormento tormento.olea.org
::1 localhost.localdomain localhost
::1 localhost6.localdomain6 localhost6

I fear I'm missing something really obvious but I've been googling for two days doing any amount of tests and now I don't know what much to do.
Since Serverfault rejected my original question as spam I've put the log and configuration details at my personal blog: http://olea.org/diario/2019/03/28/Postfix_MX_not_found.html
Thanks in advance.

A: Well, this is embarrassing. As I predicted my problem was caused by the most obvious and trivial reason: lack of read access to /etc/resolv.conf for the postfix user o_0
As you probably know the postfix subproceses (smtp, smtpd, qmgr, etc) runs with the postfix user. All the comments and suggestion I've received has been related with problems accessing to DNS resolving data and the usual suspects has been SELinux or a chrooted postfix. You all were right in the final reason. Following an advice and tried:
# sudo -u postfix -H cat /etc/resolv.conf
cat: /etc/resolv.conf: Permission denied

So... What??
# ls -l /etc/resolv.conf
-rw-r-----. 1 root named 118 mar 28 20:34 /etc/resolv.conf

OMG!... then after a chmod o+r and restarting Postfix all the email on hold can be processed and sent and new mail is processed as expected.
I doubt I've changed the resolv.conf reading permissions but I can't be 100% sure. So finally the problem is fixed and I'm very sorry for stole the attention of all of you for this ridiculous reason. Thanks you all.

A: step 1. i check gmail.com for access to mx record on my server. first i installed the bind server using yum install bind-utils and check rhe gmail.com by following command:
root@host# host -t mx gmail.com
;; connection timed out; no servers could be reached

so, i change my dns server to 8.8.8.8 using nmtui command and reboot my server...
after reboot I execute the host -t mx gmail.com and my timed out was fixed by thsi houtput:
root#host# host -t mx gmail.com
gmail.com mail is handled by 10 alt1.gmail-smtp-in.l.google.com.
gmail.com mail is handled by 30 alt3.gmail-smtp-in.l.google.com.
gmail.com mail is handled by 20 alt2.gmail-smtp-in.l.google.com.
gmail.com mail is handled by 40 alt4.gmail-smtp-in.l.google.com.
gmail.com mail is handled by 5 gmail-smtp-in.l.google.com.

But the main problem not solved yet for me... so, I did step 2...
step 2. Om my server not exist etc folder on /var/spool/postfix/.So, I created etc folder manually...Then, copy three file on it. /etc/host.conf , /etc/resolv.conf and /etc/servoces
root@host# mkdir /var/spool/postfix/etc
root@host# cp /etc/host.conf /var/spool/postfix/etc/
root@host# cp /etc/resolv.conf /var/spool/postfix/etc/
root@host# cp /etc/services /var/spool/postfix/etc/

The main problem of MX not solved yet...
step 3. I change mode of /etc/resolv.conf and /var/pool/postfix/etc/* to 1777 and fixed my problem
root@host# chmod 1777 /etc/resolve.conf
root@host# chmod 1777 -R /var/spool/postfix/etc

finally I restart the postfix service using systemctl restart postfix.service and my smtp worked fine!

A: FYI, this problem may be caused by SELinux. Postfix didn't have permission to read /etc/resolv.conf.
To fix this, you can disable SELinux completely by the command setenforce 0 or reset SELinux context for /etc/resolv.conf by the command sudo restorecon /etc/resolv.conf


text:
Q: How Do I Get a Web Browser's Public Key (Used In HTTPS) I have a program I'm developing centered around the browser digitally signing a value.
The plan was to use the HTTPS cert built in to the browser to sign, but the whole approach is contingent on getting access to the browser's HTTPS cert's public key.
How do I access it either in Javascript or ASP.NET service code?
I'm coming up blank on Google (the best I can find is something that allows for communication through custom certs, but not the one the browser uses for HTTPS).

A: Normally we sign our request with public key which is present in .crt file. Corresponding to that domain we have .pfx file which contains the private key and is present with server.
Through below code you can get complete certificate chain. Normally we have a function ServerCertificateValidationCallback which is used to validate certificate chain but here we are using it to access the certificates which we are validating. So, we need to register the callback "ServerCertificateValidationCallback" for our request.
Below is the console code which returns us the certificate:
public static void Main(string[] args)
{
    GetCertificate("https://www.facebook.com", "");
}
/// <summary>
/// Get and write certificate from URL into file in path
/// </summary>
/// <param name="_URL">URL of website with certficate</param>
/// <param name="_path">Path where you want to store certificate</param>
private static void GetCertificate(string url, string path)
{

        var request = (HttpWebRequest)WebRequest.Create(url);
        request.AllowAutoRedirect = false;
        request.ServerCertificateValidationCallback = ServerCertificateValidationCallback;

        HttpWebResponse response = (HttpWebResponse)request.GetResponse();
        response.Close();
        Console.ReadLine();

}

private static bool ServerCertificateValidationCallback(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors)
{
    foreach (var cert in chain.ChainElements)
    {
        Console.WriteLine(cert.Certificate.FriendlyName);
        Console.WriteLine(ExportToPem(cert.Certificate));
    }

    return true;
}

/// <summary>
/// Export a certificate to a PEM format string
/// </summary>
/// <param name="_cert">The certificate to export</param>
/// <returns>A PEM encoded string</returns>
public static string ExportToPem(X509Certificate2 cert)
{
    StringBuilder strBuilder = new StringBuilder();

    try
    {
        strBuilder.AppendLine("-----BEGIN CERTIFICATE-----");
        strBuilder.AppendLine(Convert.ToBase64String(cert.Export(X509ContentType.Cert), Base64FormattingOptions.InsertLineBreaks));
        strBuilder.AppendLine("-----END CERTIFICATE-----");

    }
    catch (Exception)
    {
    }

    return strBuilder.ToString();
}


text:
Q: Create Diagram - 4 blank horizontal lines in a row - Labels underneath w/lines or arrows pointing So I want to draw a diagram explaining names of digit places ('hundreds'  'tens' 'ones'). I want blank lines with these labels underneath. I'm thinking qtree might be an idea (4 top branches being the blank lines with 1 branch coming off each for the labels).
I am curious is anyone knows an easier way.
Thanks a lot!

A: One option would be to use PGF/TikZ; something along these lines:
\documentclass{article}
\usepackage{tikz}
\usetikzlibrary{positioning}

\newcommand\HuTeOn{%
\begin{tikzpicture}[node distance= 0.5cm and 1cm]
  \node (h) {\rule{1.5cm}{0.4pt}};
  \node[right= of h] (t) {\rule{1.5cm}{0.4pt}};
  \node[right= of t] (o) {\rule{1.5cm}{0.4pt}};
  \node[below = of h] (nh) {hundreds};
  \node[below = of t] (nt) {tens};
  \node[below = of o] (no) {ones};
  \foreach \i in {h,t,o}
    \draw[->] (n\i) -- (\i);
\end{tikzpicture}
}

\begin{document}

\HuTeOn

\end{document}


text:
Q: PyMC for Model Averaging I am interested in applying PyMC to model averaging. My goal is to estimate many linear models and average estimates across them, weighting by their posterior model probabilities. I am currently using the Bayesian Information Criterion (BIC) to approximate the likelihood of my data (therefore, my analysis is not fully Bayesian). I have successfully simulated a Markov Chain of models using one of my own scripts but I want to use PyMC because it seems like a great tool.
In my attempts thus far, I have not been forming the Markov Chain correctly. I am not visiting models with higher posterior weights more often than others. I will include the example code below. Please also see the IPython notebook here! on github for the math markup and code together.
import numpy as np
from pymc import stochastic, DiscreteMetropolis, MCMC
import statsmodels.api as sm
import pandas as pd
import random

def pack(alist, rank):

    binary = [str(1) if i in alist else str(0) for i in xrange(0,rank)]
    string = '0b1'+''.join(binary)
    return int(string, 2)

def unpack(integer):

    string = bin(integer)[3:]

    return [int(i) for i in xrange(len(string)) if string[i]=='1']

def make_bma():

    # Simulating Data
    size = 100
    rank = 20

    X = 10*np.random.randn(size, rank)
    error = 30*np.random.randn(size,1)
    coefficients = np.array([10, 2, 2, 2, 2, 2]).reshape((6,1))
    y = np.dot(sm.add_constant(X[:,:5], prepend=True), coefficients) + error

    # Number of allowable regressors
    predictors = [3,4,5,6,7]

    @stochastic(dtype=int)
    def regression_model():

        def logp(value):

            columns = unpack(value)

            x = sm.add_constant(X[:,columns], prepend=True)

            corr = np.corrcoef(x[:,1:], rowvar=0)

            prior = np.linalg.det(corr)

            ols = sm.OLS(y,x).fit()

            posterior = np.exp(-0.5*ols.bic)*prior

            return np.log(posterior)

        def random():

            k = np.random.choice(predictors)

            columns = sorted(np.random.choice(xrange(0,rank), size=k, replace=False))

            return pack(columns, rank)

    class ModelMetropolis(DiscreteMetropolis):
        def __init__(self, stochastic):
            DiscreteMetropolis.__init__(self, stochastic)

        def propose(self):
            '''considers a neighborhood around the previous model,
            defined as having one regressor removed or added, provided
            the total number of regressors coincides with predictors
            '''

            # Building set of neighboring models
            last = unpack(self.stochastic.value)
            last_indicator = np.zeros(rank)
            last_indicator[last] = 1
            last_indicator = last_indicator.reshape((-1,1))
            neighbors = abs(np.diag(np.ones(rank)) - last_indicator)
            neighbors = neighbors[:,np.any([neighbors.sum(axis=0) == i \
                                for i in predictors], axis=0)]
            neighbors = pd.DataFrame(neighbors)

            # Drawing one model at random from the neighborhood
            draw = random.choice(xrange(neighbors.shape[1]))

            self.stochastic.value = pack(list(neighbors[draw][neighbors[draw]==1].index), rank)

#        def step(self):
#
#            logp_p = self.stochastic.logp
#
#            self.propose()
#
#            logp = self.stochastic.logp
#
#            if np.log(random.random()) > logp_p - logp:
#
#                self.reject()

    return locals()

if __name__ == '__main__':

    model = make_bma()
    M = MCMC(model)
    M.use_step_method(model['ModelMetropolis'], model['regression_model'])
    M.sample(iter=5000, burn=1000, thin=1)

    model_chain = M.trace("regression_model")[:]

    from collections import Counter

    counts = Counter(model_chain).items()
    counts.sort(reverse=True, key=lambda x: x[1])

    for f in counts[:10]:
        columns = unpack(f[0])
        print('Visits:', f[1])
        print(np.array([1. if i in columns else 0 for i in range(0,M.rank)]))
        print(M.coefficients.flatten())
        X = sm.add_constant(M.X[:, columns], prepend=True)
        corr = np.corrcoef(X[:,1:], rowvar=0)
        prior = np.linalg.det(corr)
        fit = sm.OLS(model['y'],X).fit()
        posterior = np.exp(-0.5*fit.bic)*prior
        print(fit.params)
        print('R-squared:', fit.rsquared)
        print('BIC', fit.bic)
        print('Prior', prior)
        print('Posterior', posterior)
        print(" ")

A: It sounds like you are trying to do something akin to reversible jump MCMC, where you are sampling from the model space in addition to the parameter space(s). PyMC does not currently do rjMCMC, though it probably ought to. The trick is to account for the change in dimension when moving among models. If you do have a modest number of models, you can use an indicator function to select from the models, all of which are fit simultaneously.


text:
Q: Stream data into ag-grid with angularjs I am attempting to use ag-grid in an application where events are streamed to the client.  Every event received should be added to the grid.  I am adding via  the insertItemsAtIndex method, and am getting multiple events per second.
Unfortunately ag-grid doesn't seem to handle this scenario very well.  The first 10 or so events are displayed promptly, but after that I only see chunks of events displayed after a delay.  The browser also completely bogs down to the point that it is unusable.
Is there a better way to use ag-grid for streaming data?  I have tried the other addItems method, I have removed any cell renderers, sorts, filters, etc. in order to try and keep it as lean as possible, but with no effect.

A: There is the enterprise feature of a Viewport Row Model. It's the exact thing that you are looking for. However, if you don't have that option, then I would suggest handling the addition of items outside of the grid, then updating the rows with what you create... that might be more optimized.


text:
Q: Как подключать CSS-стили в Shopify? Как подключать CSS-стили в Shopify?
Я знаю как подключать стили CSS , когда они лежат все в папке assets , но  хочу их сложить в assets/css/Css-стили , чтобы не было грязи. И возможно ли это?Потому , что я хотел найти сам перерыл и рунет и английский ничего годного не нашёл.

A: Просто продолжите путь по новым папкам.
Если у Вас раньше было /assets/style.css , то станет /assets/css/style.css
Надеюсь я Вас правильно понял.

A: To customize the ActionBar in an Android app, you can use the getSupportActionBar() method to get a reference to the ActionBar object and then call various methods on it to change its properties. For example:

You can also customize the layout of the ActionBar by creating a custom layout file and setting it as the ActionBar's custom view. To do this, you can use the setCustomView() method and pass it the layout resource ID:

Finally, you can also customize the appearance of the ActionBar by using a custom theme that modifies the ActionBar's style. For example, you can use the windowActionBar property in your theme to change the color and appearance of the ActionBar.

You can then apply this theme to your app by setting it in the android:theme attribute in the  element of your app's manifest file.
You can also built your Shopify mobile application as it is the current needs of the businesses. To help you out for building Shopify mobile app you may visit https://appokart.com/ , here you will get the proper guidance to use every Shopify tool.


text:
Q: Use image in Userform Caption I am working on a UserForm and I am trying to use an IE/Chrome etc logo in the caption property of the UserForm so that the logo is displayed in the window frame followed by some text.
I have done some browsing and have found the following code online but I get an sub/function not defined error on the line involving ExtractIcon.
UserForm Code
Private Sub UserForm_Initialize

    Dim strIconPath As String
     Dim lngIcon As Long
     Dim lnghWnd As Long

     ' Change to the path and filename of an icon file
     strIconPath = "C:\Users\suttond\Desktop\Picture2.gif"
     ' Get the icon from the source
     lngIcon = ExtractIcon(0, strIconPath, 0)
     ' Get the window handle of the userform
     lnghWnd = FindWindow("ThunderDFrame", UserForm1.Caption)
     'Set the big (32x32) and small (16x16) icons
     SendMessage lnghWnd, WM_SETICON, True, lngIcon
     SendMessage lnghWnd, WM_SETICON, False, lngIcon

End Sub

Module Code
Private Declare Function FindWindow _
     Lib "user32" Alias "FindWindowA" _
    (ByVal lpClassName As String, _
     ByVal lpWindowName As String) As Long

 Private Declare Function ExtractIcon _
     Lib "shell32.dll" Alias "ExtractIconA" _
    (ByVal hInst As Long, _
     ByVal lpszExeFileName As String, _
     ByVal nIconIndex As Long) As Long

 Private Declare Function SendMessage _
     Lib "user32" Alias "SendMessageA" _
    (ByVal hWnd As Long, _
     ByVal wMsg As Long, _
     ByVal wParam As Integer, _
     ByVal lParam As Long) As Long

 Private Const WM_SETICON = &H80

Essentially a small IE Explorer logo would display to the left of text already in the caption.
Edit
Module code functions updated to public to allow them to be called from the initialize code. No longer getting the extract error but the image is not appearing in the UserForm caption.

A: As Mistella and Rory mentioned in the comments of your questions, the functions and the constant needs to be declared as Public. If you declare them as Private, they are only known within the Module, but not in the Form.
Second thing is you need to read the Icon from an ICO-file, not from a gif, so you need to convert it. I use IrfanView for tasks like this, but there are tons of tools (even online) available. I did a quick test and it worked:


text:
Q: Question mark on finder's side bar -- could it be malware?
When I click on this question mark finder tells me it can't open it because the original item couldn't be found. A week ago I downloaded a file that I suspect could have been malware. Could a malware manifest this way?
Thanks!

A: No. A question mark is the usual symbol for a link to a file that no longer exists or cannot be found.
Malware is designed to go unnoticed.


text:
Q: Array index of bound exception in parse I'm trying to get the object saved in parse cloud but it's giving me
java.lang.IndexOutOfBoundsException: Invalid index 0, size is 0

the code is:
      private void parsingTask() {
    //po=new ParseObject("LatLng");
    ParseQuery<ParseObject> query=ParseQuery.getQuery("LatLng");
    query.whereEqualTo("imei_code","357146054169800");
    query.findInBackground(new FindCallback<ParseObject>() {

        @Override
        public void done(List<ParseObject> latlanglist, ParseException e) {
            if(e==null){
        String firstItemId=latlanglist.get(0).getObjectId();
        lat=latlanglist.get(0).getString("latitude");
        lang=latlanglist.get(0).getString("longitude");
        e1.setText(lat);
        e2.setText(lang);
        e3.setText(firstItemId);

            Toast.makeText(getApplicationContext(),"Found the New Location:\nLatitude:"+lat+
                    "\nLongitude:"+lang+"\nObjectID:"+firstItemId,Toast.LENGTH_LONG).show();
            }
            else{

            Toast.makeText(getApplicationContext(), "Error was found\n"+e,Toast.LENGTH_LONG).show();

            }

        }
    });
    // TODO Auto-generated method stub

}

the logcat output:
01-15 14:34:21.064: E/AndroidRuntime(10986): FATAL EXCEPTION: main
01-15 14:34:21.064: E/AndroidRuntime(10986): java.lang.IndexOutOfBoundsException: Invalid index 0, size is 0
01-15 14:34:21.064: E/AndroidRuntime(10986):    at java.util.ArrayList.throwIndexOutOfBoundsException(ArrayList.java:251)
01-15 14:34:21.064: E/AndroidRuntime(10986):    at java.util.ArrayList.get(ArrayList.java:304)
01-15 14:34:21.064: E/AndroidRuntime(10986):    at com.robotrackerserver.MainActivity$1.done(MainActivity.java:43)
01-15 14:34:21.064: E/AndroidRuntime(10986):    at com.parse.FindCallback.internalDone(FindCallback.java:45)
01-15 14:34:21.064: E/AndroidRuntime(10986):    at com.parse.FindCallback.internalDone(FindCallback.java:31)
01-15 14:34:21.064: E/AndroidRuntime(10986):    at com.parse.Parse$6$1.run(Parse.java:973)
01-15 14:34:21.064: E/AndroidRuntime(10986):    at android.os.Handler.handleCallback(Handler.java:615)
01-15 14:34:21.064: E/AndroidRuntime(10986):    at android.os.Handler.dispatchMessage(Handler.java:92)
01-15 14:34:21.064: E/AndroidRuntime(10986):    at android.os.Looper.loop(Looper.java:137)
01-15 14:34:21.064: E/AndroidRuntime(10986):    at android.app.ActivityThread.main(ActivityThread.java:4944)
01-15 14:34:21.064: E/AndroidRuntime(10986):    at java.lang.reflect.Method.invokeNative(Native Method)
01-15 14:34:21.064: E/AndroidRuntime(10986):    at java.lang.reflect.Method.invoke(Method.java:511)
01-15 14:34:21.064: E/AndroidRuntime(10986):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1038)
01-15 14:34:21.064: E/AndroidRuntime(10986):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:805)
01-15 14:34:21.064: E/AndroidRuntime(10986):    at dalvik.system.NativeStart.main(Native Method)
01-15 14:34:21.134: D/dalvikvm(10986): GC_CONCURRENT freed 311K, 15% free 7079K/8327K, paused 21ms+4ms, total 118ms

A: The exception means that the returned list, List<ParseObject> latlanglist, is empty.
Instead of checking if the exception is null, you should check the constraints on the object you have to work on.
  if(latlanglist != null && !latlanglist.isEmpty()){

  }

A: Try this
if(e==null&& latlanglist!=null){
if(latlanglist.size()>0){
String firstItemId=latlanglist.get(0).getObjectId();
lat=latlanglist.get(0).getString("latitude");
lang=latlanglist.get(0).getString("longitude");
e1.setText(lat);
e2.setText(lang);
e3.setText(firstItemId);

Toast.makeText(getApplicationContext(),"Found the New Location:\nLatitude:"+lat+
"\nLongitude:"+lang+"\nObjectID:"+firstItemId,Toast.LENGTH_LONG).show();
}
else{

Toast.makeText(getApplicationContext(), "Error was found\n"+e,Toast.LENGTH_LONG).show();

}

}
}


text:
Q: Why doesn't my quick sort code work? Can anyone help me with my quick sort code because it doesn't get executed when I give data to it.
I don't get any answer. It's like it goes an infinite loop or something like that.
public class Provo {

public static void swap(int[] a, int i, int j)
{
    int temp=a[i];
    a[i]=a[j];
    a[j]=temp;
}

public static int HoarePartition(int m , int d, int[] a)
{ int pivot=a[m];
 int i=m;
 int j=d;

    while(i<j)
    {
        while(a[i]<pivot)
        {i=i+1;}

        while(a[j]>pivot)
        {j=j-1;}

        if(i<j)
         swap(a,i,j);
    }
    swap(a,m,j);

    return j;
}

public static void quicksort(int m, int d, int[] a)
{
    if (m<d)
    { int s=HoarePartition(m,d,a);
        quicksort(m,s-1,a);
        quicksort(s+1,d,a);
    }
}
}

A: This part might be problematic:
if(i<j)
  swap(a,i,j);

What happens when both a[i] and a[j] equals the pivot element? That means they'll get swapped, but neither lo nor hi will get decremented, hence resulting in an infinite loop.
Try this:
if(i<j)
  swap(a,i++,j--);

That basically does a post-increment/decrement, ensuring that lo and hi get closer after every iteration.

A: Problem is in HoarePartition() function
the left index i.e. i should start searching for a value (greater than pivot) one ahead from the pivot itself.
so statement int i=m; should be  int i=m+1;
EDIT:

Ensuring while(i<=j) rather than while(i<j) should do the trick