text:
Q: Can "what" be plural? I searched The Corpus of Contemporary American English (COCA) for "what make you".
10 results were returned.
Here are some of the results.

GROSS: So what happens, in a way, is that this young star is afraid he's being stalked
  in the first part of the movie, but by the second part of the movie he's kind of stalking
  this guy who works in the video store who wants to be a filmmaker.
  He's stalking this kind of regular guy who wishes that he was well-known and making movies.
  What make you think about this reverse stalking?

.

LAUER: How about carbs? You hear people all the time say stay away from carbs,
   they're what make you fat.

.

" Permit me to inspect your lips, " Albrecht tells Nicole later as they walk the streets to their quarters. " What? Why? Are they soiled? " The Norman wipes them with a kerchief. " No, " says Albrecht. " I thought they might have turned brown from kissing our Master's arse. " Nicole shoves the laughing Saxon, with no more effect than if he had shoved a tree. Rather it is the Norman who staggers backward a few steps. " What make you of the Englishman's notion? " asks Albrecht. " That the traversed distance is proportional to half the weight of the body and the doubling-I mean, the " squaring' -of the elapsed time. " He cocks his head, his gaze on some unseen world. " If the body be uniform and the space a void. But would it be true in a plenum and for a heterogeneous body? Suppose we drop two bodies in water? One may fall more slowly than the other depending

.

Joining me now is John Banzhaf of George Washington University. He's in favor of a fat tax. Also with me, Jacob Sullum, senior editor of " Reason " magazine. He says the government ought to stay out of it. Gentlemen, good to see both of you. I'm going to start with you tonight, professor. Most of these people say that they don't choose to be overweight. They are addicted to food. What make you think by putting a tax on fatty foods, it will actually discourage folks from eating them? JOHN-BANZHAF-FAVO: It's very simple. We tried that with cigarettes which we know are addictive and state after state finding out just how expensive smoking is about $140 billion, have dramatically increased the tax. We've seen corresponding declines or dramatic ones in smoking. We're saving an awful lot of money. By the way, the total cost of obesity estimated by the U.S. Surgeon General is about $120

.

We would never take his statements at face value. We were always looking for what's the plot behind it, what's the political motivation behind it? And all politicians are irritated by that kind of thing. I think Clinton hated it more than most. BERNARD KALB, CO-HOST: Ann, the press has a way of giving itself an acquittal in its rich profundity. Now you've been around. And you've seen a number of presidents come through the White House. Putting aside the quality of presidents, what make you of the quality of journalists who are covering the president? ANN COMPTON, ABC NEWS: It really depends so much on the issues you have out there and these external items outside of the presidency that come in. George Bush had the Berlin Wall fall down. And then he had a Persian Gulf War. And when you have a big, major story moving like that and reporters chasing what -- certainly not good news, but good, meaty stories like that and not focusing on the personal

I searched Google Books for "what make you".
https://www.google.co.jp/?gws_rd=ssl#q=%22what+make+you%22&tbm=bks&start=70
It returned 220,000 examples.
Not all of them use "what" as plural, but many of them do.
For example:

God answered and said "Jesus held everything in his hands and he was human,
  he held the heaven and the earth, the erath destroyed itself three times
  and Jesus still had compassion for it, so what make you so worthy to bring this news to me?"
  (The Next Level by Qweon Lee Drayton-Washington
  http://www.fictiondb.com/author/qweon-lee-drayton-washington~the-next-level~454899~b.htm)

.

Meanwhile, Baker was now holding a sawed off shotgun under the countrer
  just in case Danny needed him for reinforcement.
  "What make you think that I would help you? Did you helped me when I went up?"
  Daniel boasted.
  (The Bridge Back: Sisters, Cousins, Foes and Lovers by Betty Ann
  http://www.amazon.co.uk/The-Bridge-Back-Sisters-Cousins-ebook/dp/B0059HL63O)

.

"Don't be different," we are counseled, "go along with the crowd.
  What make you think you have an inside track denied to the rest of us?
  (Speaking of Christianity:Practical Compassion, Social Justice and Other Wonders
  by Robert McAfee Brown
  http://www.goodreads.com/book/show/481424.Speaking_of_Christianity)

Are these sentences using "what make you" grammatically correct?

A: The first example looks like an awkward confluence of What do you make of this? and What do you think of this?  It's either a typo or some written form of garbled thought.
The second example is "...they are what make you fat".  In that example, what is referring to they, which in turn is standing for carbs.  That sentence is not incorrect, it is just conversational.  People do speak that way, however it is confusing in the written form.
Now that you have added other examples:  What is a pronoun. The noun for which it stands may be either singular or plural. The rule is to look for the noun, which may be unexpressed, and then to match the verb form to the noun.
What make you? as a way to say "what do you think?" is correct.  The last example what make you think, the noun to which what is referring is not clear to me.
Only one of your examples was originally written. The others are transcripts, verbatim reporting of speech. What is written to be read tends to be more clear than speech.


text:
Q: Alignment of two elements in html,css I have the following code:

@import url('https://fonts.googleapis.com/css?family=Merriweather|Open+Sans');
.blogmaster {
  display: flex;
}

.blogmaster div {
  width: 98.6%;
}

@media all and (max-width: 500px) {
  .blogmaster {flex-flow: wrap;}
}

.container1{
  display: flex;
  justify-content: center;
  padding: 20px;
    overflow: hidden;
}

.square:hover {
    -webkit-transform: translate(20px, -10px);
    -ms-transform: translate(10px, -10px);
    transform: translate(10px, -10px);
    -webkit-box-shadow: 0 5px 20px rgba(0, 0, 0, 0.08);
    box-shadow: 0 5px 20px rgba(0, 0, 0, 0.08);
     }

.square{
  width: 460px;
    height: 430px;
    background: white;
  border-radius: 4px;
  box-shadow: 0px 5px 20px #D9DBDF;
  -webkit-transition: all 0.3s ease;
  -o-transition: all 0.3s ease;
  transition: all 0.3s ease;
}

.mask{
  clip: rect(0px, 460px, 220px, 0px);
  border-radius: 4px;
  position: absolute;
}

img1{
  width: 560px;
  }

.h11{
  margin: auto;
  text-align: left;
  margin-top: 240px;
  padding-left: 30px;
  padding-right: 30px;
  font-family: 'Merriweather', serif;
  font-size: 24px;
}
p9 {
  text-align: justify;
  font-family: 'Open Sans', sans-serif;
  font-size: 12px;
  color: #C8C8C8;
  line-height: 18px;
  padding-left: 30px;
  padding-right: 30px;
  display: block;
}

.button56 {
    background-color: #3EDD84;
    color: white;
    width: 100px;
    padding: 10px 18px;
    border-radius: 3px;
    text-align: center;
    text-decoration: none;
    display: block;
    margin-top: 15px;
    margin-left: 30px;
    margin-right: 70px;
    font-size: 12px;
    cursor: pointer;
    font-family: 'merriweather';
}

Sample Text Goes here

        <p9>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Aliquam in.</p9>

Read More

Sample Text Goes Here

        <p9>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Aliquam in.</p9>

Read More

When you run the above code, open it in a new page, inspect it to view it on a smaller device, then that is exactly what I am looking for. (Except, the image's width is a bit wider for some reason, but I can fix it later)
The two cards are algined vertically in responsive mode or when you view it on a smaller device.
The problem now is that when you want to view the cards on a larger screen, then the cards are still placed vertically, which is not what I want.
I am getting this output:

Expected Output:
When the user views the cards on a large screen such as a laptop or desktop, then this should be the output:

On a large screen, they should be placed beside each other with that amount of space between of them as seen in the expected output picture.
But, on a smaller screen, they should be placed vertically, which works fine. So, the only issue is getting the two cards to be beside each other and with that amount of space between them as seen in the expected output picture on a larger screen. Any suggestions?

A: Make parent div with style (display: flex),
then inside parent div make two child div having styles with (width: 50%),
then inside each child div put your cards..
Also you can use or see bootstrap cards and code structure

A: here is your expected result, you have to work on your cards

@import url('https://fonts.googleapis.com/css?family=Merriweather|Open+Sans');
.blogmaster {
    display: flex;
}

.blogmaster div {
    width: 98.6%;
}

@media all and (max-width: 500px) {
    .blogmaster {
        flex-flow: wrap;
    }
}

.container1 {
    display: flex;
    justify-content: center;
    padding: 20px;
    overflow: hidden;
}

.square:hover {
    -webkit-transform: translate(20px, -10px);
    -ms-transform: translate(10px, -10px);
    transform: translate(10px, -10px);
    -webkit-box-shadow: 0 5px 20px rgba(0, 0, 0, 0.08);
    box-shadow: 0 5px 20px rgba(0, 0, 0, 0.08);
}

.square {
    width: 460px;
    height: 430px;
    background: white;
    border-radius: 4px;
    box-shadow: 0px 5px 20px #D9DBDF;
    -webkit-transition: all 0.3s ease;
    -o-transition: all 0.3s ease;
    transition: all 0.3s ease;
}

.mask {
    clip: rect(0px, 460px, 220px, 0px);
    border-radius: 4px;
    position: absolute;
}

img1 {
    width: 560px;
}

.h11 {
    margin: auto;
    text-align: left;
    margin-top: 240px;
    padding-left: 30px;
    padding-right: 30px;
    font-family: 'Merriweather', serif;
    font-size: 24px;
}

p9 {
    text-align: justify;
    font-family: 'Open Sans', sans-serif;
    font-size: 12px;
    color: #C8C8C8;
    line-height: 18px;
    padding-left: 30px;
    padding-right: 30px;
    display: block;
}

.button56 {
    background-color: #3EDD84;
    color: white;
    width: 100px;
    padding: 10px 18px;
    border-radius: 3px;
    text-align: center;
    text-decoration: none;
    display: block;
    margin-top: 15px;
    margin-left: 30px;
    margin-right: 70px;
    font-size: 12px;
    cursor: pointer;
    font-family: 'merriweather';
}

.parent-div {
    display: flex;
    flex-wrap: nowrap;
    justify-content: center;
}
@media screen and (max-width: 480px) {
.parent-div {
    flex-direction: column;
}
<!DOCTYPE html>

    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <link rel="stylesheet" href="style.css">

Sample Text Goes here

                                <p9>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Aliquam in.</p9>

Read More

Sample Text Goes Here

                                <p9>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Aliquam in.</p9>

Read More

redpajama_set_name: RedPajamaStackExchange


text:
Q: IOS Provisioning Profile and Push Notification on New Device I can send push notification to an IOS device (IOS 5.1 IPAD 3rd gen) and handle notifications etc.. So it works quite well.
Now I have to use another device(IOS 5.1 IPAD 3rd gen), on organizer by right clicking I add my device to provisioning profile I can install my app to device but I can not send push notifications because I can not get device's token.
I guess it is because when I right click and add device to my provisioning profile It only adds the iOS Team Provisioning Profile rather then myApp Development Profile
On apples developer portal I have:

On My Organizer In Library-->Provisioning Profiles

On my teams

And I handle error code on push Notification:
- (void)application:(UIApplication*)application didFailToRegisterForRemoteNotificationsWithError:(NSError*)error
{
    NSLog(@"Failed to get token, error: %@", error);
}

Error Is: Failed to get token, error: Error Domain=NSCocoaErrorDomain Code=3000 "no valid 'aps-environment' entitlement string found for application" UserInfo=0xxxxxxx {NSLocalizedDescription=no valid 'aps-environment' entitlement string found for application}
In case error is because provisioning profile:
How can add that Paper Developement profile to my device?
or
How can I learn device token and send push notification without creating provisioning profile all over?
Thanks in advance

A: I had similar issues before so I will list your possible issues,
Firstly do not use a provisioning profile with a wild card it is highly possible that your IOS Team Provisoning Profile includes a wild card. So just go to your device's provisioning profile on organizer and delete that IOS Team Provisoning Profile
Secondly go to your provisoning profiles on developer.apple and click edit as on your second picture in question. When you click edit you will see Modify click on that
and add your device by checking squares like below:

Click save and download new profile,  now go to your provisioning profiles on your organizer and delete previous Pape Developement Profile. Double click your downloaded profile or click refresh on your organizer. Now drag and drop proviosinig profile to your device on organizer.
Finally if none of above solves your problem that means probably your bundle identifier and your app id does not much in this case check this answer
Hope you solve this issue....

A: For me it was just changing the bundle identifier and code signing identity to IOS Developer. The bundle identifier Changing it back and forth and building between changes did the trick (not sure if this step necessary). Not sure what it really was. Hope this helps someone someday, probably not.


text:
Q: Upload server log into aws cloudwatch log using cloudwatch log agent in ubuntu aws support Centralized logs for server , we can send custom logs to cloudwatch logs mu awslogs.conf file code is
datetime_format = %d/%b/%Y:%H:%M:%S
file = /path/to/log/file/test.log
buffer_duration = 5000
log_stream_name = test
initial_position = start_of_file
log_group_name = server1

It creates a log file in aws cloudwatch log named test in server1 group
But my custom log file name is current date for example
filename = test-2018-03-15.log
I tried the following code
datetime_format = %d/%b/%Y:%H:%M:%S
file = /path/to/log/file/test-%Y-%m-%d.log
buffer_duration = 5000
log_stream_name = test-%Y
initial_position = start_of_file
log_group_name = server1

It doesn't work
and also i tried in file path
   file = /path/to/log/file/test-{%Y-%m-%d}.log
it also doesn't work
How to upload log files which have current date in their filename to aws cloudwatch using cloudwatch log agent


text:
Q: adding a line at the end of the .bat file ignoring the newline I have a .bat file with the following structure:
istruction1[newline]

I would like to append some parameters in a way that the resulting file is:
istruction1 param

currently i have:
istruction1[newline]
param

Basically I want to get rid of the newline...how can I do that?
thanks a lot!

A: Try this one:
@echo off
for /f "delims=" %%i in (my.bat) DO echo %%i param

This little script will append param at the end of every (non empty) line in your input file (my.bat). You can also issue that directly from the command line, simply substituting %% with a single %:
for /f "delims=" %i in (my.bat) DO echo %i param


text:
Q: Invalid roslaunch XML syntax: not well-formed dji package When i try to launch the package by typing
roslaunch dji_sdk sdk.launch
where the launch file content :
launch>
    <node pkg="dji_sdk" type="dji_sdk_node" name="dji_sdk" output="screen">
    <!-- node parameters -->
    <param name="serial_name" type="string" value="/dev/ttyTHS0"/>
    <param name="baud_rate" type="int" value="921600"/>
    <param name="app_id" type="int" value="1079440"/>
    <param name="app_version" type="int" value="1"/>
    <param name="align_time" type="bool" value="false"/>
    <param name="enc_key" type="string" value="39d353a8e9ad01b6c659111904bae57ebb138785aa5159699383f28da3f56563"/>
    <param name="use_broadcast" type="bool" value="false"/>
    </node>
</launch>

it gives me this error :
Invalid roslaunch XML syntax: syntax error: line 1, column 0
The traceback for the exception was written to the log file

A: the error here was because of missing < in the first line.


text:
Q: Why is scrolling interacting badly with my webscraping? I'm trying to scrape all the corner betting odds for a given game at skybet, but it looks like scrolling is messing things up in my loop. When I print section.text it looks like its doing what I want but then it clicks the wrong thing?
And when I don't scroll it will only click on the first few odds sections before the code just freezes.
Any help would be really appreciated thanks!
Also, I made the odds_sections refresh itself at each iteration because I thought that might be the problem.
driver = webdriver.Safari()
driver.get("https://m.skybet.com/football/competitions")
driver.maximize_window()

#click accept cookie
try:
    button_cookie = WebDriverWait(driver, 20).until(
        EC.element_to_be_clickable((By.XPATH, "//body/div[2]/div[1]/a[2]"))
        )
    button_cookie.click()
except:
    print("no cookie")

#find location of premier league
pl = driver.find_elements_by_class_name("split__title")
locate_pl=0
link_name = pl[locate_pl].text
while link_name != "Premier League":
    locate_pl += 1
    link_name = pl[locate_pl].text

pl[locate_pl].click()
N = locate_pl + 1
#use N now to find pl matches
time.sleep(2)

#click on first match
button_match = driver.find_element_by_xpath("//div[@id='competitions']/ul[1]/li[{}]/div[1]/table[2]/tbody[1]/tr[2]/td[1]/a[1]".format(N))
teams = driver.find_element_by_xpath("//div[@id='competitions']/ul[1]/li[{}]/div[1]/table[2]/tbody[1]/tr[2]/td[1]/a[1]/b/span".format(N))
button_match.send_keys(Keys.ENTER)
time.sleep(2)

#find and click corners button
try:
    button_corners = WebDriverWait(driver, 10).until(EC.presence_of_all_elements_located((By.CLASS_NAME,"_1ouz2ki")))
#button_corners = driver.find_elements_by_class_name("_1ouz2ki")
except:
    print("no corners")
n=0
link_name = button_corners[n].text
while link_name != "Corners":
    n += 1
    link_name = button_corners[n].text

button_corners[n].click()

#Now we will scrape all corner odds for this game.
odds_sections = driver.find_elements_by_class_name('_t0tx82')
N_sections = len(odds_sections)
c=0
scroll_to = 35
#the issue is within this loop
while c <= N_sections:

    odds_sections = driver.find_elements_by_class_name('_t0tx82')
    section = odds_sections[c]

    print(section.text)
    section.click()
    time.sleep(2)
    section.click()
    c += 1
    driver.execute_script("window.scrollTo(0,{})".format(scroll_to))


text:
Q: Testing PHP CURL file uploads on laptop (blocked by Norton) I'm testing PHP CURL on my laptop, but file uploads are blocked by Norton because of negative content length.
So, I think CURL is sending Content-Length: -1.
How do I get around that? By manually setting the content length? If so, what's the best way to do that?

A: It looks like I had curl_setopt($CURL, CURLOPT_POST, TRUE), and that wasn't a good idea. I removed it, and Norton doesn't complain and the script works.


text:
Q: Alternative to multicol that allows floating figures I have three columns landscape layout, and I need to be able to use floating figures, because otherwise I have arbitrary paragraph breaks where I can insert a [H] figure, and then the columns do not spread out correctly, and I cannot insert arbitrary line breaks to place the figures.
What alternatives to multicol exists that can have a floating figure (width of a column, height of less than the column) that don't force me to fiddle around with line breaks and justification?


text:
Q: Is a bad practice passing references of a View to a Presenter in MVP Pattern? I have a big project for Android with Kotlin using the MVP pattern, and I'm starting to struggle to do Unit Tests (testing the presenters mocking the view interfaces). The reason is I'm passing view references to my functions in the presenters and it's really bad having to mock them, example:
My code would look like:
class MainActivity : Activity(), MainActivityView {

    @BindView(R.id.numberTV)
    lateinit var numberTV : AppCompatTextView

    private val mainActivityPresenter = MainActivityPresenter(this)

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        mainActivityPresenter.onCreate()
    }

    override fun showNumber() {
        mainActivityPresenter.showNumber(numberTV, 22)
    }

}

interface MainActivityView {
    fun showNumber()
}

class MainActivityPresenter(private val mainActivityView: MainActivityView) {
    fun showNumber(numberTV: AppCompatTextView, number: Int) {
        numberTV.text = if (number < 0) {
            "Not compatible"
        } else if (number < 10) {
            number.toString()
        } else {
            "9+"
        }
    }

    fun onCreate() {
        mainActivityView.showNumber()
    }
}

My current problem is, when I'm testing the function showNumber(AppCompatTextView, Int) with Mockito in Unit Tests, I should mock the view just to pass the test (as it can't be null).
Which one would be a better approach to do Unit Tests here?
My thoughts are:

*

*Grabbing the numberTV: AppCompatTextView from the MainActivityPresenter, such as mainActivityPresenter.getBindViews().mainIV

*Returning just the text logic ("Not compatible", number.toString() or "9+") from the presenter, although sometimes the requirements require to do logic between more than view (2+)

What would you do?

EDIT
I would like to point out that not passing any View to the presenter, might be an issue with asynchronous calls.
Example: setting an image with Glide:
internal fun showImageAccordingToCache(cachedSplashScreenUri: String?, mainImageView: ImageView) {
    Glide.with(context)
            /**
             * Save in cache, but we say to load it from cache. Otherwise it will throw an error
             */
            .setDefaultRequestOptions(defaultDiskStrategy()
                    .onlyRetrieveFromCache(true))
            .load(cachedSplashScreenUri)
            .listener(object : RequestListener<Drawable> {
                override fun onLoadFailed(e: GlideException?, model: Any?, target: Target<Drawable>?, isFirstResource: Boolean): Boolean {
                    /**
                     * And when that error is thrown, we preload the image for the next time.
                     */
                    activityViewPresenter.showLogo()
                    loadImageInCache(cachedSplashScreenUri)
                    return true
                }

                override fun onResourceReady(resource: Drawable?, model: Any?, target: Target<Drawable>?, dataSource: DataSource?, isFirstResource: Boolean): Boolean {
                    return false
                }
            })
            .into(mainImageView)
}

A: I think you should not pass views to your presenter. Your presenter should call mainActivityView methods to show the required Data. This should be the method in your mainAcitivityView
override fun showNumber(number: String) {
    numberTV.text = number
}

And you should call this from your presenter like this
fun onCreate() {
   showNumber(22)
}

fun showNumber(number: Int) {
    numberString:String = if (number < 0) {
        "Not compatible"
    } else if (number < 10) {
        number.toString()
    } else {
        "9+"
    }
    mainActivityView.showNumber(numberString:String)
}

A: It's normal to have an interface View in your presenter. In your case MainActivityView is the interface that represents the contract your Activity must comply to. You'd normally pass that view in the constructor of the presenter (what you're already doing) on by using dagger to inject it into the presenter.
Now this, is not very usual:
 fun showNumber(numberTV: AppCompatTextView, number: Int) {
        numberTV.text = if (number < 0) {
            "Not compatible"
        } else if (number < 10) {
            number.toString()
        } else {
            "9+"
        }
    }

Now the presenter knows about "Android SDK components" which is not a good thing. In this case what you should be doing is this:
 fun showNumber(number: Int) {
        if (number < 0) {
            mainActivityView.setNumberText("Not compatible");
        } else if (number < 10) {
            mainActivityView.setNumberText(number.toString());
        } else {
            mainActivityView.setNumberText("9+");
        }
    }

To test this you would mock the view and see if depending on number each of those methods were actually called.(In java).
@Mock
MainActivityView view;

@Test
public fun shouldShowCorrectNumber() {

    int number = 10;
    presenter.showNumber(number);
    verify(view).showNumber("9+");
}

As for async calls, what I usually see when using the Glide library is that it is used in the activity, not in the presenter. Other types of async calls might go in other layers, for example. I usually see network calls in the Interactor layer with callbacks to the presenter:


text:
Q: How to enable Location Services for a WKWebView in Swift? My Browser app uses WKWebView but when I try to visit a website that needs to use Location Services (like Google Maps, for example), it doesn't work.
I have searched for a way to fix it and came across this question. I tried to add the string on the answer to the question to my Info.plist but it doesn't resolve the issue.
How can I fix this?
Thanks,
PastaCoder

A: I'm not sure how, but trying to add a string for NSLocationWhenInUseUsageDescription in the Info.plist did work yesterday and the issue has been resolved.


text:
Q: Splash approach in single activity shows everywhere splash theme I use this approach in my single activity app - Splash-screen approach in single Activity app
But everywhere in my layouts I see splash theme and this prevents me from working with views in Android Studio.
Can someone help me with this?

A: Android 12 now has a SplashScreen API, which enables a new app launch animation for all apps when running on a device with Android 12 or higher. This includes an into-app motion at launch, a splash screen showing your app icon, and a transition to your app itself, and for that, you don't need a Splash Activity.
As for your app, you need to set the theme only for SplashActivity. For other activity, set the theme to be the default one.


text:
Q: Kafka Consumer in play framework using java I have searched thousands of sites for kafka consumer example in play framework in java language. But not able to find any example. Can anyone provide details on how to write a service which consumes topics produced by kafka continuously.
Thanks

A: Play is a web-framework. The underlying Actor system relies on Akka.
The Akka Kafka API is called Alpakka, so I suspect you are searching in the wrong keywords
To combine both Akka and Play w/ Kafka, you can even use the Lagom Framework

Otherwise, of course you can use plain Java consumer as well, regardless of Play Framework

provide details on how to write a service which consumes topics produced by kafka continuously

KafkaConsumer c = new KafkaConsumer(props);
while (true) {
    ConsumerRecords r = c.poll(1000);
    ...
}

A: Recently I have faced a similar issue, so I will add few notes after my researches.
I will describe how to use plain KafkaConsumer in Play Framework (but in scala not Java). It is always worth to know how lower-level components works, but after all I strongly encourage you to consider use libraries like Alpakka. For example in my last project I decided to use akka-projection which is build on Alpakka. It composes with Akka nicely and give you some extra value like easy configuration of restart strategy in case of failure.
To use plain KafkaConsumer in Play Framework:

*

*Create Singleton which will manage KafkaConsumer. In the following example while loop runs in dedicated thread. Plain KafkaConsumer is closed during application shutdown.

@Singleton
class SampleKafkaConsumer @Inject()(coordinatedShutdown: CoordinatedShutdown) extends Logging {

  logger.info("SampleKafkaConsumer starts")

  private val executionContext: ExecutionContext = ExecutionContext.fromExecutor(Executors.newSingleThreadExecutor())
  private val stopConsumer: AtomicBoolean = new AtomicBoolean(false)

  private val properties = new Properties()
  properties.put("bootstrap.servers", "localhost:6003")
  properties.put("group.id", s"sample-group-id")
  properties.put("key.deserializer", classOf[StringDeserializer])
  properties.put("value.deserializer", classOf[StringDeserializer])

  val kafkaConsumer = new KafkaConsumer[String, String](properties)
  kafkaConsumer.subscribe(Set("sample-topic").asJava)

  Future {
    while (!stopConsumer.get()) {
      kafkaConsumer.poll(Duration.ofSeconds(3)).asScala
        .foreach(r => {
          logger.info(s"SampleKafkaConsumer receives record: $r")
        })
    }
    logger.info(s"SampleKafkaConsumer quits 'while(true)' loop.")
  }(executionContext)
  .andThen(_ => kafkaConsumer.close())(executionContext)
  .andThen {
    case Success(_) =>
      logger.info(s"SampleKafkaConsumer succeed.")
    case Failure(e) =>
      logger.error(s"SampleKafkaConsumer fails.", e)
  }(executionContext)

  coordinatedShutdown.addTask(CoordinatedShutdown.PhaseServiceStop, "SampleKafkaConsumer-stop"){() =>
    logger.info("Shutdown-task[SampleKafkaConsumer-stop] starts.")
    stopConsumer.set(true)
    Future{ Done }(executionContext).andThen{
      case Success(_) => logger.info("Shutdown-task[SampleKafkaConsumer-stop] succeed.")
      case Failure(e) => logger.error("Shutdown-task[SampleKafkaConsumer-stop] fails.", e)
    }(executionContext)
  }
}

*Mark it as "eager" using play module:

class KafkaModule extends AbstractModule with Logging {

  override def configure(): Unit = {
    logger.info("Starting KafkaModule")
    bind(classOf[SampleKafkaConsumer]).asEagerSingleton()
  }
}

3.Enable your module in play config file:
play.modules.enabled += "kafka.KafkaModule

And it is all. I described everything in details here.


text:
Q: listView item listeners When using a listView I noticed that, on setting up a checkBox in a listView, the listView.OnItemClicked listener does not work ! For now, I am trying to implement two different on click listeners for the listView. The first one is for the listView body and the second one for the listView's body's checkBox. The listView's body is to (for now) generate a toast and the checkBox is to generate a another toast(for now).
The problem I am facing is when referring to checkBox.onClick
the logic is only implemented to the last(or any random,but only one) checkbox in the layout.
The listView layout looks like this:

MainActivity.java:
    private void registerClickCallBack() {
        // TODO Auto-generated method stub
        ListView list = (ListView)findViewById(R.id.listViewComplex);
        list.setOnItemClickListener(new AdapterView.OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> parent, View viewClicked, int position,
                    long id) {
                // TODO Auto-generated method stub

                Random clickedRandom = randomList.get(position);
                String message = "You have clicked position "+position+" which is titled "+clickedRandom.getTitle();
                Toast.makeText(MainActivity.this, message, Toast.LENGTH_LONG).show();
                final CheckBox check= (CheckBox)findViewById(R.id.checkBoxComplex);
                check.setOnClickListener(new OnClickListener() {

                    @Override
                    public void onClick(View v) {
                        // TODO Auto-generated method stub
                        if(check.isChecked()){
                        Toast.makeText(MainActivity.this, "Checked", Toast.LENGTH_LONG).show();
                        }
                    }
                });
            }
        });
    }

}

A: Add this
  android:focusable="false"

to checkbox in xml.
Assuming you want to dispaly a toast on click of a check box. Try the below
You should use a view holder for smooth scrolling and performance.
http://developer.android.com/training/improving-layouts/smooth-scrolling.html
Initialize your listiew in onCreate. From your previous code before the edit i could see you intializing listview twice. No need for that.
Change you activity to
 public class MainActivity extends Activity {
    private List<Random> randomList = new ArrayList<Random>();
    ListView list;
    ArrayAdapter<Random> adapter;
    private  SparseBooleanArray mCheckStates;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        list = (ListView)findViewById(R.id.listViewComplex);
        adapter = new MyListAdapter();
        populateRandomList();
        populateListView();
        registerClickCallBack();
    }

    private void populateRandomList() {
        // TODO Auto-generated method stub
        randomList.add(new Random("Title One", "Simple", "Status: OK", R.drawable.ic_launcher));
        randomList.add(new Random("Title Two", "Complex", "Status: WORKING", R.drawable.ic_launcher));
        randomList.add(new Random("Title Three", "Moderate", "Status: NOT OK", R.drawable.ic_launcher));
        randomList.add(new Random("Title Four", "Simple", "Status: BAD", R.drawable.ic_launcher));
        randomList.add(new Random("Title Five", "Moderate", "Status: NOT OK", R.drawable.ic_launcher));
        randomList.add(new Random("Title Six", "Simple", "Status: WORKING",R.drawable.ic_launcher));
        randomList.add(new Random("Title Seven", "Complex", "Status: EXCELLENT", R.drawable.ic_launcher));
        randomList.add(new Random("Title Eight", "Complex", "Status: NBA", R.drawable.ic_launcher));
    }

    private void populateListView() {
        list.setAdapter(adapter);
    }

    private class MyListAdapter extends ArrayAdapter<Random> implements CompoundButton.OnCheckedChangeListener{

        public MyListAdapter(){
            super(MainActivity.this,R.layout.layout_complex,randomList);
            mCheckStates = new SparseBooleanArray(randomList.size());
        }

        @Override
        public int getCount() {
            // TODO Auto-generated method stub
            return randomList.size();
        }

        public View getView(int position, View convertView, ViewGroup parent){
            ViewHolder vh;
            if(convertView == null){
                convertView = getLayoutInflater().inflate(R.layout.layout_complex,parent,false);
                vh = new ViewHolder();
                vh.imageView = (ImageView)convertView.findViewById(R.id.itemImage);
                vh.titleText = (TextView)convertView.findViewById(R.id.itemTitle);
                vh.typeText = (TextView)convertView.findViewById(R.id.itemType);
                vh.statusText = (TextView)convertView.findViewById(R.id.itemStatus);
                vh.cb = (CheckBox) convertView.findViewById(R.id.checkBoxComplex);
                convertView.setTag(vh);
        } else {
            vh = (ViewHolder) convertView.getTag();
        }

            Random currentItem = randomList.get(position);
            vh.imageView.setImageResource(currentItem.getIconID());
            vh.titleText.setText(currentItem.getTitle());
            vh.typeText.setText(currentItem.getType());
            vh.statusText.setText(currentItem.getStatus());
            vh.cb.setTag(position);
            vh.cb.setChecked(mCheckStates.get(position, false));
            vh.cb.setOnCheckedChangeListener(this);
            return convertView;

        }
         public boolean isChecked(int position) {
                return mCheckStates.get(position, false);
            }

            public void setChecked(int position, boolean isChecked) {
                mCheckStates.put(position, isChecked);

            }

            public void toggle(int position) {
                setChecked(position, !isChecked(position));

            }
        @Override
        public void onCheckedChanged(CompoundButton buttonView,
                boolean isChecked) {
             mCheckStates.put((Integer) buttonView.getTag(), isChecked);
             if(isChecked)
                {
                Toast.makeText(MainActivity.this, "Checked at "+(Integer) buttonView.getTag(), Toast.LENGTH_SHORT).show();
                }

        }
        class ViewHolder
        {
            TextView titleText,typeText,statusText;
            ImageView imageView;
            CheckBox cb;
        }
    }

    private void registerClickCallBack() {
        list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View viewClicked, int position,
                    long id) {
                Random clickedRandom = randomList.get(position);
                String message = "You have clicked position "+position+" which is titled "+clickedRandom.getTitle();
                Toast.makeText(MainActivity.this, message, Toast.LENGTH_LONG).show();

            }
        });
    }
}

Snap shot

A: You can also use
android:descendantFocusability="blocksDescendants"

as explained in this answer: https://stackoverflow.com/a/13415566/2812681


text:
Q: TypeError: Cannot read property 'Symbol(Symbol.iterator)' of undefined RxJS I want to trigger this catch block and confirm that handleError() runs:
@Injectable()
export class JwtService {
    private actionUrl: string;
    private headers: Headers;

    constructor(private http: Http, private configurationService: ConfigurationService, private _utilsSvc: UtilitiesService) {}

    getToken() {
        if (this.configurationService.config) {
            return this.http.post(this.configurationService.config.jwtUrl, { "brand": "IAG" })
                .map(this._utilsSvc.parseJson)
                .catch(this.handleError);
        }
    }

    handleError(error: any) {
        let errorStatus = error.status;
        return Observable.throw(errorStatus);
    }
}

utilsSvc class:
@Injectable()
export class UtilitiesService {

    constructor(private http: Http) { }

    fetchFile(url) {
        return this.http.get(url)
            .toPromise();
    }

    parseJson(response: Response) {
        return response.json();
    }
}

I'm trying to pass it invalid json to cause an error to be caught:
it("Should handle error", () => {
    let resOp = new ResponseOptions({
        body: "invalid json"
    });
    mockHttpResponse = new Response(resOp);
    mockBackend.connections.subscribe(connection => {
        connection.mockRespond(mockHttpResponse);
    });
    spyOn(jwtService, 'handleError');
    jwtService.getToken().subscribe((res) => {
        expect(jwtService.handleError).toHaveBeenCalled();
    });
});

I'm getting this error:

TypeError: Cannot read property 'Symbol(Symbol.iterator)' of undefined

How do cause the catch block to catch the error?
Here is my whole test file:
/// <reference path="../../typings/globals/es6-shim/index.d.ts"/>
/// <reference path="../../typings/globals/jasmine/index.d.ts" />
import { inject, TestBed, ComponentFixture } from "@angular/core/testing";
import { RouterTestingModule } from "@angular/router/testing";
import { Headers, HttpModule, BaseRequestOptions, XHRBackend, Response, Http, ResponseOptions } from "@angular/http";
import { MockBackend, MockConnection } from "@angular/http/testing";
import { Component, DebugElement } from "@angular/core";
import { By } from '@angular/platform-browser';
import "rxjs/add/operator/toPromise";
import { Observable } from "rxjs/Rx";
import "rxjs/add/operator/toPromise";

import { AuthenticationLibrary } from "../../app/services/authenticationLibrary.service";
import { ConfigurationService } from "../../app/services/configuration.service";
import { FrontEndLoggingService } from "../../app/services/frontEndLogging.service";
import { JwtService } from "../../app/services/jwt.service";
import { UtilitiesService } from "../../app/services/utilities.service";

describe("Authentication service", () => {

    let mockBackend;
    let jwtService;
    let configSvc;
    let http;
    let feLogSvc;
    let mockHttpResponse;

    beforeEach(() => {
        TestBed.configureTestingModule({
            imports: [HttpModule],
            providers: [
                { provide: XHRBackend, useClass: MockBackend },
                ConfigurationService,
                FrontEndLoggingService,
                JwtService,
                UtilitiesService
            ]
        });

        mockBackend = TestBed.get(XHRBackend);
        http = new Http(mockBackend, new BaseRequestOptions);
        feLogSvc = TestBed.get(FrontEndLoggingService);
        configSvc = TestBed.get(ConfigurationService);
        configSvc.config = {
            enableFrontEndDebugLogs: true,
            baseUrl: "www.someurl.com",
            providerEndpoint: "someMachine",
            categoriesEndpoint: "someCatEndpoint"
        }

        jwtService = new JwtService(
            TestBed.get(Http),
            configSvc,
            TestBed.get(UtilitiesService)
        )

    });

    it("Should get token", () => {
        let resOp = new ResponseOptions({
            body: {
                "token": "Bearer ABC123",
                "brand": "AMI"
            }
        })
        mockHttpResponse = new Response(resOp)
        mockBackend.connections.subscribe(connection => {
            connection.mockRespond(mockHttpResponse);
        });
        jwtService.getToken().subscribe(response => {
            expect(response.token).toBe("Bearer ABC123");
        });
    });

    it("Should handle error", () => {
        let resOp = new ResponseOptions({
            body: "sdvhfujvn"
        });
        mockHttpResponse = new Response(resOp);
        mockBackend.connections.subscribe(connection => {
            connection.mockRespond(mockHttpResponse);
        });
        spyOn(jwtService, 'handleError');
        jwtService.getToken().subscribe((res) => {
            expect(jwtService.handleError).toHaveBeenCalled();
        });
    });
});

A: Issue is here
spyOn(jwtService, 'handleError');

spyOn will override this method so it will not return anything while catch is expecting you to return an observable.
To fix this you need to return from that method
it("Should handle error", () => {
        let resOp = new ResponseOptions({
            body: "sdvhfujvn"
        });
        mockHttpResponse = new Response(resOp);
        mockBackend.connections.subscribe(connection => {
            connection.mockRespond(mockHttpResponse);
        });
        spyOn(jwtService, 'handleError').and.callFake(function () {
            return Observable.from("fake error");
        });
        jwtService.getToken()
            .subscribe((res) => {
                expect(jwtService.handleError).toHaveBeenCalled();
            });
    });

This test will work but I am not sure if this test make any sense


text:
Q: Proving that $\sum\limits_{a\in \Bbb{F}_q^\times} a^k=0$ for $k\not\equiv 0\mod q-1$
Let $p$ be a prime number, and $q=p^n$ for some $n$. Consider the field $\Bbb{F}_q$. When $k\not\equiv 0\mod q-1$, then $\sum\limits_{a\in \Bbb{F}_q^\times} a^k=0$.

Is this assertion true? And if it is, could someone give a hint as to why it is?

A: Yes, it is true. Because $\Bbb F_q^*$ is cyclic (it is well known fact) one has for some generator $$\Bbb F_q^*=\{g,\space g^2,\space g^3,\space g^4\cdots,g^n,\cdots,\space g^{q-1}=1\}$$ and since $k\ne m(q-1)$ for all $m$ there is a $g^n\ne 1\Rightarrow g^{nk}\ne 1$; furthermore $a^k\to  g^{nk}a^k$ is a bijection ($g^{nk}a^k=g^{nk}b^k\Rightarrow a^k=b^k $ and for all $b^k$ there is $a$ such that
$a^k=g^{-kn}b^k\iff b^k=g^{nk}a^k$) hence $$\{g^{nk}a^k\}_{a\in\Bbb F^*_q}=\Bbb F_q^*$$ It follows $$\sum_{a\in\Bbb F^*_q}a^k=\sum_{a\in\Bbb F^*_q}g^{nk}a^k\iff\sum_{a\in\Bbb F^*_q}a^k-\sum_{a\in\Bbb F^*_q}g^{nk}a^k=0$$
$$(1-g^{nk})\sum_{a\in\Bbb F^*_q}a^k= 0\Rightarrow\sum_{a\in\Bbb F^*_q}a^k=0$$


text:
Q: creating itemsets in apriori algorithm I am reading about association analysis in book titled Machine learning in action. Following code is given in book

The k-2 thing may be a little confusing. Let's look at that a little
  further. When you were creating {0,1} {0,2}, {1,2} from {0}, {1}, {2},
  you just combined items. Now, what if you want to use {0,1} {0,2},
  {1,2} to create a three-item set? If you did the union of every set,
  you'd get {0, 1, 2}, {0, 1, 2}, {0, 1, 2}. That's right. It's the same
  set three times. Now you have to scan through the list of three-item
  sets to get only unique values. You're trying to keep the number of
  times you go through the lists to a minimum. Now, if you compared the
  first element {0,1} {0,2}, {1,2} and only took the union of those that
  had the same first item, what would you have? {0, 1, 2} just one time.
  Now you don't have to go through the list looking for unique values.

def aprioriGen(Lk, k): #creates Ck
    retList = []
    lenLk = len(Lk)
    for i in range(lenLk):
        for j in range(i+1, lenLk):
            L1 = list(Lk[i])[:k-2]; L2 = list(Lk[j])[:k-2] # Join sets if first k-2 items are equal
            L1.sort(); L2.sort()
            if L1==L2:
                retList.append(Lk[i] | Lk[j])
    return retLis

Suppose i am calling above function
Lk = [frozenset({2, 3}), frozenset({3, 5}), frozenset({2, 5}), frozenset({1, 3})]

k = 3

aprioriGen(Lk,3)

I am geting following output
[frozenset({2, 3, 5})]

I think there is bug in above logic since we are missing other combinations like {1,2,3}, {1,3,5}. Isn't it? Is my understanding right?

A: I think you are following the below link, Output set depends on the minSupport what we pass.
http://adataanalyst.com/machine-learning/apriori-algorithm-python-3-0/
If we reduce the minSupport value to 0.2, we get all sets.
Below is the complete code
# -*- coding: utf-8 -*-
"""
Created on Mon Dec 31 16:57:26 2018

@author: rponnurx
"""

from numpy import *

def loadDataSet():
    return [[1, 3, 4], [2, 3, 5], [1, 2, 3, 5], [2, 5]]

def createC1(dataSet):
    C1 = []
    for transaction in dataSet:
        for item in transaction:
            if not [item] in C1:
                C1.append([item])

    C1.sort()
    return list(map(frozenset, C1))#use frozen set so we
                            #can use it as a key in a dict

def scanD(D, Ck, minSupport):
    ssCnt = {}
    for tid in D:
        for can in Ck:
            if can.issubset(tid):
                if not can in ssCnt: ssCnt[can]=1
                else: ssCnt[can] += 1
    numItems = float(len(D))
    retList = []
    supportData = {}
    for key in ssCnt:
        support = ssCnt[key]/numItems
        if support >= minSupport:
            retList.insert(0,key)
        supportData[key] = support
    return retList, supportData

dataSet = loadDataSet()
print(dataSet)

C1 = createC1(dataSet)

print(C1)

#D is a dataset in the setform.

D = list(map(set,dataSet))
print(D)

L1,suppDat0 = scanD(D,C1,0.5)
print(L1)

def aprioriGen(Lk, k): #creates Ck
    retList = []
    print("Lk")
    print(Lk)
    lenLk = len(Lk)
    for i in range(lenLk):
        for j in range(i+1, lenLk):
            L1 = list(Lk[i])[:k-2]; L2 = list(Lk[j])[:k-2]
            L1.sort(); L2.sort()
            if L1==L2: #if first k-2 elements are equal
                retList.append(Lk[i] | Lk[j]) #set union
    return retList

def apriori(dataSet, minSupport = 0.5):
    C1 = createC1(dataSet)
    D = list(map(set, dataSet))
    L1, supportData = scanD(D, C1, minSupport)

    L = [L1]
    k = 2
    while (len(L[k-2]) > 0):
        Ck = aprioriGen(L[k-2], k)
        Lk, supK = scanD(D, Ck, minSupport)#scan DB to get Lk
        supportData.update(supK)
        L.append(Lk)
        k += 1
    return L, supportData

L,suppData = apriori(dataSet,0.2)

print(L)

Output:
[[frozenset({5}), frozenset({2}), frozenset({4}), frozenset({3}), frozenset({1})], [frozenset({1, 2}), frozenset({1, 5}), frozenset({2, 3}), frozenset({3, 5}), frozenset({2, 5}), frozenset({1, 3}), frozenset({1, 4}), frozenset({3, 4})], [frozenset({1, 3, 5}), frozenset({1, 2, 3}), frozenset({1, 2, 5}), frozenset({2, 3, 5}), frozenset({1, 3, 4})], [frozenset({1, 2, 3, 5})], []]
Thanks,
Rajeswari Ponnuru


text:
Q: SwiftUI always throws argument error for no reason struct HomeList: View {
 var body: some View {
  ScrollView { // ERROR HERE: 'Argument passed to call that takes no arguments'
   HStack {
    ForEach(0.. < 3) {
     item in
      ScrollView()
    }
   }
   Spacer()
  }
 }
}

It always throws the error Argument passed to call that takes no argument, only one person has had this issue and they said restarting their project worked for them,
I tried it and the error still gets thrown? Is it a bug or?
Thanks,
Nathan

A: You cannot call just ScrollView() -> this needs an argument or a content like e.g. so:
struct ContentView: View {

    var body: some View {
        ScrollView { // ERROR HERE: 'Argument passed to call that takes no arguments'
            HStack {
                ForEach(0..<3) {
                    item in
                    ScrollView {
                        Text("a")
                    }
                }
            }
            Spacer()
        }
    }
}


text:
Q: WPF how to get maximize/minimize button icon - Custom title bar I'm trying to create a custom title bar for my application. I have no idea how to add a the windows maximize or minimize icon to the button. I want my icons o look similar to this

Here is my XAML for my buttons
            <Button Command="{x:Static SystemCommands.MaximizeWindowCommand}" Content="+" Canvas.Left="1020" Height="30" Width="30">
            <Button.Style>
                <Style TargetType="{x:Type Button}">
                    <Setter Property="Background" Value="Black"/>
                    <Setter Property="TextBlock.Foreground" Value="White"/>
                    <Setter Property="Template">
                        <Setter.Value>
                            <ControlTemplate TargetType="{x:Type Button}">
                                <Border Background="{TemplateBinding Background}">
                                    <ContentPresenter HorizontalAlignment="Center" VerticalAlignment="Center"/>
                                </Border>
                            </ControlTemplate>
                        </Setter.Value>
                    </Setter>
                    <Style.Triggers>
                        <Trigger Property="IsMouseOver" Value="True">
                            <Setter Property="Background" Value="#403c47"/>
                        </Trigger>
                    </Style.Triggers>
                </Style>
            </Button.Style>
        </Button>
        <Button Command="{x:Static SystemCommands.MinimizeWindowCommand}" Content="" Canvas.Left="990" Height="30" Width="30" >
            <Button.Style>
                <Style TargetType="{x:Type Button}">
                    <Setter Property="Background" Value="Black"/>
                    <Setter Property="TextBlock.Foreground" Value="White"/>
                    <Setter Property="FontSize" Value="24"/>
                    <Setter Property="TextBlock.LineHeight" Value="5"/>
                    <Setter Property="Template">
                        <Setter.Value>
                            <ControlTemplate TargetType="{x:Type Button}">
                                <Border Background="{TemplateBinding Background}">
                                    <ContentPresenter HorizontalAlignment="Center" VerticalAlignment="Center"/>
                                </Border>
                            </ControlTemplate>
                        </Setter.Value>
                    </Setter>
                    <Style.Triggers>
                        <Trigger Property="IsMouseOver" Value="True">
                            <Setter Property="Background" Value="#403c47"/>
                        </Trigger>
                    </Style.Triggers>
                </Style>
            </Button.Style>
        </Button>

Any assistance is appreciated :)

A: This an extract of code i have used. (in my case is a reusable Window class extension, too long to post entirely)
XAML 2 button minimize and maximize
<Grid Margin="1,0,1,0">
    <Button x:Name="Restore" Command="{Binding Source={x:Static SystemCommands.RestoreWindowCommand}}"  Visibility="Collapsed" Style="{StaticResource WindowButtonStyle}">
        <Grid Width="30" Height="25" UseLayoutRounding="True" RenderTransform="1,0,0,1,.5,.5">
            <Path Data="M2,0 L8,0 L8,6 M0,3 L6,3 M0,2 L6,2 L6,8 L0,8 Z" Width="8" Height="8" VerticalAlignment="Center" HorizontalAlignment="Center"
                Stroke="{Binding Foreground, RelativeSource={RelativeSource AncestorType={x:Type Button}, Mode=FindAncestor}}" StrokeThickness="1"  />
        </Grid>
    </Button>
    <Button x:Name="Maximize" Command="{Binding Source={x:Static SystemCommands.MaximizeWindowCommand}}"  Style="{StaticResource WindowButtonStyle}">
        <Grid Width="31" Height="25">
            <Path Data="M0,1 L9,1 L9,8 L0,8 Z" Width="9" Height="8" VerticalAlignment="Center" HorizontalAlignment="Center"
                Stroke="{Binding Foreground, RelativeSource={RelativeSource AncestorType={x:Type Button}, Mode=FindAncestor}}" StrokeThickness="2"  />
        </Grid>
    </Button>
</Grid>

Trigger to hide minimize/maximize button when window is maximized/minimized
<ControlTemplate.Triggers>
    <Trigger Property="WindowState" Value="Maximized">
        <Setter TargetName="Maximize" Property="Visibility" Value="Collapsed" />
        <Setter TargetName="Restore" Property="Visibility" Value="Visible" />
    </Trigger>
    <Trigger Property="WindowState" Value="Normal">
        <Setter TargetName="Maximize" Property="Visibility" Value="Visible" />
        <Setter TargetName="Restore" Property="Visibility" Value="Collapsed" />
    </Trigger>
    .....
</ControlTemplate.Triggers>

Hope can adapt to your needs.

A: An alternative solution is to use the Webdings font, which has minimise, maximise and restore glyphs on 0, 1 and 2 respectively.
There are also unicode characters for these e.g.    but they are relatively recent and don't currently seem to work correctly in all locales.


text:
Q: inject bean with real parameters with mockito I'm trying to write a unit test case with mockito and I want to inject a bean with real parameters not mocked ones.
That bean has some string values that read from a .properties file.
@Component
public class SomeParameters {

    @Value("${use.queue}")
    private String useQueue;

 }

@RunWith(MockitoJUnitRunner.class)
public class ServiceTest {

    @Mock
    private A a;

    @Autowired
    private SomeParameters someParameters;

    @Before
    public void init() {
        MockitoAnnotations.initMocks(this);

    }

    @Test
    public void testMethod() {
        if(someParameters.getUseQueue==true){
            //do something
        }else{
            /bla bla
        }
    }

my main objective is to run a test case with real scenarios. I don't want to use mock values.
I was able to inject bean with real parameters in this way. But this is the unit test case, not an integration test. So I should not give applicationContext. Can you guide me how can handle this situation?
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = {"classpath:applicationContextTest.xml"})
public class ServiceTest {

A: If you want to use a spring-context then you should create a configuration (via xml or java config) for your test and declare only the beans that you require. For Example
For setting properties just declare @TestPropertiesSource("use.queue=someValue") otherwise you need to read value from test resources.
PS. also check @MockBean and @SpyBean especially @SpyBean

A: If you want to use real properties, then load the property file using Properties object and mock the value by getting from Properties object.


text:
Q: No contexto Web o que é um proxy? Como se trabalha com essa tecnologia e qual seu uso no dia dia de uma aplicação web seja no caso do cliente ou do servidor ?
Casos de uso podem ser em qualquer linguagem, apenas para compreensão de seu funcionamento.

A: Um proxy é um "intermediário" entre um cliente e um servidor.
Um caso de uso típico para proxy é o balanceamento de servidores. Vamos supor que um site tenha 10 servidores. No entanto, o site recebe os pedidos apenas por um proxy, que redireciona cada pedido recebido para um dos 10 servidores, de maneira que a carga de trabalho seja dividida igualmente entre os 10 servidores.
Um outro caso de uso é o proxy para cache. Neste caso, pedidos repetitivos e páginas estáticas como imagens, scripts, etc ficam na memória do proxy, e não em disco, para melhorar a performance de resposta. De maneira geral, apenas as páginas dinâmicas seriam repassadas para os servidores de backend.


text:
Q: Using logstash Elasticsearch output plugin error: NameError: SSLConnectionSocketFactory not found I am trying to import data from MySQL to Elasticsearch using logstash version.
Versions of software used:

*

*Java/JRE 1.8

*Elasticsearch 6.1.0

*Logstash 6.1.0

My conf contents are as follows:
file: simple-out.conf
input {
    jdbc {
        # MySQL jdbc connection string to our database, mydb
        jdbc_connection_string => "jdbc:mysql://valid/validDBNAME?useSSL=false"
        # The user we wish to execute our statement as
        jdbc_user => "MY USER"
        jdbc_password => "MY PWD"
        # The path to our downloaded jdbc driver
        jdbc_driver_library => "C:\JavaDevelopment\TomcatServer\apache-tomcat-8.5.20\lib\mysql-connector-java-5.1.45-bin.jar"
        # The name of the driver class for Postgresql
        jdbc_driver_class => "com.mysql.jdbc.Driver"
        # our query
        statement => "SELECT * from testtable"
        jdbc_paging_enabled => "true"
        jdbc_page_size => "50000"
    }
}
output {
    stdout { codec => json_lines }
    elasticsearch {
        hosts => "http://localhost:9200"
        index => "test-migrate"
        document_type => "data"
    }
}

When I run logstash I get the following error:
[2017-12-19T16:50:08,055][ERROR][logstash.pipeline        ] Pipeline aborted due to error {:pipeline_id=>"main", :exception=>#<NameError: SSLConnectionSocketFactory not found ERROR

Please suggest how to get past this.
Thanks

A: Try adding httpclient-VERSION.jar, httpcore-VERSION.jar files to LOGSTASH_HOME/vendor/jruby/lib/ folder.

A: I had same problem, the solution is:
add LOGSTASH_HOME variable path in environment variables in mycomputer properities to C:\some_path\logstash-6.3.0
then add these files to C:\some_path\logstash-6.3.0\logstash-core\lib\jars
files:
httpclient-4.5.2.jar
log4j-1.2.17.jar
httpcore-VERSION.jar
this is because logstash doesn't come with ssl jar file and you need to add this to jar folder and set the environment so as logstash can read those jar files
and try using gitbash rather than cmd or powershell!
and try to close and restart your logstash and elasticsearch
follow this link to see which index are comming to elasticsearch.
http://localhost:9200/_cat/indices?v
if you are running on diff. port please change port number
addidional tips
and it didn't work for me on jdk 10.x so use jdk 8.x
and maybe installer wont work even so just unzip file and run elasticsearch.bat and logstash -f cong_filepath\configfile.config in bin folders
 windows user can type cmd in top of path
Please make sure MySQL is running, (doesn't mean open) on server

Learn @ https://www.elastic.co/blog/logstash-jdbc-input-plugin

To resolve it yourself in future:
open logstash/bin folder and right click and gitbash (need git)
 type "vi log" and press tab 3 times till all logstahsh files are shown up
a new line will appear, type "vi logstash" and press enter to open source file
you'll have code to understand flow,.. if you look carefully Logstash_home and javacmd (at bottom) are important that execute jar, javacmd should be set to your java_home variable in env variables to jdk8.x and Logstash_home has a path for jar directory, either change it or put you jar to this folder.
Hope this helps!


text:
Q: How to avoid having (or delete) PDB files in TFS 2012 build result When using DefaultTemplate from Visual Sturdio 2012 (and TFS 2012 server), the PDB files are included in build directory. I do not want them.
Is there a way not to generate those files during build process?
Or
How can I delete those files?
I found this thread about deletion but seems a bit strange (no delete activity?)
There also is this answer but does not involve XAML template.
Thanks in advance for your help.

A: PDB files hold debug information on your code and its not advised to disable them, they are valid output hence deployment shouldn't be messing with them.
You can disable their generation in Visual Studio project Properties> Build > Advanced > Debug Info = none.
If you absolutely want them gone then disable them for build specific configuration (relaese etc.)

A: The build server by default does whatever the Solution (sln) tells it to. That by default is to do a "Debug" build and that created the PDB's. You can tell the Build to do a "Release" build that will not by default create any PDB's...

Figure: Adding a Build Configuration
I would however recommend against it as the PDB's contain information that you need even in production systems. Consider for a moment that you have a DLL in production and the customer is encountering a problem. You get them to create an InteliTrace log so that you can debug it locally (or they let you debug on their environment) and suddenly you are trying to debug without Visual Studio understanding the relationship between the Executable and the Source Code. So no debug...

A: Since I was unable to find building option to disable PDB file generation, I delete them afterwards.
There is no easy way to delete files. I did:

*

*use a FindMatchingFiles Activity with wildcard *.pdb, which returns
a full path to pdb files

*use a Foreach loop

*call a DotNet method in the loop for each file with the InvokeMethod Activity,
with    target type System.IO.File and method being "Delete"

A: In the previous version (Visual Studio 2010)
When we build /release, it was not generating PDBs, the PDB files are created when we only build with /debug:full or /debug:pdbonly, we use /debug:pdbonly if we want to generate PDBs for a release build that we do not want to be debuggable.
This is not the case in Visual Studio 2012, I checked it and I found it generated PDBs in both, /debug and /release
There is no documentation for Visuals Studio 2012.


text:
Q: Generate latitude and longitude on click in Google Maps Is there any tutorial on how can I get latitude and longitude whenever a user click a specific place in the maps? Thanks! I'm using Google Maps.

A: The following example will shows exactly how to generate lat and long on mouse events
Get lattitude and longitude onmouseover and onclick event in google map


text:
Q: Unable to debug in android studio (Error running app: java.lang.Error : no Connectors loaded. Check your JDK installation.) I am using Android studio 1.02 on Linux Mint. I was able to successfully debug my code on android emulators and my device LG G2 till yesterday. Today when I started my workstation I cant 'debug' my code.
It says:

Error running navigationbar: java.lang.Error : no Connectors loaded.
  Check your JDK installation.

On my device I can see the message:

Waiting for the Debugger
Application NavigationBar (com.example.test.navigationbar) is
  waiting for the debugger to attach.

and following are the console messages

Waiting for device. Target device: lge-lg_My_DEVICE'sID
  Uploading file    local path:
  /path-to-apk/apk/navigationbar-debug.apk
    remote path: /data/local/tmp/com.example.test.navigationbar
  Installing com.example.test.navigationbar DEVICE SHELL COMMAND: pm
  install -r "/data/local/tmp/com.example.test.navigationbar" pkg:
  /data/local/tmp/com.example.test.navigationbar Success
Launching application:
  com.example.test.navigationbar/com.example.test.navigationbar.NavigationBar.
  DEVICE SHELL COMMAND: am start -D -n
  "com.example.test.navigationbar/com.example.test.navigationbar.NavigationBar"
  -a android.intent.action.MAIN -c android.intent.category.LAUNCHER Starting: Intent { act=android.intent.action.MAIN
  cat=[android.intent.category.LAUNCHER]
  cmp=com.example.test.navigationbar/.NavigationBar }
Waiting for process: com.example.test.navigationbar Can't start
  debugging.

As advices on some older posts. I have already tried :

*

*android:debuggable="true"

*Restarting android studio and my PC

*Uncheck and then select again  'Enable ADB integration'

*Try to debug on emulator(gives the same problem)

*Make a new program from the android-studio's templates and try to debug it

On the other hand if I 'run' my application. It gives no such error.
Finally, if I run android.sh form my terminal then I get this message after I choose my device:

java.util.ServiceConfigurationError: com.sun.jdi.connect.Connector:
  Provider com.sun.tools.jdi.SunCommandLineLauncher could not be
  instantiated java.util.ServiceConfigurationError:
  com.sun.jdi.connect.Connector: Provider
  com.sun.tools.jdi.RawCommandLineLauncher could not be instantiated
  java.util.ServiceConfigurationError: com.sun.jdi.connect.Connector:
  Provider com.sun.tools.jdi.SocketAttachingConnector could not be
  instantiated java.util.ServiceConfigurationError:
  com.sun.jdi.connect.Connector: Provider
  com.sun.tools.jdi.SocketListeningConnector could not be instantiated

Kindly advice steps to resolve this issue.
Thanks
Some links I already tried:

*

*Not Able To Debug App In Android Studio

A: Finally I uninstalled my JDK8 and installed JDK7 this time.
Then if I open Android-Studio. It gave the errors that 'jdk8 not found'.
Upon this I typed :

rm -R -f ~/.AndroidStudio/

To delete all the settings related to Android-Studio.
Now when you run Android studio it will ask you to install/initialize it again.
That worked for me!!
Note: Till now I was working comfortably with JDK8. Only today due to some change I got the error.


text:
Q: How to send multicast report on virtual interface? I want to send multicast report, and the source address is the virtual interface address, how to do that? thank you.
for example:
Interface information:
eth0      Link encap:Ethernet  HWaddr 00:0C:35:00:11:22
          inet addr:192.168.126.100  Bcast:192.168.126.255  Mask:255.255.255.0
eth0:111  Link encap:Ethernet  HWaddr 00:0C:35:00:11:22
          inet addr:192.168.200.52  Bcast:192.168.200.255  Mask:255.255.255.0
I want to send multicast report and the source address is 192.168.200.52, how to do that?
My code:
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <net/if.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

struct sockaddr_in localSock;
struct ip_mreq group;
int sd;
int datalen;
char databuf[1024];

int main(int argc, char *argv[])
{
    /* Create a datagram socket on which to receive. */
    sd = socket(AF_INET, SOCK_DGRAM, 0);
    if(sd < 0)
    {
        perror("Opening datagram socket error");
        exit(1);
    }
    else
    {
        printf("Opening datagram socket....OK.\n");
    }

    /* Bind to the proper port number with the IP address */
    /* specified as INADDR_ANY. */
    memset((char *) &localSock, 0, sizeof(localSock));
    localSock.sin_family = AF_INET;
    localSock.sin_port = htons(4321);
    localSock.sin_addr.s_addr = inet_addr("192.168.200.52");;
    if(bind(sd, (struct sockaddr*)&localSock, sizeof(localSock)))
    {
        perror("Binding datagram socket error");
        close(sd);
        exit(1);
    }
    else
    {
        printf("Binding datagram socket...OK.\n");
    }

    /* Join the multicast group 226.1.1.1 on the local 203.106.93.94 */
    /* interface. Note that this IP_ADD_MEMBERSHIP option must be */
    /* called for each local interface over which the multicast */
    /* datagrams are to be received. */
    group.imr_multiaddr.s_addr = inet_addr("226.1.1.1");
    group.imr_interface.s_addr = inet_addr("192.168.200.52");
    if(setsockopt(sd, IPPROTO_IP, IP_ADD_MEMBERSHIP, (char *)&group, sizeof(group)) < 0)
    {
        perror("Adding multicast group error");
        close(sd);
        exit(1);
    }
    else
    {
        printf("Adding multicast group...OK.\n");
    }

    /* Read from the socket. */
    datalen = sizeof(databuf);
    if(read(sd, databuf, datalen) < 0)
    {
        perror("Reading datagram message error");
        close(sd);
        exit(1);
    }
    else
    {
        printf("Reading datagram message...OK.\n");
        printf("The message from multicast server is: \"%s\"\n", databuf);
    }
    return 0;
}


text:
Q: Converting JSON to HTML in an angular.js app I have an app which is supposed to display book like data (although will also have some interactive content such as quizzes). I am storing the pages as xml, as something like
<page>
  <image>http://someimage</image>
  <text>bla bla bla </text>
  <text>hello there </text>
  <image></image>
  <quiz type="multichoice">
    <question>What is the first letter of the alphabet</question>
    <answer>a</answer>
    <answer>b</answer>
    <answer>c</answer>
  </quiz>
</page>

And there is no restriction on the order or amount of elements on a given page. On my web server, I am converting these to a javascript object (and caching it). All is good until this point.
But what I want is for the client to then be able to request a page, and have logic to convert the javascript object into HTML. What I cannot figure out is how to write this logic with angular.js. I cannot see an obvious way of doing it - ng-repeat would only work if I wanted the same HTML for every element. But in this case I would want to display an image as an image, text as a paragraph, and quiz as something more complex. With jade templating, this would be trivial.
I want to have something working quickly, and am concerned that the learning curve of angular is going to be a time waster. Doing this with jade templating would be trivial, but of course has the downside of being server side.
Some clarification: I know how to get the data to the client, that just requires using $http. But what I don't understand at all is how to actually do what I want with the data once it is actually at the client. Whether it is JSON or XML is irrelevant. I just need to know how to write code that will dynamically add html elements to the view, based on what is in the data.

A: You need something "working quickly" when you already are familiar with a technology for which achieving results will be "trivial".  You've answered your own question - go with what you know.
Angular is just a tool, it takes time to learn and upon doing so you can accomplish things.  It can solve your problem, but you'll need to learn it first.  Even if you get some good answers as to how this particular problem might be solved with Angular, you will still need to understand how to develop and deploy an angular application, which will not be as trivial as using what you already know.

A: Get the XML data to the client using http. Parse the xml.
angular.module('app').controller('TestController', function($scope, $http){
//use $http here
$http.get('https://stackoverflow.com').then(function(successResponse){
   $scope.data = successResponse;
}, function(errorRepsonse){
   $scope.error = errorRepsonse;
});

});


text:
Q: Mysql in node.js (Java Script) Cannot enqueue Query after invoking quit Regards
I'm trying with nodejs to make a loop to execute some queries and depending on if a record exists or not do one action or another (update or delete).
This is the function I have inside my class:
CODE NUMBER 1
class BBDDP extends BBDD {
    insertOrUpdate = async (profile) => {
        let bdc = await this.connect();
        await new Promise(async (resolve, reject) => {
            await profile.tweets.forEach(async tweet => {
                await new Promise(async (resolve, reject) => {
                    bdc.query(
                        ("SELECT x FROM table_x WHERE id = ?"), [profile.id],
                        function (err, row) {
                            if (err) {
                                throw err;
                            } else {
                                if (row && row.length) {
                                    //bdc.connect()
                                    bdc.query("DELETE * FROM table_x where id = ?";[profile.id])
                                    console.log('Case row was found!');
                                } else {
                                    bdc.query("INSERT INTO table_x set name = ?, addres = ? where id = ?;",[profile.name, profile.addres, profile.id])
                                    console.log('No case row was found :( !');
                                }
                            }
                        }
                    );
                    resolve();
                })
                resolve();
            });
        });
        bdc.end()
    }
}

My BBDDC class inherits from another class called BBDD which basically has only 3 basic methods that can be used to run.
CODE NUMBER 2
Class BBDD:
class BBDD {
    /**
     * Clase helper que se usa para poder hacer query contra la bbdd.
     * @param {*} ip Direccion ip del servidor
     * @param {*} user Usuario para la autenticación
     * @param {*} password La contraseña para la bbdd
     * @param {*} dataBase Nombre de la base de datos
     * @param {*} port El puerto
     */

    constructor(ip, user, password, dataBase, port = 3306) {
        this.ip = ip;
        this.user = user;
        this.password = password;
        this.dataBase = dataBase;
        this.port = port;
        this.data = null;
        console.log(`Info de conexion con la bbdd ip ${this.ip} en el puerto ${this.port}, a la bbdd ${this.dataBase}.`);
    }

    connect = async () => {
        let con = await new Promise(async (resolve) => {
            this.con = mysql.createConnection({
                host: this.ip,
                user: this.user,
                password: this.password,
                database: this.dataBase,
                port: this.port,
                charset: "utf8"
            });

            this.con.connect(function (err) {
                if (err) throw err;
                console.log("Connected!");
            });
            resolve(this.con);
            return this.con;
        });
        return con;
    }

    query = async (query, values = null) => {
        /**
         * @param {*} query Query, es la consulta que se desea ejecutar.
         * @returns La respuesta de mysql
         */
        await this.connect();
        return await new Promise(async resolve => {
            if (values != null) {
                let x = this.con.query(query, values, function (error, results, fields) {
                    if (error) throw error;
                    resolve(results);
                })
                await this.closeConnection();
            } else {

                let x = this.con.query(query, function (error, results, fields) {
                    if (error) throw error;
                    resolve(results);
                })
                await this.closeConnection();
            }
        });
    }

    closeConnection = async () => {
        return await new Promise(async (resolve) => {
            this.con.end();
            console.log("Conexion cerrada.")
            resolve();
        })
    }
}

What I am trying to do is, in the same loop inside the callback of the mysql query function what I want to do is the query to know if it exists or not and depending on that inside the same callback execute one query or another, but I don't know why before executing the queries inside the callback the connection is closed and I get the following failure:
Error: Cannot enqueue Query after invoking quit.
This failure occurs when I call the function called closeConnection at the end of the loop that executes in the insertOrUpdate function.
The execution is from my main class:
class Main {
    constructor() {
    }

    static async run() {
        this.api = MyApi('xxx', "xxx","xxx");
        this.bdCargas = new BBDDQ("xxx", "xxx", "xxx", "xxx");
        this.bd = new BBDDP("xxx", "xxx", "xxx", "xxx");
        let profiles = await this.bdCargas.getQueue();

        profiles.forEach(async profile => {
            await this.api.setFollowers(profile);
            await this.api.setUserContents(profile);
            await this.bd.insertOrUpdate(profile);
        })
    }
}

I have tried, in making the functions asynchronous, changing classes from static to non-static. Also to run with different structure, etc... Nothing works for me.
I want something like this:

insertOrUpdate = async (profile) => {
  await this.conect();
  profile.tweets.forEach(async tweet => {
                await new Promise(async (resolve, reject) => {
                    bdc.query(
                        ("SELECT x FROM table_x WHERE id = ?"), [profile.id],
                        function (err, row) {
                            if (err) {
                                throw err;
                            } else {
                                if (row && row.length) {
                                    //bdc.connect()
                                    bdc.query("DELETE * FROM table_x where id = ?";[profile.id])
                                    console.log('Case row was found!');
                                } else {
                                    bdc.query("INSERT INTO table_x set name = ?, addres = ? where id = ?;",[profile.name, profile.addres, profile.id])
                                    console.log('No case row was found :( !');
                                }
                            }
                        }
                    );
                    resolve();
                })
                resolve();
            });
this.closeConnection();
}

To be able to execute a loop and to be able to do the necessary actions.

A: I found the error.
My failure is due to the forEach I use, as it doesn't wait for promises, the solution was to change it to the modern js forEach.
insertOrUpdate = async (profile) => {
  await this.conect();
  for(let tweet of profile.tweets){
                await new Promise(async (resolve, reject) => {
                    bdc.query(
                        ("SELECT x FROM table_x WHERE id = ?"), [profile.id],
                        function (err, row) {
                            if (err) {
                                throw err;
                            } else {
                                if (row && row.length) {
                                    //bdc.connect()
                                    bdc.query("DELETE * FROM table_x where id = ?";[profile.id])
                                    console.log('Case row was found!');
                                } else {
                                    bdc.query("INSERT INTO table_x set name = ?, addres = ? where id = ?;",[profile.name, profile.addres, profile.id])
                                    console.log('No case row was found :( !');
                                }
                            }
                        }
                    );
                    resolve();
                })
                resolve();
        }
  this.closeConnection();
}


text:
Q: Is it possible to delete or invalidate gecko / firefox session without closing browser? Is it possible, using the gecko / firefox XPCOM interfaces, to delete or invalidate a user's active session without closing the browser? I am using Gecko embedded (specifically GeckoFX) in an application where it is possible that multiple users might use the browser component across the lifetime of the application.
The application packages web browsing with various other functionality, and when the web browser is 'closed', the app remains open. It seems that as far as the gecko engine is concerned, as the process hasn't closed, the active session is still active. If a user is to log into Gmail or Facebook, for instance, and then close the browser, upon reopening the browser and navigating back to one of those pages, that user is determined to still be logged in. As multiple users can use the application without the application actually exiting, this raises privacy issues.
I have tried calling NS_InitXPCOM2 and NS_ShutdownXPCOM within the constructor / dispose method of the browser control, however NS_InitXPCOM2 cannot be called after NS_ShutdownXPCOM within the lifetime of the process, so this simply crashes.
I have also used the PurgeHistory method of nsISHistory and the evictEntries method of nsICacheService - none of these appear to have an immediate effect within the life of the process.
Does anyone know of any XPCOM interfaces that can achieve this? Alternatively, any pointers in direction of similar functionality, be it through XPCOM interfaces or Firefox extensions would be greatly appreciated (are there any extensions that allow you to clear your current browsing session without reopening the browser? or that provide you a different session between each Firefox window / tab?)
The program is written in C#, however answers in any language are appreciated.
Many thanks

A: I finally found the interface that seems to allow this: nsICookieManager removeAll()
Relevant C# interfaces / code for those using GeckoFX:
[Guid("AAAB6710-0F2C-11d5-A53B-0010A401EB10"),
ComImport,
InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
interface nsICookieManager
{
    void removeAll();
    void remove(string aDomain, string aName, string aPath, bool aBlocked);
}

and Xpcom.GetService<nsICookieManager>("@mozilla.org/cookiemanager;1").removeAll(); in appropriate location.


text:
Q: Storing socket.io data I'm developing an app using socket.io where users send and receive data to users who are present in there channels/rooms. Here, I need your suggestion for storing data that is passed from user to a channel. So when some one enters that channel he should be able to get the data from that particular channel he entered.
So how will I save the data to the particular channel?
I had planned for storing data in MySQL database, which will have channel id, channel name, and channel message columns.
But I think it will be a problem if number of users increases and inserting each message as a new row into database?
Please help me the best way for these query.

A: Until you have thousands of simultaneous users, it hardly matters.  Just use whatever you are most comfortable with. When you get thousands of users you can change the architecture, if necessary.


text:
Q: Measurability of a set constructed from another measurable set Let $E$ be a measurable subset of the real numbers. I define $\sigma(E) = \{ (x,y) \in \mathbb{R}^2 | x-y \in E\}$. I would like to prove that this set $\sigma(E)$ is Lebesgue measurable in $\mathbb{R^2}$, but when I write down the equation $\mu(\sigma(E) \cap A) + \mu(\sigma(E) \cap A^c) = \mu(\sigma(E))$ for arbitrary $A$,I get stuck. I would like help on how to tackle this situation of measurability in a different space.
A similar question of this kind was that if $f,g$ are measurable functions then so is $h(x,y)=f(x-y)g(y)$ in a higher dimensional space. I had trouble writing down $h(x,y)>\alpha$ in this case, where $\alpha \in \mathbb{R}$,and decomposing it in terms of $f$ and $g$.

A: Hint for the first question: Let $f(x,y) = x-y.$ Then $f$ is continuous. If $E\subset \mathbb R$ were a Borel set, then $f^{-1}(E)$ would be a Borel set. So you'll be done if you can show that if $F\subset \mathbb R$ has one-dimensional Lebesgue measure $0,$ then $f^{-1}(F)$ has two-dimensional Lebesgue measure $0.$


text:
Q: How to do inter-process locking with forked Ruby processes? Objective
Increment a counter using Ruby's fork method and several workers
Disclaimers

*

*I do not want to use any external dependencies for this

*Usage of Ruby's Thread class is not allowed

*I want to see if this is possible using fork

Here's a little shared memory mock
class Memory
  def self.address= value
    @value = value
  end

  def self.address
    @value
  end
end

Here's my worker
class Worker
  def initialize mutex
    @mutex = mutex
  end

  def work
    @mutex.synchronize do
      print "begin: %d " % (tmp=Memory.address)
      sleep 0.05
      print "end: %d \n" % (Memory.address = tmp + 1)
    end
  end
end

Let's run it
# init
Memory.address = 0
mutex = Mutex.new

# create workers
workers = []
10.times do
  workers << fork do
    Worker.new(mutex).work
  end
end

# wait for workers to finish
Process.waitall

Output
begin: 0 begin: 0 begin: 0 begin: 0 begin: 0 begin: 0 begin: 0 begin: 0 begin: 0 begin: 0 end: 1
end: 1
end: 1
end: 1
end: 1
end: 1
end: 1
end: 1
end: 1
end: 1

Expected Output
begin: 0 end: 1
begin: 1 end: 2
begin: 2 end: 3
begin: 3 end: 4
begin: 4 end: 5
begin: 5 end: 6
begin: 6 end: 7
begin: 7 end: 8
begin: 8 end: 9
begin: 9 end: 10

Side Questions:

*

*Am I supposed to be using a single Mutex?

*Does it matter if each worker creates its own Mutex?

A: Forked processes inherit their parent's resources but the memory is a copy (or copy on write): the changes made in one process have no effect on the other ones.
Similarly each process has its own copy of the mutex, so the calls to synchronise don't achieve anything.
If you need to communicate with your child processes, one way is to use a pipe (see the docs for IO). Each process inherits a copy of the pipe and writes from one process show up in the other process.
child_in, parent_out = IO.pipe
parent_in, child_out = IO.pipe

Process.fork do
  parent_out.close
  parent_in.close
  #data written to child_out appears on parent_in in the parent process
  #reading from child_in returns data the parent has written to parent_out
end
child_out.close
child_in.close

#write data to parent_out here to have it appear on child_in in the child
#reading from parent_in to get data the child has written to child_out

As far as I know there are no cross process concurrency primitives built into ruby.

A: The File class has flock which lets you lock a file. It's one method to do inter-process locking.
There is even a gem called remote_lock if you want to store it remotely.


text:
Q: How to connect json file with c# I have Json file connected with database: http://222.255.29.210:9000/pk/api/index.php/fbids

In code boder red: If I set "des = true" in database then tool run, if I set "des = false" then Winform c# close. Use Json data

A: I guess that your data on JSON come from database right ?
So, use Json.net to determine your program in c#
to read that json object and check is "des = true" or not.


text: Q: I want to create hive external table for Unix file directory I want to create hive external table for Unix file directory, not for HDFS. Mean I want to give external path of a Unix directory so that my hive external table could point a unix file. Is it possible in hive?.


text:
Q: can not retrieve json object value postgresql 9.6 DO
$$
DECLARE
array_ json;
category_name text;
category_ json:='{"Maincategory":"Vehicle","Categoryname":"Car"}'::json;
BEGIN
category_name:=(SELECT category_  ->'Maincategory'::text) ;
array_:=(SELECT elements -> category_name FROM webuser.footable WHERE id=somenumber)::json;
raise notice '%',array_ ;
END
$$;

                             elements
                              (json)
|-------------------------------------------------------------------------------------|
|{"Vehicle": [{"Car": 3}, {"Truck": 1}], "Office": [{"Printer": 3}, {"Desk": 8}]}     |

I have elements column and i want to retrieve vehicle array which is ([{"Car": 3}, {"Truck": 1}] ) that will be stored in array_ variable. I get array_ always null. What is wrong with this code?

A: category_  ->'Maincategory'::text will return "Vehicle", while you need the value of the filed...
change (SELECT category_  ->'Maincategory'::text)
to
(SELECT category_  ->>'Maincategory'::text), like here:
b=# DO
b-# $$
b$# DECLARE
b$# array_ json;
b$# category_name text;
b$# category_ json:='{"Maincategory":"Vehicle","Categoryname":"Car"}'::json;
b$# elements  json:= '{"Vehicle": [{"Car": 3}, {"Truck": 1}], "Office": [{"Printer": 3}, {"Desk": 8}]}';
b$# BEGIN
b$# category_name:=(SELECT category_ ->>'Maincategory'::text) ;
b$# raise info '%',(select elements->category_name);
b$# --array_:=(SELECT elements -> category_name FROM webuser.footable WHERE id=somenumber)::json;
b$# --raise notice '%',array_ ;
b$# END
b$# $$;
INFO:  [{"Car": 3}, {"Truck": 1}]
DO


text:
Q: Contracting a tensor with a selection rule Imagine that you have a tensor $T_{ijkl}$ (0<=i,j,k,l< N) that has the following property
T_{ijkl} is nonzero if i+j=k+l
which acts as a "selection rule".
You want to contract the tensor T with another tensor u to make a third tensor v as follows
$$v_{ij} = sum_{kl=0}^N T_{ijkl} u_{kl}$$
is there a way to do this construction such that:
a. Uses the tensor contraction machinery of numpy and/or tensorflow? Things like einsum and the like.
b. Uses the explicit symmetry of the tensor, i.e the above operation should require $O(N^3)$ operations, not $O(N^4)$.
One could use einsum directly getting $O(N^4)$ operations:
v = np.einsum('ijkl,ij->kl',T,u)

Or one could do a custom triple loop as
v = np.zeros_like(u)
for i in range(N):
    for j in range(N):
        for k in range(max(1+i+j-N,0),min(i+j,N-1)+1):
            v[i,j]+=T[i,j,k,i+j-k]*u[k,i+j-k]

But neither of this satisfy both a. and b. above


text:
Q: PHP UTF-8 handling I am parsing a text file and am occassionally running into data such as:
CASTA¥EDA, JASON

Using a Mongo DB backend when I try saving information, I am getting errors like:
[MongoDB\Driver\Exception\UnexpectedValueException]
  Got invalid UTF-8 value serializing 'Jason Casta�eda'

After Googling a few places, I located two functions that the author says would work:
 function is_utf8( $str )
    {
        return preg_match( "/^(
         [\x09\x0A\x0D\x20-\x7E]            # ASCII
       | [\xC2-\xDF][\x80-\xBF]             # non-overlong 2-byte
       |  \xE0[\xA0-\xBF][\x80-\xBF]        # excluding overlongs
       | [\xE1-\xEC\xEE\xEF][\x80-\xBF]{2}  # straight 3-byte
       |  \xED[\x80-\x9F][\x80-\xBF]        # excluding surrogates
       |  \xF0[\x90-\xBF][\x80-\xBF]{2}     # planes 1-3
       | [\xF1-\xF3][\x80-\xBF]{3}          # planes 4-15
       |  \xF4[\x80-\x8F][\x80-\xBF]{2}     # plane 16
      )*$/x",
            $str
        );
    }

    public function force_utf8($str, $inputEnc='WINDOWS-1252')
    {
        if ( $this->is_utf8( $str ) ) // Nothing to do.
            return $str;

        if ( strtoupper( $inputEnc ) === 'ISO-8859-1' )
            return utf8_encode( $str );

        if ( function_exists( 'mb_convert_encoding' ) )
            return mb_convert_encoding( $str, 'UTF-8', $inputEnc );

        if ( function_exists( 'iconv' ) )
            return iconv( $inputEnc, 'UTF-8', $str );

        // You could also just return the original string.
        trigger_error(
            'Cannot convert string to UTF-8 in file '
            . __FILE__ . ', line ' . __LINE__ . '!',
            E_USER_ERROR
        );
    }

Using the two functions above I am trying to determine if a line of text has UTF-8 by calling is_utf8($text) and if it is not then I call the force_utf8($text) function. However I am getting the same error. Any pointers?

A: This question is pretty old, but for those who face same issue and get on this page like me:
mb_convert_encoding($value, 'UTF-8', 'UTF-8');

This code should replace all non UTF-8 characters by ? symbol and it will be safe for MongoDB insert/update operations.


text:
Q: How to query MongoDb for partial Id matches with Guid Id? I have an App written in C#, where the DB is MongoDB. the Id object is C# Guid, so the _id field in the DB looks like:

  "_id": {
    "$binary": {
      "base64": "tZqfm0KNMUi1GGfCkQQosw==",
      "subType": "03"
    }
  }

And the App is using regular Guid ("9b9f9ab5-8d42-4831-b518-67c2910428b3")
Now, I want to add the ability to search by partial id - if I search for "67c2910428b3", I want to find the object with corresponding id.
how to I add a filter \ query to do that ?
I cannot use BsonRegex, since the field in the db is not "converted" - it will never get Guid-id.
the "simple" solution is to add another field in MongoDB with the Guid as string so i can Search on it - but that seems redundant, since the id is already there.

A: From the bson spec, binary subtype 3 is the old UUID format.  One of the problems with the old format was that it permitted the client to specify the ordering of the bytes.
Decoding from the base-64 string, the value of that field is:
0xb59a9f9b428d3148b51867c2910428b3

Note that this UUID you mention, but is using a client ordering that does not conform to RFC-4122 section 4.1.2, which requires MSB ordering for each field.
A UUID is stored by MongoDB as a binary blob. There are no server-side functions to convert or slice the value into smaller chunks.
You can make comparisons of the entire value as described in Comparison/Sort Order
For example, you could find all values that start with 9b9f9ab5 by querying for
{$gte: Guid("9b9f9ab5-0000-0000-0000-000000000000"), $lt: Guid("9b9f9ab6-0000-0000-0000-000000000000")}

Querying a part in the middle, such as all UUID with a time-mid value of 0x8d42 like 00000000-8d42-0000-0000-000000000000, will not be possible with the value stored as binary.


text:
Q: Subspace proof wording not sure how to word my answer for this question:
Let V be a vector space and let H and K be two subspaces of V. Show that the following set W is a subspace of V:
W={u+v: u ∈ H, v ∈ K}
I'm pretty sure the answer is because H and K are two subspaces of V, meaning they are closed under addition. So when you add u and v together, they are also a subspace of V, but I'm not sure how to phrase this! Any help would be appreciated.

A: Suppose that $u\in W$ and $v\in W$.  We wish to prove that $\alpha u - v$ is also in $W$.
Since $u\in W$, we know by definition of $W$ that $u$ can be written as $u=h_1+k_1$ where $h_1\in H$ and $k_1\in K$
Similarly, $v\in W$ implies that $v$ can be written as $v=h_2+k_2$ with $h_2\in H$ and $k_2\in K$.
Then $\alpha u - v = \alpha (h_1+k_1)-h_2-k_2 = (\alpha h_1 - h_2) + (\alpha k_1 - k_2)$
Since $H$ is a subspace, $(\alpha h_1 - h_2)\in H$ and similarly since $K$ is a subpsace $(\alpha k_1 - k_2)\in K$
Thus $\alpha u - v$ can be written as the sum of vectors with the first vector from $H$ and the second from $K$ and is therefore an element of $W$, proving that it is indeed a subspace.

As an aside:  checking that $\alpha u - v \in W$ is equivalent to checking the following conditions simultaneously:

*

*$0\in W$

*$u\in W, v\in W\Rightarrow u+v\in W$

*$u\in W, \alpha\in \Bbb F\Rightarrow \alpha u \in W$

Also worth mentioning is that here, we made no assumptions about $H\cap K$.  In a future problem, you might use the additional assumption that $H\cap K=\{0\}$ in which case you will conclude that $\dim(W) = \dim(H)+\dim(K)$ and that there is a unique way to write $u=h+k$.

A: Check the necessary and sufficient conditions: is $W$ non-empty and is it closed under addition and scalar multiplication?
Take $w_1,w_2 \in W$, this means $w_1=u_1+v_1$ with $u_1 \in H$ and $v_1 \in K$ and $w_2=u_2+v_2$ with $u_2 \in H$ and $v_2 \in K$. Now look at $w_1+w_2$; is it of the required form to be in $W$?
Do the same for $w \in W$ (this means $w = \ldots$) and consider $\lambda w$.
You can also combine these two conditions by working with a more general linear combination $\lambda w_1 + \mu w_2$.


text:
Q: how to use different sender than credentials use in smtp configuration in asp.net Hi in my web application we are sending mail to the person whos birthday is in current week, so while sending mail i dont want sender as email id which is used in smtp configuration i want to use different email id as sender,
Can any one tell me how i can achieve this,

A:     /// <summary>
    /// Sends mail with authentification
    /// </summary>
    /// <param name="recipients"></param>
    /// <param name="from"></param>
    /// <param name="subject"></param>
    /// <param name="body"></param>
    /// <param name="isHTMLbody"></param>
    /// <param name="SMTPhost"></param>
    /// <param name="priority"></param>
    /// <param name="credentials"></param>
    /// <param name="port"></param>
    /// <param name="enableSsl"></param>
    public static void SendMailWithAuthentication(List<string> recipients, string from, string subject, string body, bool isHTMLbody,
        string SMTPhost, System.Net.Mail.MailPriority priority, System.Net.NetworkCredential credentials, int? port, bool enableSsl)
    {
        System.Net.Mail.MailMessage message = new System.Net.Mail.MailMessage();
        foreach (string recipient in recipients)
        {
            message.To.Add(recipient);
        }
        message.SubjectEncoding = Encoding.UTF8;
        message.BodyEncoding = Encoding.UTF8;
        message.Subject = subject;
        message.From = new System.Net.Mail.MailAddress(from);
        message.IsBodyHtml = isHTMLbody;
        message.Body = body;
        message.Priority = priority;
        System.Net.Mail.SmtpClient client = new System.Net.Mail.SmtpClient();
        client.Credentials = credentials;
        client.Host = SMTPhost;
        if (port != null)
        {
            client.Port = (int)port;
        }
        client.EnableSsl = enableSsl;
        client.Send(message);
        message.Dispose();
    }

For "from" parameter you can use what ever email as you want as while it's valid email address. Just a sample it could be "bill.gates2@microsoft.com" and it will work.
If this is not working you should contact your email provider, because they are preventing you from doing this.