text:
Q: How to change default ProgressDialog circle color in android I am using ProgressDialog for showing progressbar
            ProgressDialog progressDialog = new ProgressDialog(context);
            progressDialog.setCancelable(false);
            progressDialog.setMessage(message);
            progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
            progressDialog.show();

And it is coming like this

I want to change the green color of the circle to red. is there any way?
I tried
.getIndeterminateDrawable().setColorFilter(0xFFFFFFFF, android.graphics.PorterDuff.Mode.MULTIPLY);

But not working.

A: This is not a perfect solution, but may help.
Also check my previous comment.
https://stackoverflow.com/a/39687893/2598453
final ProgressDialog progress = new ProgressDialog(this);
progress.setMessage(getString(R.string.progress_message));
progress.setIndeterminate(true);
progress.setCancelable(false);

if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {
    Drawable drawable = new ProgressBar(this).getIndeterminateDrawable().mutate();
    drawable.setColorFilter(ContextCompat.getColor(this, R.color.colorAccent),
            PorterDuff.Mode.SRC_IN);
    progress.setIndeterminateDrawable(drawable);
}

progress.show();

A: In style.xml create style for dialog box :
<style name="AppCompatAlertDialogStyle" parent="Theme.AppCompat.Light.Dialog.Alert">
<item name="colorAccent">@color/black</item>
<item name="android:textColorPrimary">@color/white</item>
<item name="android:background">@color/grey_dialog_box</item>
</style>

In this  "android:textColorPrimary" need to define color you want to show and in java code define style of ProgressDialog like :
ProgressDialog progressDialog = new ProgressDialog(context,R.style.AppCompatAlertDialogStyle);

MORE : http://androidprogressdialogcustomcolor.blogspot.in/

A: Get the resource from the android resource that being used by the ProgressDialog.
final ProgressDialog progress = new ProgressDialog(context);
progress.setTitle("Loading");
progress.setMessage("Wait while loading...");
progress.setCancelable(false); // disable dismiss by tapping outside of the dialog
progress.show();
ProgressBar progressbar=(ProgressBar)progress.findViewById(android.R.id.progress);
progressbar.getIndeterminateDrawable().setColorFilter(Color.parseColor("#C60000"), android.graphics.PorterDuff.Mode.SRC_IN);

A: Try this:
Example where setting color to red:
ProgressBar spinner = new android.widget.ProgressBar(
                context,
                null,
                android.R.attr.progressBarStyle);

spinner.getIndeterminateDrawable().setColorFilter(0xFFFF0000, android.graphics.PorterDuff.Mode.MULTIPLY);

A: Add Style.xml
<style name="MyAlertDialogStyle" parent="Theme.AppCompat.Light.Dialog.Alert">
    <item name="colorAccent">@color/colorPrimary</item>
</style>

set style to progress dialog
pdialog = new ProgressDialog(context, R.style.MyAlertDialogStyle);

A: In your Application Theme, change colorAccent
<style name="AppTheme.Bash" parent="Theme.AppCompat.Light.DarkActionBar">
    <item name="colorPrimary">@color/colorPrimary</item>
    <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
    <item name="colorAccent">Add your color here</item>
    <item name="android:windowBackground">@color/gray</item>
</style>

use whatever color you want

A:
Create layout for progress dialog as named as custom_progress_dialog.xml in drawable folder.
<?xml version="1.0" encoding="utf-8"?>
<rotate xmlns:android="http://schemas.android.com/apk/res/android"
    android:pivotX="50%" android:pivotY="50%" android:fromDegrees="0"
    android:toDegrees="360">
    <shape android:shape="ring" android:innerRadiusRatio="3"
        android:thicknessRatio="8" android:useLevel="false">

        <size android:width="56dip" android:height="56dip" />

        <gradient android:type="sweep" android:useLevel="false"
            android:startColor="@android:color/transparent"
            android:endColor="#1e9dff"
            android:angle="0"
             />

    </shape>
</rotate>

make sure that indeterminate = true and android:indeterminateDrawable="@drawable/custom_progress_background"
 In the activity layout where you want to use the loader
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/loadingPanel"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:gravity="center">

    <ProgressBar
        android:layout_width="wrap_content"
        style="?android:attr/progressBarStyleLarge"
        android:layout_height="wrap_content"
        android:indeterminateDrawable="@drawable/custom_progress_dialog"
        android:indeterminate="true" />
</RelativeLayout>

A: The perfect and simple solution for custom color progress bar.

public class CustomProgressBar extends ProgressBar{
    public CustomProgressBar(Context context) {
        super(context);
        this.setIndeterminate(true);
        this.getIndeterminateDrawable().setColorFilter(getResources().getColor(R.color.app_blue), PorterDuff.Mode.MULTIPLY);
    }

    public CustomProgressBar(Context context, AttributeSet attrs) {
        super(context, attrs);
        this.getIndeterminateDrawable().setColorFilter(getResources().getColor(R.color.app_blue), PorterDuff.Mode.MULTIPLY);
    }

    public CustomProgressBar(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }
}

and use it in your layout.
<RelativeLayout
        android:id="@+id/loadingPanel"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:gravity="center"
        android:visibility="gone">

        <com.mayproject.views.CustomProgressBar
            android:layout_width="wrap_content"
            android:layout_height="wrap_content" />
    </RelativeLayout>

A: If you'd like to define the colour ad-hoc, without needing inheritance or dedicated XML, you can use something like this:
/** Styles a ProgressDialog to use a themed Spinner. */
public void setStyledProgressDialog(final Context pContext, final ProgressDialog pProgressDialog, final int pColorResourceId) {
    // Allocate a new ProgressBar.
    final ProgressBar lProgressBar = new android.widget.ProgressBar(pContext, null, android.R.attr.progressBarStyle);
    // Configure the IndeterminateDrawable.
    lProgressBar.getIndeterminateDrawable().setColorFilter(ContextCompat.getColor(pContext, pColorResourceId), android.graphics.PorterDuff.Mode.MULTIPLY);
    // Assign the ProgressBar to the ProgressDialog.
    pProgressDialog.setIndeterminateDrawable(lProgressBar.getIndeterminateDrawable());
}

A: If you already use material dialogs library (https://github.com/afollestad/material-dialogs#indeterminate-progress-dialogs) the simplest solution could be to use the progress dialog from that library. The circle will be automatically colored with the primary color:
MaterialDialog dialog = new MaterialDialog.Builder(context)
                    .content(R.string.loading)
                    .progress(true, 0)
                    .show();


text:
Q: hasOwnProperty method in javascript output true?
hasOwnProperty search for __proto__ ?

 function Person(){}
 Person.prototype.name = "Nicholas";
 Person.prototype.age = 29;
 Person.prototype.job = "Software Engineer";
 Person.prototype.sayName = function(){

 };
 var person1 = new Person();
 person1.hasOwnProperty("name") // false ?

the above example comes from Prefessional JavaScript for Web Developers

use chrome :
person1.hasOwnProperty("name") // is true

A: Yes, it should be true.
person1.name = "Greg"; gives person1 its own name property, so it doesn't come via the prototype chain.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Validity of the boolean expression grammar Is this grammar correct for parsing boolean expressions?
ident = true | false
bxpr  = ident and bxpr | ident or bxpr | not bxpr | ( bxpr ) | ident

This so far parsed most of my test cases [using scala parsers]. I see many grammars using terms and factors to create a grammar


text:
Q: Send Notification to specific user in spring boot websocket I want to send notification to specific client.
e.g username user
@Configuration
@EnableWebSocketMessageBroker
public class WebSocketConfiguration extends
    AbstractWebSocketMessageBrokerConfigurer {

        @Override
        public void registerStompEndpoints(StompEndpointRegistry stompEndpointRegistry) {
            stompEndpointRegistry.addEndpoint("/socket")
                    .setAllowedOrigins("*")
                    .withSockJS();
        }

        @Override
        public void configureMessageBroker(MessageBrokerRegistry registry) {
            registry.enableSimpleBroker("/topic", "/queue");
            registry.setApplicationDestinationPrefixes("/app");

        }

Controller
@GetMapping("/notify")
public String getNotification(Principal principal) {
    String username = "user";

    notifications.increment();
    logger.info("counter" + notifications.getCount() + "" + principal.getName());
    //  logger.info("usersend:"+sha.getUser().getName()) ; //user

    template.convertAndSendToUser(principal.getName(), "queue/notification", notifications);

    return "Notifications successfully sent to Angular !";
}

Client-Side
Angular Service
connect() {
    let socket = new SockJs(`api/socket`);

    let stompClient = Stomp.over(socket);

    return stompClient;
}

Angular Component
 let stompClient = this.webSocketService.connect();

     stompClient.connect({}, frame => {

      stompClient.subscribe('/user/queue/notification', notifications => {
               console.log('test'+notifications)
          this.notifications = JSON.parse(notifications.body).count;

      })     });

I am have searched many other questions and tried but none of them worked for me
e.g here answered by Thanh Nguyen Van and  here
Console
 Opening Web Socket...
    stomp.js:134 Web Socket Opened...
    stomp.js:134 >>> CONNECT
    accept-version:1.1,1.0
    heart-beat:10000,10000

    stomp.js:134 <<< CONNECTED
    version:1.1
    heart-beat:0,0

    stomp.js:134 connected to server undefined
    reminder.component.ts:18 test callsed
    stomp.js:134 >>> SUBSCRIBE
    id:sub-0
    destination:/user/queue/notification

thanks in advance .

A: Seems you are missing a slash in your destination:
template.convertAndSendToUser(principal.getName(), "/queue/notification", notifications);

A: The answer of gerrytan to Sending message to specific user on Spring Websocket mentions a web socket configuration change, to register the /user prefix. In your case I guess it means to replace
registry.enableSimpleBroker("/topic", "/queue");

with
registry.enableSimpleBroker("/topic", "/queue", "/user");

He also says that in controller you don't need the /user prefix because it is added automatically. So you could try this:
template.convertAndSendToUser(principal.getName(), "/queue/notification", notifications);

and this:
template.convertAndSendToUser(principal.getName(), "/user/queue/notification", notifications);

On the client side you need to provide the username that you used to connect to server.  You might insert it directly:
stompClient.subscribe('/user/naila/queue/notification', ...)

or get it from a header.  But Markus says at How to send websocket message to concrete user? that even here you don't need the username, so it might work like this:
stompClient.subscribe('/user/queue/notification', ...)


text:
Q: Convert Plain password into .NET Membership HASH password in T-SQL We have a system that stores the username/password as plain text. I have been asked to covert this to Membership.
I'd like a SQL function to convert the plain text password into .NET Membership Hashed password. The only HashBytes function I found doesn't even come close to what I see in the .NET Membership table.
I am desperate. Please help.

A: I learnt that you cannot generate the same HASH algorithm in T-SQL and the best way is to simple read your basic table to the ASP.net side, then call the Membership Script to insert users. This cuts down on time as well.
DataSet dtData = DivDatabase.ExecuteSQLString("SELECT * FROM Users");

foreach (DataRow row in dtData.Tables[0].Rows)
{
    MembershipUser mUser = null;
    mUser = Membership.GetUser(row["Username"].ToString());
    if (mUser == null)
    {
        mUser = Membership.CreateUser(row["Username"].ToString(), row["Password"].ToString(), row["Email"].ToString() );
    }
}

I first check if the userName is not in the system already. This is because I had duplicating usernames and I wanted to eliminate that. For additional information from the old table that doesn't exist in the Membership tables, we agreed with the senior management that we are not going to use the Membership Profile as it's not easy to write queries against this. But I have added sample code for reference.
var profile = System.Web.Profile.ProfileBase.Create(row["Username"].ToString());
profile.SetPropertyValue("FirstName", row["FirstName"].ToString());
profile.SetPropertyValue("LastName", row["LastName"].ToString());
profile.Save();

I hope you find this useful.


text:
Q: UIAutomation logElementTree() returns UIAElementNil When us this line of code to logElementTree() in Instruments UIAutomation  target.frontMostApp().mainWindow().logElementTree();
The results return is UIAElementNil
Even when I record a script and tap on the screen the only line that gets recorded is target.frontMostApp().tap();

A: you might have enabled accessibility for the main view.
if your provide the accessibility label for the main view then you will not get accessibility label for the child. try removing accessibility for the main view, you will get full hierarchy.

A: Don't set isAccessibilityElement = YES. If you do then the subviews of that element are hidden.
You should set accessibilityItentifier = @"xxxx"; isAccessibilityElement = NO;

A: Dont use "target.frontMostApp().mainWindow().logElementTree();", instead use "target.logElementTree()" always. It will display all the elements present on the current screen.

A: don't use target.frontMostApp().mainWindow().logElementTree();
Instead of your code replace it with this:
var target = UIATarget.localTarget();
target.logElementTree();


text:
Q: bisection search causes infinite loop I want to use bisection search to find out how much monthly payment should be in order to pay the full amount of balance within 12 months which user will input. However, this code I write goes into the infinite loop,showing "low, high, montlyPayment infinite times." I don't know which code causes this problem since conditional statement seems right to me .
initialBalance = float(raw_input('Enter the outstanding balance on your           credit card'))
annualInterestrate = float(raw_input('Enter the annual credit card  interest rate as a decimal'))
monthlyInterestrate = round(annualInterestrate, 2)

balance = initialBalance
while balance > 0:
    numMonth = 0
    balance = initialBalance
    low = balance/12.0
    high = (balance*(1+(annualInterestrate/12.0))**12.0)/12.0
    epsilon = 0.01
    monthlyPayment = round((high + low)/2.0, 2)
    while abs(monthlyPayment*12.0 - initialBalance) >= epsilon:
        print 'low =', low, 'high =', high, 'monthlyPayment =', round(monthlyPayment,2)
        if monthlyPayment*12.0 < balance:
            low = monthlyPayment
        else:
            high = monthlyPayment
        monthlyPayment = round((high + low)/2.0, 2)
        while balance > 0 and numMonth < 12:
            numMonth += 1
            interest = monthlyInterestrate * balance
            balance -= monthlyPayment
            balance += interest
balance = round(balance, 2)

print 'RESULT'
print 'monthly payment to pay off debt in 1 year:', monthlyPayment
print 'Number of months needed:', numMonth
print 'Balance:',balance

A: I have re-coded the above problem as
balance = 120000
annualInterestRate = 0.1
rate=annualInterestRate/12.0
high=(balance * (1 + rate)**12) / 12.0
low=balance/12.0
payment=0
bal_ref=balance
unpaid=balance
N=0
while (abs(unpaid) > .01):
    month=0
    pay=(high+low)/2
    balance=bal_ref
    while(month < 12):
        unpaid=balance-pay
        balance=unpaid + (unpaid * rate)
        month +=1
    if (abs(unpaid) < .01):
        payment=pay
        break
    elif (unpaid > .01):
        low=pay
    elif (unpaid < -.01):
        high=pay
    N+=1
print("Payment:",round(pay,2))


text:
Q: Ethernet won't connect (18.04.2) I left my computer running for an hour or two, idle, and when I logged back in, the ethernet connection was stuck on "connecting." I should probably mention that I installed some tools with Katoolin, which may have messed with my network settings. What steps should I take, beyond router reset, unplugging/replugging the cable, and restarting network-manager? Thanks!

A: Apparently, the system wasn't loading the network driver, so the interface wasn't detected. sudo modprobe r8169 appears to have fixed it.


text:
Q: C++ Virtual Destructor with Unresolved externals I have two classes..
template <class T>
class Node
{
protected:
    Node() = default;
    virtual ~Node() = 0;
    Node(const T& data) noexcept;
    Node(const Node<T> & copy) noexcept;
    Node(Node<T> && copy) noexcept;
    Node<T> & operator=(const Node<T> & rhs) noexcept;
    Node<T> & operator=(Node<T> && rhs) noexcept;
public:
    T & GetData() noexcept;
    T GetData() const noexcept;
    void SetData(const T & data) noexcept;
private:
    T data_;
};

template<class T>
class ListNode : public Node<T>
{
public:
    ListNode() = default;
    ListNode(const T& data, ListNode<T> * next = nullptr, ListNode<T> * previous = nullptr) noexcept;
    ListNode(const ListNode<T> & copy) noexcept;
    ListNode(ListNode<T> && copy) noexcept;
    ~ListNode() override = default;
    ListNode<T> & operator=(const ListNode<T> & rhs) noexcept;
    ListNode<T> & operator=(ListNode<T> && rhs) noexcept;
    ListNode<T> * GetNext() noexcept;
    ListNode<T> * GetPrevious() noexcept;
    void SetNext(ListNode<T> * const next) noexcept;
    void SetPrevious(ListNode<T> * const previous) noexcept;
private:
    ListNode<T> * next_;
    ListNode<T> * previous_;
};

I get an "1 unresolved externals" error. In my previous experience this would usually mean something is wrong with virtual, override, or something like that. I've messed around with this code but can't make the error go away. Any advice?

A: Derived destructors always implicitly invoke the base destructor at the end of their execution. You have code that is trying to invoke an abstract function. You need to give ~Node() a definition with an empty function body:
virtual ~Node() {};


text:
Q: Confidence interval for Brier score in R I am using the lrm function in the rms package in R to fit a logistic regression model. The function outputs various useful stats, including Brier score.

Is it possible to output the confidence interval for these statistics, especially the Brier score?
If not then what are the other ways of doing this?
EDIT: The calculation of the confidence interval is somehow related to the Spiegelhalter's z-statistic. I am not sure how. The brier function in STATA does output this statistic.


text:
Q: hibernate criteria sqlRestriction I have:
criteria.createAlias(withAlias(alias, PLAN_PROPERTY), PLAN_ALIAS)
                    .add(Restrictions.eqProperty(withAlias(alias, "course"), withAlias(PLAN_ALIAS, "years")));

where course is integer, years is float.
Need to do FLOOR() on the years property. alias is the current entity alias.
I would like to do this with Restrictions.sqlRestriction() like this:
Restrictions.sqlRestriction("{alias1}.course = FLOOR({alias2}.years)")

but we can use only the keyword {alias} that is processed by hibernate and returns the current criteria root entity alias. How to do this with two different aliases of inner join tables?


text:
Q: Javascript and PHP Encryption/Decryption Basically, I have an ajax form that carries login information, is there any way I can encrypt the password before it sends in ajax then decrypt it in php?
Or any other ways I should look at it?
Many thanks :)

A: There is no reason to do any encryption in JavaScript or PHP as the appropriate solution is to use SSL (HTTPS). Nowadays you can even get certificates which are trusted in all browsers for free so there's no reason for not using SSL.
If you cannot use SSL for some reason, you could get a JavaScript implementation of RSA so you can encrypt it locally but only your server is able to decrypt it again.

A: You could use RC4, since I know theres an implementation of it in PHP and Javascript. However, with any sort of encryption, you'd have to leave the key client side (so it can encrypt it), which means that anyone who has access to your page can get the key and decrypt it (thus defeating the point).
You might be better off either hashing it client-side (and then matching the hashes in PHP, if you don't need to know the password), or using Public-Private key encryption (like RSA), so that clients can encrypt, but not decrypt it.
For hashing, look at hash() and sha1 for Javascript.
And for RSA, check out this blog post http://www.sematopia.com/2008/10/rsa-encrypting-in-javascript-and-decrypting-in-php/

A: Use an SSL certificate and send the login over HTTPS from your AJAX form.

A: You can't in a secure manner. you should use https

A: You can do md5(password) in both JS and PHP, and then compare the encrypted passwords.
As username is not encrypted, you can use it to take the password from DB in PHP, and then encrypt it.
Best way to do that is:

*

*generate a uniqid, save it in $_SESSION['crypt_key'], and send it as a hidden input on the ajax form;

*encrypt in JS using md5(crypt_key + password) before sending it;

*encrypt in PHP using md5($_SESSION['crypt_key'] . $password) and compare them. This way, every request will transfer an unpredictable crypted password.


text:
Q: Unable to tokenize multiple columns in a dataframe I have a table with both numeric and string data but in separate columns. The table is answers to a web form and contains empty cells. I want to use text processing on the string columns. I cannot drop the rows with empty cells so for the empty string columns, I replaced the NaN with aplhabet 'a'.
Sample data
colmun_name1    column_name2     column_name3 column_name4 classify
This is a cat   This is a dog    1            2            0
This is a rat   This is a mouse  45           32           1
a               Good mouse       0            0            0

I used the following code to make sure all data in the string columns is actually string data.
df2=df[[column_name1, column_name2]]
for i in range(0,len(df2)):
cell=df2.iloc[i]
cell=str(str)
df2.iloc[i]=cell

Then when I tokenize, I get an error
    <ipython-input-64-24a99733ba19> in <module>
      1 from nltk.tokenize import word_tokenize
----> 2 tokenized_word=word_tokenize(df2)
      3 print(tokenized_word)

/anaconda3/lib/python3.6/site-packages/nltk/tokenize/__init__.py in word_tokenize(text, language, preserve_line)
    126     :type preserver_line: bool
    127     """
--> 128     sentences = [text] if preserve_line else sent_tokenize(text, language)
    129     return [token for sent in sentences
    130             for token in _treebank_word_tokenizer.tokenize(sent)]

/anaconda3/lib/python3.6/site-packages/nltk/tokenize/__init__.py in sent_tokenize(text, language)
     93     """
     94     tokenizer = load('tokenizers/punkt/{0}.pickle'.format(language))
---> 95     return tokenizer.tokenize(text)
     96
     97 # Standard word tokenizer.

/anaconda3/lib/python3.6/site-packages/nltk/tokenize/punkt.py in tokenize(self, text, realign_boundaries)
   1239         Given a text, returns a list of the sentences in that text.
   1240         """
-> 1241         return list(self.sentences_from_text(text, realign_boundaries))
   1242
   1243     def debug_decisions(self, text):

/anaconda3/lib/python3.6/site-packages/nltk/tokenize/punkt.py in sentences_from_text(self, text, realign_boundaries)
   1289         follows the period.
   1290         """
-> 1291         return [text[s:e] for s, e in self.span_tokenize(text, realign_boundaries)]
   1292
   1293     def _slices_from_text(self, text):

/anaconda3/lib/python3.6/site-packages/nltk/tokenize/punkt.py in <listcomp>(.0)
   1289         follows the period.
   1290         """
-> 1291         return [text[s:e] for s, e in self.span_tokenize(text, realign_boundaries)]
   1292
   1293     def _slices_from_text(self, text):

/anaconda3/lib/python3.6/site-packages/nltk/tokenize/punkt.py in span_tokenize(self, text, realign_boundaries)
   1279         if realign_boundaries:
   1280             slices = self._realign_boundaries(text, slices)
-> 1281         for sl in slices:
   1282             yield (sl.start, sl.stop)
   1283

/anaconda3/lib/python3.6/site-packages/nltk/tokenize/punkt.py in _realign_boundaries(self, text, slices)
   1320         """
   1321         realign = 0
-> 1322         for sl1, sl2 in _pair_iter(slices):
   1323             sl1 = slice(sl1.start + realign, sl1.stop)
   1324             if not sl2:

/anaconda3/lib/python3.6/site-packages/nltk/tokenize/punkt.py in _pair_iter(it)
    311     """
    312     it = iter(it)
--> 313     prev = next(it)
    314     for el in it:
    315         yield (prev, el)

/anaconda3/lib/python3.6/site-packages/nltk/tokenize/punkt.py in _slices_from_text(self, text)
   1293     def _slices_from_text(self, text):
   1294         last_break = 0
-> 1295         for match in self._lang_vars.period_context_re().finditer(text):
   1296             context = match.group() + match.group('after_tok')
   1297             if self.text_contains_sentbreak(context):

TypeError: expected string or bytes-like object

I tried changing
df2=df[column_name1][column_name2]

But I get the same error.
What should I do?

A: Please see How to apply NLTK word_tokenize library on a Pandas dataframe for Twitter data?
TL;DR
# Creates a `colmun_name1_tokenized` column by
# taking the `colmun_name1` column and
# applying the word_tokenize function on every cell in the column.

>>> df['colmun_name1_tokenized'] = df['colmun_name1'].apply(word_tokenize)

>>> df.head()
    colmun_name1     column_name2  column_name3  column_name4  classify  \
0  This is a cat    This is a dog             1             2         0
1  This is a rat  This is a mouse            45            32         1
2              a       Good mouse             0             0         0

  colmun_name1_tokenized
0     [This, is, a, cat]
1     [This, is, a, rat]
2                    [a]

If you need more than one column to be tokenized and you want to overwrite the column with the tokenized output:
>>> with StringIO(file_str) as fin:
...     df = pd.read_csv(fin, sep='\t')
...
>>> for col_name in ['colmun_name1', 'column_name2']:
...     df[col_name] = df[col_name].apply(word_tokenize)
...
>>> df.head()
         colmun_name1          column_name2  column_name3  column_name4  \
0  [This, is, a, cat]    [This, is, a, dog]             1             2
1  [This, is, a, rat]  [This, is, a, mouse]            45            32
2                 [a]         [Good, mouse]             0             0

   classify
0         0
1         1
2         0

Just the code:
from io import StringIO

import pandas as pd

from nltk import word_tokenize

file_str = """colmun_name1\tcolumn_name2\tcolumn_name3\tcolumn_name4\tclassify
This is a cat\tThis is a dog\t1\t2\t0
This is a rat\tThis is a mouse\t45\t32\t1
a\tGood mouse\t0\t0\t0 """

with StringIO(file_str) as fin:
    df = pd.read_csv(fin, sep='\t')

for col_name in ['colmun_name1', 'column_name2']:
    df[col_name] = df[col_name].apply(word_tokenize)

A: I think your mistake is pretty simple replace cell=str(str) with cell=str(cell).
Also you need to have correct indentation and you can't call str on a row, only on individual cells. So your code should look something like this minimal example
import pandas as pd

data_dict = {'a':[l for l in 'aakjnasnkdf']+[None],
               'b':[l for l in 'aakjnasnkdf']+[1],
               'c':range(12)}

df=pd.DataFrame(data_dict)

column_name1 ='a'
column_name2 =  'b'
df2=df.loc[:,[column_name1, column_name2]]

for i in range(0,len(df2)):
    cell1, cell2 = df2.iloc[i]
    cell1=str(cell1)
    cell2 = str(cell2)
    df2.iloc[i]=[cell1,cell2]


text:
Q: Guava - Can a Multimap be serialized? I am looking at this API ArrayListMultiMap which implements the Serializable interface. Does that mean I can serialize this object ? Are all Multimap objects serialized ?

A: The meaning of Serializable is always the same: If an object isn't serializable, it can't be serialized. If it is, it may work or not... Especially in case of collections (including maps and multimaps), it depends on their content.
As an example, you can surely serialize ArrayList<String> as ArrayList.class is serializable and so is each member of the list. OTOH trying to serialize ArrayList<Object> may or may not work: If all contained objects are e.g. strings, it will work. If any member is not serializable, you'll get an exception.

Does it mean I can serialize this object?

If all keys and values are serializable, you can.

Are all multiMap object serializable?

No, the interface Multimap doesn't extend Serializable, so there may be non-serializable implementation. Indeed, you can get such an instance via e.g. Multimaps.filterEntries.

A: ArrayListMultimap and HashMultimap are Serializable BUT the Collection views (in asMap() for example) are not.
This problem is answered here:
To use the map returned by asMap(), you can re-create a new map and wrap the Multimap Collection views into other collections (for example a Set), that will make the new map Serializable:
Multimap<MyClass, MyOtherClass> myMultiMap = HashMultimap.create();
// ... build your multimap
Map<MyClass, Set<MyOtherClass>> map = myMultiMap.asMap().entrySet()
    .stream()
    .collect(Collectors.toMap(
        Map.Entry::getKey,
        (entry) -> ImmutableSet.copyOf(entry.getValue())
    ));

Or java 7 compliant code:
Multimap<MyClass, MyOtherClass> myMultiMap = HashMultimap.create();
// ... build your multimap
Map<MyClass, Set<MyOtherClass>> map = Maps.newHashMap();
for (Map.Entry<MyClass, Collection<MyOtherClass>> entry :
myMultiMap.asMap().entrySet()) {
    map.put(entry.getKey(), ImmutableSet.copyOf(entry.getValue()));
}


text:
Q: How can I find out what's causing differences in generated Sandcastle docs? In Noda Time, we generate our documentation using Sandcastle and SHFB. We then commit the documentation back into the source repository - primarily because that makes it easy to view the latest (and historical) docs.
I'm the primary developer for the project, but I use two computers - and unfortunately, at the moment they're building different documentation even though they're both updated to the same source.
The two computers are the same in every important way I can think of:

*

*Sandcastle 2.7.2.0

*SHFB 1.9.6.0

*VS 2012 Professional (both reported version 11.0.50727.1 in "Programs", both "Version 11.0.51106.01 Update 1" in the "About" page)

*Latest version of local help content for .NET Framework 4.5 (and no local help content for other framework versions)

Steps taken to ensure a clean build:

*

*Deleted the SHFB cache folder (C:\Users\Jon\AppData\Local\EWSoftware\Sandcastle Help File Builder\Cache)

*Deleted the folder the documentation is generated into

*Deleted the user settings file related to the SHFB project file

*Deleted the symbol cache in Visual Studio

Still the differences remain. They appear to be limited to documentation inherited from MSDN itself, in particular Object.Finalize.
Version 1 (generated on machine "Chubby"):

Allows an object to try to free resources and perform
other cleanup operations before it is reclaimed by garbage collection.

Version 2 (generated on machine "Sandy"):

Allows an
   Object to attempt to free resources and perform other cleanup operations
   before the Object is reclaimed by garbage collection.

Both link to the same MSDN documentation, which looks like version 1 (no links to Object).
Looking at a few of the changed files, the change is consistent and restricted to this member.
Where might Sandcastle be getting this documentation from, and how can I get both computers to behave the same way?
EDIT: One more fragment of information - after cleaning the cache and rebuilding the docs on both machines, there are three files in the SHFB Cache directory:

*

*Reflection.cache has the same size on both machines

*MsdnUrl.cache has the same size on both machines

*.NETFramework_4.0.0319_E8879A28.cache has size 13,377,733 bytes on Chubby, and 13,337,949 bytes on Sandy

EDIT: Significant progress! I've found where the difference is probably coming from...
The file c:\Windows\Microsoft.NET\Framework\v2.0.50727\en\mscorlib.xml:

*

*On Chubby is 8,005,263 bytes with a date of 12th December 2011, and has the non-linked text for Finalize

*On Sandy is 9,740,370 bytes with a date of 31st August 2009, and has the text for Finalize which includes links

On both machines, mscorlib.dll itself is the same size (4,550,656 bytes) and has a modified date of 13th September 2012.
But how can I get them to be the same? Where does that difference come from? (Service packs?)
EDIT: Okay, the version in c:\Windows was a red herring - it's the version in c:\Program Files (x86)\Reference Assemblies\Microsoft\Framework that's to blame. I'm going to see if I can find out why that might be different between installations...

A: A couple of ideas considering your recent edits, although I agree it is a bit shooting in the dark...
I would use a tool like "Beyond Compare" to compare the .Net Framework files and XML files on both machines ("folder compare" profile).
Favour the binary level comparison to be perfectly sure... if both of your machines are local, it should be very fast.
You can also try to run Mark Russinovich's Process Monitor ( http://live.sysinternals.com/procmon.exe ) on both machines and run the documentation building process.
This way, you will see which files are being read from and involved in the help file building process, and where they are coming from...
You will get a lot of output as it will show everything that happens in your system; you may want to disable registry and network monitoring, to only leave file monitoring, and also exclude any process unrelated to the documentation building process.
I'm not an help generation expert, but I would think that the text comes from the XML files, so you may want to put a filter on only showing the xml files as well.
If you can identify the files involved, then you might just have to copy them from one machine over to the other.


text:
Q: AngularJS Event not firing from $rootScope I've got a problem where $rootScope.$broadcast events aren't being fired:
App.run(function($rootScope){
    var text = 'Not So Static Now';
    $rootScope.$broadcast('event:staticText', text);
}).$inject = ['$rootScope'];

App.controller('Ctrl1', function($scope, $rootScope) {
   $scope.staticText = "Static Text";

    var things = [
        'AngularJS',
        'StackOverflow',
        'JSFiddle'
    ];

    $scope.$emit('event:things', things);

    $scope.$on('event:staticText', function(e, args){
        $scope.staticText = args;
    });

}).$inject = ['$scope', '$rootScope'];

The above should change the {{staticText}} output to 'Not so Static Now' but it doesn't.
I've created a JSFiddle to demonstrate the problem http://jsfiddle.net/flavrjosh/uXzTV/
This is part of a bigger issue I'm trying to debug where IE9 isn't firing the events after the page gets refreshed (works first time but on refresh - F5 or the refresh button nothing happens).
Any help / Advice would be appreciated

A: It appears that the problem's caused by the Child scopes not being setup when the $rootScope.$broadcast event is fired.
I resolved the example by using:
App.run(function($rootScope, $timeout){
    var text = 'Not So Static Now';

    $timeout(function(){
        $rootScope.$broadcast('event:staticText', text);
    }, 100);
}).$inject = ['$rootScope'];

and:
App.controller('Ctrl1', function($scope, $rootScope) {
    $scope.staticText = "Static Text";

    var things = [
        'AngularJS',
        'StackOverflow',
        'JSFiddle'
    ];

    $scope.$emit('event:things', things);

    $scope.$on('event:staticText', function(e, args){
        $scope.$apply(function(){
            $scope.staticText = args;
        });
    });

}).$inject = ['$scope', '$rootScope'];

which can be seen here
Not sure if this is the best solution but it works.


text:
Q: Installing .whl file on Heroku I am currently trying to host my Python Django-powered website on Heroku but the CLI failed during installation of a required package, Numpy+Mkl (pip could not find links for the package).
I have installed the package on my dev server through the .whl file I have download in Christoph Gohlke's online repository of python packages.
I am wondering if are there some ways I could install this package on Heroku? Or do I have to find other hosting sites? If yes, can you recommend a better hosting site?


text:
Q: Passing global variables from page inline script to Symfony webpack encore How to use global variables if they are defined inline on the html page? ex: <script> var userLoggedIn= true </script>
As per https://github.com/symfony/webpack-encore/issues/331 it is recommended to export the vars needed, but I only want some dynamic variables from the Twig template.

A: maybe you can put your twig variables in html hidden fields.


text:
Q: Amazon JetS3t API and Glassfish Server Where do I put the Amazon JetS3t and the related jar files in Glassfish 3?
I have a sample Restful Web application which currently uses a Arraylist to maintain objects at back-end, I would like them to be stored as text files on Amazon S3. So I am using jets@t API for that.
When I deploy the application onto Glassfish, it throes an error like this
Caused by: java.lang.ClassNotFoundException: org.jets3t.service.security.ProviderCredentials
    at

org.glassfish.web.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1519)   at org.glassfish.web.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1369)    ... 45 more

A: GlassFish v3 has a well defined Class Loader hierarchy which identifies the common class loader as the proper way to deal with shared libraries. So to make a long story short, putting you libraries and other framework JARs in domains/domain1/lib is all you need to do.
Good luck!


text:
Q: Safari 10 CSS.supports('display', 'contents') returns true even though it is not supported? According to CanIUse.com, display:contents has some support across browsers.
https://caniuse.com/#feat=css-display-contents
I would like to enable the feature in browsers which support and disable the feature in browsers which do not support.
So, I use CSS.supports('display', 'contents'); to determine if it is supported or not. In IE11, I have to make an extra check because CSS is not supported.
However, my expectation is that in Safari11, it should return true, and in Safari10, it should return false. Instead what happens is both return true. The UI clearly looks correct in 11, however in 10, there are undesirable effects because display: contents does not actually work, so my patch-class is not applied & UI looks wrong. This is confirmed to be caused by the invalid feature detection.
I searched for solutions to detect Safari10 (and not Safari11), but unable to find anything that works.
How can I tell from JavaScript accurately wether or not the feature is supported / I am in Safari 10?

A: Here's a solution:
@supports (display: contents) and (not (-webkit-flow-from: main)) {
  /**/
}

the display: contents-check only raises a false flag up to Safari 11, so I've been scrolling through the CSS values on caniuse and found CSS Regions, which is only supported by MS browsers up to Edge 18 (the last version that doesn't use Chrome's rendering engine) and Safari versions up to 11.IE doesn't support @supports and Edge doesn't support -webkit-flow-from.
I haven't tested this, by the way, since I don't own any Apple products. If someone could do that, that would be great.


text:
Q: Wordpress On Edit Post Page Save, Update Post Meta I am trying to create/update post meta when you create/update a post that is specifically a post type of "offer". However, it does not update the post meta. This code is added in my functions.php file.
add_filter( 'pre_post_update', 'update_voucher_deadline', 10, 2 );
function update_voucher_deadline( $post_id, $data ) {
    $evergreen = get_field('offer_evergreen', $post_id);
    if ($evergreen == "evergreen-yes") {
        $year = date('Y');
        $month = date('m');
        $currentDate = "". $year . "-" . $month . "-" . date('d') . date('H') . ":" . date('i') . ":" . date('s');
        $day = date("t", strtotime($currentDate));
        $endOfMonth = "". $year . "-" . $month . "-" . $day . "23:59:00";

        //global $post; Tried with this uncommented and also didn't work.

        if ( ! add_post_meta($post_id, 'offer_voucher_deadline', $endOfMonth)) {
            update_post_meta($post_id, 'offer_voucher_deadline', $endOfMonth);
        }
    }
}

A: I see you use ACF plugin to create custom field which means you can use acf/save_post filter to do this something like this.
1. Check if we save post type 'offer'
2. Check if we have custom field 'offer_evergreen' with value 'evergreen-yes'
3. Check if we have custom filed 'offer_voucher_deadline' if yes - update him.
4. If we do not have custom filed 'offer_voucher_deadline' create him and save
our data.
add_filter('acf/save_post', 'update_voucher_deadline', 20);
function update_voucher_deadline($post_id) {
    if ( get_post_type($post_id) != 'offer' ) //if current post type not equal 'offer' return
        return;

         $year = date('Y');
         $month = date('m');
         $currentDate = "". $year . "-" . $month . "-" . date('d') . date('H') . ":" . date('i') . ":" . date('s');
         $day = date("t", strtotime($currentDate));
         $endOfMonth = "". $year . "-" . $month . "-" . $day . "23:59:00";

    if ( get_field('offer_evergreen') == 'evergreen-yes' ) {

        if ( get_post_meta( $post_id, 'offer_voucher_deadline', true ) ) //If get post meta with key 'offer_voucher_deadline' - update meta
            update_post_meta($post_id, 'offer_voucher_deadline', $endOfMonth);
        else //else if do not have post meta with key 'offer_voucher_deadline' create post meta
            add_post_meta( $post_id, 'offer_voucher_deadline', $endOfMonth);

    } else {
        return; //Remove return and add what you want to save, if offer_evergreen not equal to evergreen-yes
    }
}

A: First of all pre_post_update hook will not fires on create, it will fires immediately before an existing post is updated.
You need to use save_post hook it will triggered whenever a post or page is created or updated
add_action( 'save_post', 'update_voucher_deadline', 10, 3 );
/**
 * Save post metadata when a post is saved.
 *
 * @param int $post_id The post ID.
 * @param post $post The post object.
 * @param bool $update Whether this is an existing post being updated or not.
 */
function update_voucher_deadline( $post_id, $post, $update ) {
    $evergreen = get_field('offer_evergreen');
    if ($evergreen == "evergreen-yes") {
        $year = date('Y');
        $month = date('m');
        $currentDate = "". $year . "-" . $month . "-" . date('d') . date('H') . ":" . date('i') . ":" . date('s');
        $day = date("t", strtotime($currentDate));
        $endOfMonth = "". $year . "-" . $month . "-" . $day . "23:59:00";

        //global $post; Tried with this uncommented and also didn't work.

        if ( ! add_post_meta($post_id, 'offer_voucher_deadline', $endOfMonth)) {
            update_post_meta($post_id, 'offer_voucher_deadline', $endOfMonth);
        }
    }
}

Note: you can update your function using $update param if necessary.


text:
Q: Assimp leaking memory I recently passed my game engine to a memory leak test with valgrind; it actually told me that there are ~7000 bytes being leaked in my Mesh class;  the strange thing is that is tells me this :
7,280 bytes in 1 blocks are definitely lost in loss record 391 of 393
==5639==    at 0x4C2C100: operator new(unsigned long) (in /usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so)
==5639==    by 0x598647E: ??? (in /usr/lib/libassimp.so.3.0.1264)
==5639==    by 0x597F37D: ??? (in /usr/lib/libassimp.so.3.0.1264)
==5639==    by 0x58139E5: ??? (in /usr/lib/libassimp.so.3.0.1264)
==5639==    by 0x581E2B2: Assimp::Importer::ReadFile(char const*, unsigned int) (in /usr/lib/libassimp.so.3.0.1264)
==5639==    by 0x40D71A: glDetail::CMesh::CMesh(char const*) (Mesh.cpp:49)
==5639==    by 0x412FB5: _ZN9__gnu_cxx13new_allocatorIN8glDetail5CMeshEE9constructIS2_IRPKcEEEvPT_DpOT0_ (in /home/mattmatt/workspace/C++/alpha++/main-dev/eclipse/Alpha++/Debug/Alpha++)

So Question is : is Assimp responsible for the leaked memory ? Here is the part of code which is in question :
CMesh::CMesh(const char* fileName){
    Assimp::Importer importer;

    const aiScene* scene = importer.ReadFile(fileName,  aiProcess_Triangulate |
                                                        aiProcess_GenSmoothNormals |
                                                        aiProcess_FlipUVs |
                                                        aiProcess_CalcTangentSpace
                                                        );
    if(!scene){
        LOG_ERROR("Mesh", "ERROR LOADING MESH ! : CHECK THE SUPPORTED MODEL TYPES MODEL I OR THE FILE PATH !");
        abort();
    }
    const aiMesh* model = scene->mMeshes[0];

    std::vector<Vertex> vertices;
    std::vector<unsigned int> indices;

    const aiVector3D aiZeroVector(.0f, .0f, .0f);
    IndexedModel out;

    for(unsigned i = 0; i < model->mNumVertices; ++i)
    {
        const aiVector3D* pPos = &(model->mVertices[i]);
        const aiVector3D* pNormal = &(model->mNormals[i]);
        const aiVector3D* pTexCoord = model->HasTextureCoords(0) ? &(model->mTextureCoords[0][i]) : &aiZeroVector;

        const aiVector3D* pTangent = &(model->mTangents[i]);

        Vertex vert (
                        glm::vec3(pPos->x, pPos->y, pPos->z),///positions
                        glm::vec2(pTexCoord->x, pTexCoord->y),///UV coords
                        glm::vec3(pNormal->x, pNormal->y, pNormal->z),///normals
                        glm::vec3(pTangent->x, pTangent->y, pTangent->z)///tangents

                    );

        vertices.push_back(vert);

        out.positions.push_back(*vert.getPos());
        out.texCoords.push_back(*vert.getTexCoord());
        out.normals.push_back(*vert.getNormal());
        out.tangents.push_back(*vert.getTangent());
    }
    for(unsigned i = 0; i < model->mNumFaces; ++i){
        const aiFace& face = model->mFaces[i];
        assert(face.mNumIndices == 3);
        indices.push_back(face.mIndices[0]);
        indices.push_back(face.mIndices[1]);
        indices.push_back(face.mIndices[2]);
    }

    importer.FreeScene();

    out.indices = indices;
    initMesh(out);
}

the full code for my mesh class can be viewed at this question Memory Leak in opengl Mesh class if necessary :)
////////////////////////////Important Edit///////////////////////////
I isolated the part of code which leaked resources :
Assimp::Importer importer;

       const aiScene* scene = importer.ReadFile("res/Suzy.obj",  aiProcess_Triangulate |
                                                           aiProcess_GenSmoothNormals |
                                                           aiProcess_FlipUVs |
                                                            aiProcess_CalcTangentSpace
                                                           );
       if(!scene){
           LOG_ERROR("Mesh", "ERROR LOADING MESH ! : CHECK THE SUPPORTED MODEL TYPES MODEL I OR THE FILE PATH !");
           abort();
       }

What do I have to change ?

A: I've experienced those errors too with SDL2 or opengl; You  have to assume that the assimp devs know what they are doing; same thing for opengl, glew
and SDL2.

A: The documentation of Importer::ReadFile(const char *, unsigned) states:

If the call succeeds, the contents of the file are returned as a pointer to an aiScene object. The returned data is intended to be read-only, the importer object keeps ownership of the data and will destroy it upon destruction.

Based on this, it would appear that you are using the Assimp library correctly, but there is a memory leak issue within the library itself.
The ??? lines mean that debugging information is not available.  If this is indeed a true memory leak, it is immensely useful to have debugging information in order to determine exactly where the memory leak is occurring.  Debugging information is especially important in this case because Importer::ReadFile() calls a non-virtual BaseImporter::ReadFile(const Importer*, const std::string&, IOSystem*) member, which then calls the pure-virtual BaseImporter::InternReadFile(const std::string&, aiScene*, IOSystem*) member.  I would assume that 0x58139E5 is BaseImporter::ReadFile().  Stack frames beyond that would depend on which BaseImporter implementation was selected by Importer::ReadFile().
On Fedora systems, debugging information can be obtained by installing the corresponding debuginfo package when available.  Fedora provides an assimp-debuginfo package that can be installed via:

sudo yum --enablerepo fedora-debuginfo,updates-debuginfo install assimp-debuginfo

On Ubuntu and Debian systems, debugging information is obtained by installing the -dbg package when available.  Unfortunately, neither Debian 8 'Jessie' nor Ubuntu 15.04 'Vivid Vervet' offer a libassimp-dbg package.
You can try building Assimp from source with debugging information.  See the Stack Overflow question Creating symbol table for gdb using cmake for instructions on how to do this.


text:
Q: Passing an unknown length of options to subprocess here is my existing (non-functional) code.
def call_GM(sourcefile):
    source = os.path.splitext(sourcefile)
    outfile = '"' + source[0] + '_straightened' + source[1] + '"'
    options = ('convert', '-auto-orient', sourcefile, outfile)
    command = 'gm'
    subprocess.call([command, options])

How do I correctly pass the contents of "options" given its length in not always fixed? This is the simplest example but I actually have similar code calling several different commands.

A: Pass command as flat list or tuple:
def call_GM(sourcefile):
    source = os.path.splitext(sourcefile)
    outfile = '"' + source[0] + '_straightened' + source[1] + '"'
    options = ['convert', '-auto-orient', sourcefile, outfile]
    command = 'gm'
    subprocess.call([command] + options)

NOTE: modified options to be a list because list + tuple is not allowed.


text:
Q: Should I use v-show with v-for I know that "v-if" must avoid with "v-for" but not sure about "v-show" because it is just to toggle the display attribute.
This is the code in case anyone wants to know. Basically, I try to switch 3 different types of filter list. The code runs fine but I just wanna know if it should be avoid like "v-if".
<template>
<button
  v-for="(filter, index) in filterList" :key="index"
  @click="chosenFilter = filter.name"
>
  {{ filter.name }}
</button>

    {{ listItem }}

</template>

A: From the official style guide: https://v2.vuejs.org/v2/style-guide/#Avoid-v-if-with-v-for-essential
There are 2 points in which it's not a good practice to use that, the 2nd one is interesting: To avoid rendering a list if it should be hidden. This one is basically fine since you're not doing heavy JS rendering, just basic CSS toggling.
So yeah, I'd say it's correct to have a v-show (and ESlint is not complaining btw).
But IMO, you can solve this kind of behavior in pretty much all cases with a computed: your filter button could be selected with an ID and your list rendering could be filtered with a filter here.
Replace @click="chosenFilter = filter.name" with @click="chooseFilter and get the ID (thanks to $event) of the item you've clicked on, then filter your list with the selected filter.


text:
Q: How do i get the audio to play in a ListView in android Studio? When it open in the emulator and i click on it the audio doesn't play. I've tried on several computers. I add a toast and the toast showed but audio didn't work.
    The mediaPlayer is declared already.
    ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, socialArrayPhrases);
    socialPhrases.setAdapter(arrayAdapter);

    socialPhrases.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> adapterView, View view, int position_of_phrase, long ld) {
            Toast.makeText(getApplicationContext(), socialArrayPhrases.get(position_of_phrase), Toast.LENGTH_SHORT).show();
            if (position_of_phrase == 0) {
                mediaPlayer = MediaPlayer.create(SpanishSocialPhrases.this, R.raw.audio);
            }

        }
    });
}

A: To play the sound from [MediaPlayer] , you need the following code :
mediaPlayer.start();

Your modified code :
ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, socialArrayPhrases);
        socialPhrases.setAdapter(arrayAdapter);

        socialPhrases.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                @Override
                public void onItemClick(AdapterView<?> adapterView, View view, int position_of_phrase, long ld) {
                    Toast.makeText(getApplicationContext(), socialArrayPhrases.get(position_of_phrase), Toast.LENGTH_SHORT).show();
                    if (position_of_phrase == 0) {
                        mediaPlayer = MediaPlayer.create(SpanishSocialPhrases.this, R.raw.audio);
                        mediaPlayer.setLooping(false); // Loop
                        mediaPlayer.start(); // Play Sound !
                    }

                }
            });
    }


text:
Q: How to setup the Mac terminal for Programming with Python? I would like to know from you guys how you have set up your Mac terminal for python programming. I havent done anything big so far (have used ide's until now) with python in terminal but I think that you can do all kinds of fancy things (automatic fill up functions, colors, ...). Any suggestions??
Thanks you guys!

A: Assuming that Python is already on your computer:
Go to /Applications folder
Then open Utilities
Double Click Terminal to open it and get a command line
type 'python' in the command prompt
Your all set!


text:
Q: Cayley-Hamilton to find a power of a matrix I have the matrix $A=\begin{pmatrix} 1& 1& -1\\ -1&-1&0\\ 0&-1&0\end{pmatrix}$, which has characteristic polynomial $P(t)=t^3+1$.
Cayley-Hamilton gives us that $P(A)=A^3+I_3=0$, how can I use this to find $A^{100}$?

A: $A^{100}=A\cdot(A^3)^{33}=A\cdot(-I_3)^{33}=A\cdot-I_3=A$
Thanks go out to @DanielFischer and @VaibhavJena


text:
Q: How to view debug messages on Android? I've got an Android app that works highly unstable and I want to fix it.  So I decompiled the apk with apktool and figured that the app call a bunch of Log.d where it writes the useful information.  Then I installed a log viewer for Android and figured that it doesn't show anything.  I read into the reviews of CatLog (for example) and the user told that it doesn't work on the newest Android version. Well, now I wonder what to do - now can I view the log trace on Android provided my phone isn't rooted?
Edit: I wonder if there is some way to modify each call of Log.d or Log.e inside *.smali files decompiled by apktool so I will be able to write say to the text file directly w/o interacting with log mechanisms of OS.  Have anyone done similar thing?
I also understand that it would be much-much better to use remote debugging, but I simply don't have an access to computer right now - only to smartphone and the Linux server by SSH.
Edit 2: Here is a manifest of an app.  I am trying to figure out if it is possible to ad debuggable flag in it.
<?xml version="1.0" encoding="utf-8" standalone="no"?><manifest xmlns:android="http://schemas.android.com/apk/res/android" android:targetSdkVersion="16" package="com.anda.otgdiskpro" platformBuildVersionCode="23" platformBuildVersionName="6.0-2704002">
    <uses-feature android:name="android.hardware.usb.accessory"/>
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
    <uses-permission android:name="android.permission.INTERNET"/>
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
    <uses-permission android:name="android.permission.WAKE_LOCK"/>
    <application android:icon="@drawable/icon" android:label="@string/app_name" android:largeHeap="true">
        <activity android:configChanges="orientation" android:label="@string/app_name" android:launchMode="singleInstance" android:name="com.anda.otgdiskpro.USBActivityPro">
            <intent-filter>
                <action android:name="android.intent.action.MAIN"/>
                <category android:name="android.intent.category.LAUNCHER"/>
            </intent-filter>
        </activity>
        <activity android:label="Settings" android:name="com.anda.otgdisk.PrefPage"/>
        <activity android:configChanges="orientation" android:label="@string/title_activity_music" android:launchMode="singleInstance" android:name="com.anda.otgdisk.MusicActivity"/>
    </application>
</manifest>

Edit 3:
Aha!  Apparently I have to put "android:debuggable="true"" I to the application tag of AndroidManifest.xml
...
Okay. I modified the AndroidManifest.xml:
    <application android:icon="@drawable/icon" android:label="@string/app_name" android:largeHeap="true" android:debuggable="true">

Compiled it to apk, signed it and installed on the smartphone.  Also I installed LogCat Extreme.  Run both apps and ... no logs in the LogCat Extreme.  It seems that Android is not allowing me to view the logs of other apps.  Right?

A: Your app needs to have debuggable true defined in the build variant for you to see Log messages.
See this documentation.
Once you have debugging enabled in your application, you can use Logcat to view your app's logs via its package name. I've never used CatLog but I'd assume it's just parsing Logcat to display the logs.

A: Try adding:
{
    debuggable true
}

in your build.gradle file.


text:
Q: How To Display Markdown Text In Command Line? I have a command line tool that needs to display short help files on hot key inputs.
Currently help files are in markdown format.
Is there an easy way to display that markdown text in command line formatted?

A: The nd tool can do it. It is written in node.js and primarily aimed at node.js package documentation. Which may or may not be suitable for your needs.


text:
Q: dynamically creating menu items that call a function, passing a different variable for each item What I need, is a menu in tkinter, where each item has the name of a playlist, and each item will go to the same function (ImportPlaylist()) , but passes a different variable, namely: the rownumber for a csv file where that playlist is stored.
This cannot be done just by hand, because it happens dynamically, i.e. the user can make his own set of playlist with his own names.
I have made a music player, and am just experimenting now with reading and writing csv files. I made a csv file, and made a function to save playlists to that csv file. The way they are saved is that in each row, the first item is the name of the playlist, after that come youtube links one by one.
What I want is now to have functions for importing the playlists. The functions should be called from a tkinter menu. So they need to be created at the opening of the program.
I was hoping to do this with a for-loop. So, the for loop would go through the csv file row by row, and for every row create a menu-item, whose name is the first item in the row, and who refers to a function ImportPlaylist, passing some argument to indicate from which row the playlist needs to be imported.
Is this even possible?
To import a playlist, I made this little bit of code, generating menu items in a tkinter window:
with open(os.path.join(sys.path[0], "AntiTubePlaylists.txt"), "r") as csv_file:
    csv_reader = csv.reader(csv_file, quotechar='"', delimiter=',')
    counter = 0
    for row in csv_reader:
        playlistmenu.add_command(label=row[0], command=(lambda:  ImportPlaylist(counter)))
        counter += 1

This doesn't work. Which I kind of understand. I suppose counter is a global variable, and therefor all my nicely generated menu items refer to the same number, which is an empty row.
Any thoughts on this?


text:
Q: How to treat autocomplete suggestion as link to that post in WordPress? So I have a WordPress site with autocomplete suggestions for my search box. What I'm trying to do is to make all autocomplete suggestions as links to that exact post/page.
Also if possible, how to separate posts from pages and add HTML div for title "Pages" and div for "Posts" ?
PHP Code: (functions.php)
<?php
/**
 * Enqueue scripts and styles.
 *
 * @since 1.0.0
 */
 function ja_global_enqueues() {
 wp_enqueue_style(
    'jquery-auto-complete',
    'https://cdnjs.cloudflare.com/ajax/libs/jquery-
 autocomplete/1.0.7/jquery.auto-complete.css',
    array(),
    '1.0.7'
 );
 wp_enqueue_script(
    'jquery-auto-complete',
    'https://cdnjs.cloudflare.com/ajax/libs/jquery-
 autocomplete/1.0.7/jquery.auto-complete.min.js',
    array( 'jquery' ),
    '1.0.7',
    true
 );
 wp_enqueue_script(
    'global',
    get_template_directory_uri() . '/js/global.min.js',
    array( 'jquery' ),
    '1.0.0',
    true
 );
 wp_localize_script(
    'global',
    'global',
    array(
        'ajax' => admin_url( 'admin-ajax.php' ),
    )
 );
 }
add_action( 'wp_enqueue_scripts', 'ja_global_enqueues' );
/**
* Live autocomplete search feature.
*
* @since 1.0.0
*/
function ja_ajax_search() {
$results = new WP_Query( array(
    'post_type'     => array( 'post', 'page' ),
    'post_status'   => 'publish',
    'nopaging'      => true,
    'posts_per_page'=> 100,
    's'             => stripslashes( $_POST['search'] ),
) );
$items = array();
if ( !empty( $results->posts ) ) {
    foreach ( $results->posts as $result ) {
        $items[] = $result->post_title;
    }
}
wp_send_json_success( $items );
}
add_action( 'wp_ajax_search_site',        'ja_ajax_search' );
add_action( 'wp_ajax_nopriv_search_site', 'ja_ajax_search' );

jQuery Code:
jQuery(function($){
var searchRequest;
$('.search-autocomplete').autoComplete({
    minChars: 2,
    source: function(term, suggest){
        try { searchRequest.abort(); } catch(e){}
        searchRequest = $.post(global.ajax, { search: term, action:
'search_site' }, function(res) {
            suggest(res.data);
        });
    }
 });
 });

HTML Code inside .php file:
<form class="navbar-form" role="search" method="get" action="<?php echo esc_url( home_url( '/' ) ); ?>">
<div class="form-group">
    <input type="text" name="s" class="form-control search-autocomplete" placeholder="Search">
</div>
<button type="submit" class="fa fa-search"></button>
</form>


text:
Q: How to overcome 412 status yielded by the Python Requests package? Why is my python script using the requests package not able to download the tar.gz file while BASH's wget command is able to? It complained that the requested resource could not be found (412). How do I overcome this issue?
Update:
I discovered that after deactivating the VPN my python script could work. It would not work when VPN is activated. However, wget worked when the VPN is and is not activated. Why is this the case? Is there some settings that need to be done on requests to overcome the 412 status?
My Python3.6 script:
#!/usr/bin/python3.6
# -*- coding: utf-8 -*-

from pathlib import Path
import requests
import sys

def download_sdk( url, sdkname ):
    print( f'\nDownloading SDK...' )
    print( f'url = {url}' )
    print( f'sdkname = {sdkname}' )
    r = requests.get( url )
    #response less than 400 response, open in binary mode and write sdk to user defined vulkan directory
    if r.ok:
        with open( sdkname, "wb" ) as file:
            file.write( r.content )
    else:
        sys.exit( print( f'Quit: requests_status_code={r.status_code}' ) )
    print( f'\nDownload Completed.' )
    return True

sdk = f'vulkansdk-linux-x86_64-1.1.121.1.tar.gz'
url = f'https://sdk.lunarg.com/sdk/download/1.1.121.1/linux/{sdk}?u='
sdkname = Path.cwd() / sdk
download_sdk( url, sdkname )

Python script's output:
Downloading SDK...
url = https://sdk.lunarg.com/sdk/download/1.1.121.1/linux/vulkansdk-linux-x86_64-1.1.121.1.tar.gz?u=
sdkname = /home/master/Vulkan/Installers/vulkansdk-linux-x86_64-1.1.121.1.tar.gz
Quit: requests_status_code=412

BASH's  wget command is able to download the tar.gz file.
$ wget https://sdk.lunarg.com/sdk/download/1.1.121.1/linux/vulkansdk-linux-x86_64-1.1.121.1.tar.gz?u=
--2020-06-17 23:11:28--  https://sdk.lunarg.com/sdk/download/1.1.121.1/linux/vulkansdk-linux-x86_64-1.1.121.1.tar.gz?u=
Resolving sdk.lunarg.com (sdk.lunarg.com)... 2604:86c0:5000:3::3, 38.143.66.106
Connecting to sdk.lunarg.com (sdk.lunarg.com)|2604:86c0:5000:3::3|:443... failed: Connection refused.
Connecting to sdk.lunarg.com (sdk.lunarg.com)|38.143.66.106|:443... connected.
HTTP request sent, awaiting response... 200 OK
Syntax error in Set-Cookie: u=H0TJAB4JavYv3jKUtK1SDiu2UjlaBDHatNkvDosqN8ppYXwEVEX45Z60GLqE%0A6k5%2BerCS3KZHcD8RhV7liLcoYQ%3D%3D; ; path=/; SameSite=Lax at position 100.
Syntax error in Set-Cookie: a=XZxs35QBwvluz8x%2Bgl5n4w%3D%3D; expires=Fri, 10 Jun 2050 15:11:31 +0000; ; path=/; SameSite=Lax at position 74.
Length: 119858765 (114M) [application/octet-stream]
Saving to: 'vulkansdk-linux-x86_64-1.1.121.1.tar.gz?u='

vulkansdk-linux-x86_64-1.1.121.1.tar.gz?u=           100%[====================================================================================================================>] 114.31M   576KB/s    in 3m 12s

2020-06-17 23:14:43 (610 KB/s) - 'vulkansdk-linux-x86_64-1.1.121.1.tar.gz?u=' saved [119858765/119858765]

A: I got it working with this function and urllib.parse.urljoin() to generate the url:
import requests
from urllib.parse import urljoin

def download(url, path):
    response = requests.get(url) # get the response of the ink
    with open(path, 'wb') as file: # create the file
        file.write(response.content) # write the contents of the response to the file

base_url = 'https://sdk.lunarg.com/sdk/download/1.1.121.1/linux/'
sdk = 'vulkansdk-linux-x86_64-1.1.121.1.tar.gz'
query = '' # if you need to adda query stirng like '?u=' but that didn't make a difference in this case
url = urljoin(base_url, sdk, query) # make the full url
print(url)

download(url, f'./{sdk}')


text:
Q: BUSQUEDA EN COLUMNAS INDIVIDUALES - LARAVEL Quiero hacer una búsqueda en varias columnas. Algo así.

Pero no sé como hacerlo en Laravel ya que se maneja por medio de MVC.
La pagina de DATATABLES sugiere que ingrese este codigo.
$(document).ready(function() {
// Setup - add a text input to each footer cell
$('#example tfoot th').each( function () {
    var title = $(this).text();
    $(this).html( '<input type="text" placeholder="Search '+title+'" />' );
} );

// DataTable
var table = $('#example').DataTable();

// Apply the search
table.columns().every( function () {
    var that = this;

    $( 'input', this.footer() ).on( 'keyup change', function () {
        if ( that.search() !== this.value ) {
            that
                .search( this.value )
                .draw();
        }
    } );
} );

} );
La tabla la tengo actualmente luce así.

Codigo del controlador.

<?php
/**
 * Controller genrated using LaraAdmin
 * Help: http://laraadmin.com
 */

namespace App\Http\Controllers\LA;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Http\Requests;
use Auth;
use DB;
use Validator;
use Datatables;
use Collective\Html\FormFacade as Form;
use Dwij\Laraadmin\Models\Module;
use Dwij\Laraadmin\Models\ModuleFields;

use App\Models\Computer;

class ComputersController extends Controller
{
 public $show_action = true;
 public $view_col = 'n_serie';
 public $listing_cols = ['id', 'empresa', 'departamento', 'codigo', 'marca', 'modelo', 'n_serie', 'tipo', 'procesador', 'vel_procesador'];

 public function __construct() {
  // Field Access of Listing Columns
  if(\Dwij\Laraadmin\Helpers\LAHelper::laravel_ver() == 5.3) {
   $this->middleware(function ($request, $next) {
    $this->listing_cols = ModuleFields::listingColumnAccessScan('Computers', $this->listing_cols);
    return $next($request);
   });
  } else {
   $this->listing_cols = ModuleFields::listingColumnAccessScan('Computers', $this->listing_cols);
  }
 }

 /**
  * Display a listing of the Computers.
  *
  * @return \Illuminate\Http\Response
  */
 public function index()
 {
  $module = Module::get('Computers');

  if(Module::hasAccess($module->id)) {
   return View('la.computers.index', [
    'show_actions' => $this->show_action,
    'listing_cols' => $this->listing_cols,
    'module' => $module
   ]);
  } else {
            return redirect(config('laraadmin.adminRoute')."/");
        }
 }

 /**
  * Show the form for creating a new computer.
  *
  * @return \Illuminate\Http\Response
  */
 public function create()
 {
  //
 }

 /**
  * Store a newly created computer in database.
  *
  * @param  \Illuminate\Http\Request  $request
  * @return \Illuminate\Http\Response
  */
 public function store(Request $request)
 {
  if(Module::hasAccess("Computers", "create")) {

   $rules = Module::validateRules("Computers", $request);

   $validator = Validator::make($request->all(), $rules);

   if ($validator->fails()) {
    return redirect()->back()->withErrors($validator)->withInput();
   }

   $insert_id = Module::insert("Computers", $request);

   return redirect()->route(config('laraadmin.adminRoute') . '.computers.index');

  } else {
   return redirect(config('laraadmin.adminRoute')."/");
  }
 }

 /**
  * Display the specified computer.
  *
  * @param  int  $id
  * @return \Illuminate\Http\Response
  */
 public function show($id)
 {
  if(Module::hasAccess("Computers", "view")) {

   $computer = Computer::find($id);
   if(isset($computer->id)) {
    $module = Module::get('Computers');
    $module->row = $computer;

    return view('la.computers.show', [
     'module' => $module,
     'view_col' => $this->view_col,
     'no_header' => true,
     'no_padding' => "no-padding"
    ])->with('computer', $computer);
   } else {
    return view('errors.404', [
     'record_id' => $id,
     'record_name' => ucfirst("computer"),
    ]);
   }
  } else {
   return redirect(config('laraadmin.adminRoute')."/");
  }
 }

 /**
  * Show the form for editing the specified computer.
  *
  * @param  int  $id
  * @return \Illuminate\Http\Response
  */
 public function edit($id)
 {
  if(Module::hasAccess("Computers", "edit")) {
   $computer = Computer::find($id);
   if(isset($computer->id)) {
    $module = Module::get('Computers');

    $module->row = $computer;

    return view('la.computers.edit', [
     'module' => $module,
     'view_col' => $this->view_col,
    ])->with('computer', $computer);
   } else {
    return view('errors.404', [
     'record_id' => $id,
     'record_name' => ucfirst("computer"),
    ]);
   }
  } else {
   return redirect(config('laraadmin.adminRoute')."/");
  }
 }

 /**
  * Update the specified computer in storage.
  *
  * @param  \Illuminate\Http\Request  $request
  * @param  int  $id
  * @return \Illuminate\Http\Response
  */
 public function update(Request $request, $id)
 {
  if(Module::hasAccess("Computers", "edit")) {

   $rules = Module::validateRules("Computers", $request, true);

   $validator = Validator::make($request->all(), $rules);

   if ($validator->fails()) {
    return redirect()->back()->withErrors($validator)->withInput();;
   }

   $insert_id = Module::updateRow("Computers", $request, $id);

   return redirect()->route(config('laraadmin.adminRoute') . '.computers.index');

  } else {
   return redirect(config('laraadmin.adminRoute')."/");
  }
 }

 /**
  * Remove the specified computer from storage.
  *
  * @param  int  $id
  * @return \Illuminate\Http\Response
  */
 public function destroy($id)
 {
  if(Module::hasAccess("Computers", "delete")) {
   Computer::find($id)->delete();

   // Redirecting to index() method
   return redirect()->route(config('laraadmin.adminRoute') . '.computers.index');
  } else {
   return redirect(config('laraadmin.adminRoute')."/");
  }
 }

 /**
  * Datatable Ajax fetch
  *
  * @return
  */
 public function dtajax()
 {
  $values = DB::table('computers')->select($this->listing_cols)->whereNull('deleted_at');
  $out = Datatables::of($values)->make();
  $data = $out->getData();

  $fields_popup = ModuleFields::getModuleFields('Computers');

  for($i=0; $i < count($data->data); $i++) {
   for ($j=0; $j < count($this->listing_cols); $j++) {
    $col = $this->listing_cols[$j];
    if($fields_popup[$col] != null && starts_with($fields_popup[$col]->popup_vals, "@")) {
     $data->data[$i][$j] = ModuleFields::getFieldValue($fields_popup[$col], $data->data[$i][$j]);
    }
    if($col == $this->view_col) {
     $data->data[$i][$j] = 'data[$i][0]).'">'.$data->data[$i][$j].'';
    }
    // else if($col == "author") {
    //    $data->data[$i][$j];
    // }
   }

   if($this->show_action) {
    $output = '';
    if(Module::hasAccess("Computers", "edit")) {
     $output .= 'data[$i][0].'/edit').'" class="btn btn-warning btn-xs" style="display:inline;padding:2px 5px 3px 5px;">';
    }

    if(Module::hasAccess("Computers", "delete")) {
     $output .= Form::open(['route' => [config('laraadmin.adminRoute') . '.computers.destroy', $data->data[$i][0]], 'method' => 'delete', 'style'=>'display:inline']);
     $output .= ' <button class="btn btn-danger btn-xs" type="submit"></button>';
     $output .= Form::close();
    }

    $data->data[$i][] = (string)$output;
   }
  }
  $out->setData($data);
  return $out;
 }
}

Codigo de la vista

@extends("la.layouts.app")

@section("contentheader_title", "Computers")
@section("contentheader_description", "Computers listing")
@section("section", "Computers")
@section("sub_section", "Listing")
@section("htmlheader_title", "Computers Listing")
@section("headerElems")

@la_access("Computers", "create")

  <button class="btn btn-success btn-sm pull-right" data-toggle="modal" data-target="#AddModal">Add Computer</button>
  <button class="btn btn-info dropdown-toggle" data-toggle="dropdown">

   Toggole Dropdown

  </button>

@endla_access
@endsection

@section("main-content")

@if (count($errors) > 0)

            @foreach ($errors->all() as $error)

{{ $error }}

            @endforeach

@endif

   @foreach( $listing_cols as $col )
   {{ $module->fields[$col]['label'] or ucfirst($col) }}
   @endforeach
   @if($show_actions)
   Actions
   @endif

@la_access("Computers", "create")

    <button type="button" class="close" data-dismiss="modal" aria-label="Close">×</button>

Add Computer

   {!! Form::open(['action' => 'LA\ComputersController@store', 'id' => 'computer-add-form']) !!}

                    @la_form($module)

     {{--
     @la_input($module, 'empresa')
     @la_input($module, 'departamento')
     @la_input($module, 'codigo')
     @la_input($module, 'marca')
     @la_input($module, 'modelo')
     @la_input($module, 'n_serie')
     @la_input($module, 'tipo')
     @la_input($module, 'procesador')
     @la_input($module, 'vel_procesador')
     @la_input($module, 'memoria_ram1')
     @la_input($module, 'memoria_ram2')
     @la_input($module, 'memoria_ram3')
     @la_input($module, 'disco_duro1')
     @la_input($module, 'disco_duro2')
     @la_input($module, 'sistema_operativo')
     @la_input($module, 'g_inicio')
     @la_input($module, 'g_final')
     --}}

    <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
    {!! Form::submit( 'Submit', ['class'=>'btn btn-success']) !!}

   {!! Form::close() !!}

@endla_access

@endsection

@push('styles')
<link rel="stylesheet" type="text/css" href="{{ asset('la-assets/plugins/datatables/datatables.min.css') }}"/>

@endpush

@push('scripts')

@endpush

A: Lo de datatables usa ajax, asi que sería practicamente usarlo del lado del cliente y no del servidor, podrías hacerlo pero cuando sean miles de datos la página se saturará y será muy muy lento, asi que no lo sugiero usar de esa forma.
Pero si no manejarás muchos datos ingresa ese codigo javascript en la vista dentro de @push('scripts') y configuralo como dice la documentación y deberia estar funcionando correctamente.


text:
Q: Sunlight reflectors I am trying to display LEDs on a panel exposed to sunlight and they are hardly visible. What kind of reflectors can be used to make them visible? e.g. Tow truck lighting, sign displays etc

The LEDs are mounted on clothing similar to reflective vest.. and are programmable Ws2813. The target  colors are BLUE, RED, YELLOW, WHITE, and possibly green. No fixed position for the wearer. One thing that is wrong is I have a reflective band. I will use black.


text:
Q: Supremum and infimum of continuous functions on $[a,b]$ Let $\{ f_\alpha (x) \}_{\alpha \in I }$ a family of continuous functions from $[a,b]$ to $\Bbb{R}$ ($  a<b $). Now we know because $[a,b]$ is compact then  every $f_\alpha$ is uniformly continuous and every $f_\alpha $ has maximum and minimum.
My questions are :

*

*Let $f(x) = \sup  \{ f_\alpha (x) \} _{\alpha \in I }$ for $x \in [a,b] $ , is $f$ uniformly continuous ?

*Let $f(x) = \inf\{ f_\alpha (x) \} _{\alpha \in I }$ for $x \in [a,b] $ , is $f$ uniformly continuous ?
In the special case where we have $ k(x) = \max \{ f(x), g(x) \}$ and  $u(x) = \min \{ f(x), g(x) \}$, then we know $k(x)$ and $u(x)$ are continuous functions and because $[a,b]$ is compact then  $k(x)$ and $u(x)$ are uniformly continuous.

A: This is wrong in general.
Define $$f_n : [0,1] \to [0,1] \qquad f_n(x) = \begin{cases}
nx & 0≤x<\frac{1}{n}\\
1 & \frac{1}{n}≤x<1-\frac{1}{n}\\
n-nx & 1-\frac{1}{n} ≤ x ≤ 1 \end{cases} $$
Here is a picture for $n=5$ :

Then $f_n$ is uniformly continuous since it is continuous on a compact set. But $$f(x) = \sup\{f_n(x) \mid n ≥ 1\} = \begin{cases}
1 & 0<x<1\\
0 & x=0,x=1\\ \end{cases}$$ is not even continuous.
You can find similar examples for the $\inf$. (Actually the result has no meaning in general, see for instance $f_n(x)=n$ since $\sup f_n = +\infty$ is not a real-valued function).


text:
Q: How to configure my Regular Expression dot to match linebreaks? i'm trying to figure this out:
<STYLE>
lots of text
and
linebreaks
</STYLE>

how can i detect ANYTHING that lies inside the style tag (incl. linebreaks)?
i tried .*? but didn't help
thx

A: .* doesn't work with your example text because . does not match new lines.  You can either enable single-line mode in your regex implementation (some don't support it, like javascript) or you can use [\S\s]* in place of .*.

A: you probably need to add "s" modifier to the regexp. Without "s" dot doesn't match newlines.
remember however, that regexp is a wrong tool for parsing html, better consider a dedicated parsing library available in your language.

A: Regex is a bad way to parse HTML. Jeff Atwood has a nice article on it.


text:
Q: Is there a performance penalty in executing read only queries under transaction? Is there any performance penalty to define all methods as transactional using Spring AOP based declarative transaction management? See the config below. The reason is that I do not know what method name developers will give for non transactional methods. One option is I start with a wild card list and developers update the list if the method name does not fall under the defined list.
<tx:advice id="txAdvice" transaction-manager="transactionManager">
    <tx:attributes>
        <tx:method name="*" />
    </tx:attributes>
</tx:advice>

<aop:config>
    <aop:pointcut id="dtxops" expression="bean(*Service)" />
    <aop:advisor advice-ref="txAdvice" pointcut-ref="dtxops" />
</aop:config>

A: It depends on what underlying transaction manager you are using. The default spring "transaction per thread, no XA transactions" probably doesn't have a any penalty.  If you are using JBoss with the XA transaction manager, then it will write some data to a transaction log .
-- original -- Even then, I think you'd find the performance penalty to be fairly small.
-- edited -- In my experience, I haven't seen a huge increase in performance when converting to Readonly using the JBoss transaction manager.  Per the comment below, at least one user saw a 30% performance increase which is significant.

A: Theoretically there's a performance penality to adding AOP (and thus introspection/reflection) overhead to more methods than necessary. Also there's the added overhead of opening and closing more transactions than needed. It should be up to the developer coding the data-acces layer to know when and if a transaction should be started IMHO.


text:
Q: Filtering for email address with a dot I am trying to filter only the email with dot (Sam.Smith@forfun.com). But all email would be displayed to me. Is this somehow possible to get only "Sam.Smith@forfun.com" this?
PS C:\Users\Rayman>  Get-AzureADUser -SearchString "Sam".AlternateEmailAddresses
PS C:\Users\Rayman>  (Get-AzureADUser -SearchString "Sam Smith").UserPrincipalName
PS C:\Users\Rayman> Get-AzureADUser -SearchString "Sam Smith" | Select Mail
Sam.Smith@forfun.com
samsmith@forfun.com

I have tried many variants without success.

A: Use Select-Object -First 1 to discard everything but the first output item:
$samSmith = Get-AzureADUser -SearchString "Sam Smith" |Select-Object -First 1

A: Thank You Abraham Zinala for your suggestion posting this as solution to help other community member if they encounter for same requirement.
Note : Use PowerShell Version 7+ Version.
PowerShell Script :
(Get-AzureADUser -SearchString "Sam Smith"| Select Mail)[0]


text:
Q: Why the content display code html without render it? I have used MarkiItUp to build a jquery editor. Now when user type content in textarea with html code, like this:
A new true question
When record was saved, it save A new true question. And when it display on page, it also display like content was saved, is A new true question . But i want the content display on web like this:
A new true question
How can i do that?

A: To display it, use html_safe. This way your string would be rendered as HTML.
Refer to this question for more info.
Ruby on Rails: how to render a string as HTML?


text:
Q: php date time is not same $date = '11/14/1997';
$unix_birthday = strtotime($date);
echo $unix_birthday;

The result is: 879487200
When I run this code:
$time = 879487200;
echo htmlspecialchars(gmdate("Y/m/d", $time));

The result is: 1997/11/14
How Can I fix this? The dates are not same

A: echo htmlspecialchars(gmdate("m/d/Y", $time));

A: echo htmlspecialchars(gmdate("Y/m/d", $time)); should be echo htmlspecialchars(gmdate("m/d/Y", $time)); its just a matter of format

A: echo htmlspecialchars(gmdate("m/d/Y", $time));

Just rearrange m/d/Y where m = month, d =day and Y = year
Demo
http://ideone.com/2R93OZ


text:
Q: How can i extract only the words end with number? i am getting a info from back-end. i need to convert that in to multiple word, and to require to store in array. using regexp how to get that?
here is the word:
Enter Room/Area^_^Area 100#_#Enter Grid^_^Grid2#_#Enter Level / Building^_^Building1#_#Enter Drawing^_^Drawing1#_#Enter Spec section^_^Spec2#_#Enter BOQ^_^BOQ1#_#

the result should be :
["Area 100", "Grid2","Building1", "Drawing1", "Spec2", "BOQ1" ]

So simply i would like to pick the words which end with number. upto the special char ^.

A: \b[a-zA-Z0-9 ]+\d+\b

Try this.See demo.
https://regex101.com/r/wZ0iA3/6
var re = /\b[a-zA-Z0-9 ]+\d+\b/gi;
var str = 'Enter Room/Area^_^Area 100#_#Enter Grid^_^Grid2#_#Enter Level / Building^_^Building1#_#Enter Drawing^_^Drawing1#_#Enter Spec section^_^Spec2#_#Enter BOQ^_^BOQ1#_#';
var m;

while ((m = re.exec(str)) != null) {
if (m.index === re.lastIndex) {
re.lastIndex++;
}
// View your result using the m-variable.
// eg m[0] etc.
}


text:
Q: Eclipse (Aptana) Typing Lag I've been using Aptana for some time now, and as of recent I've been dealing with files that are really, really big (500+ lines of code, which is huge for me, being a novice developer). Whenever I deal with smaller files, I get that weird sensation that I'm "in front of" what's typing, but now I'm quite sure of it--there is a significant lag between when I type something and when I see the text appear on screen. I don't have this issue with Dreamweaver CS3, so I know my computer has the capability to edit these files without this happening, but Eclipse still lags.
I also don't see when something is being deleted if I hold down backspace, I see the first few characters get deleted, but then everything "hangs." Once I release the backspace key, the characters that would've been shown deleting instantly vanish all at once. The same thing happens with the forward delete key.
I'm beginning to think this is an issue with Java, since I have the same feeling that everything is slightly "behind me" when I'm using -any- Java application.
The computer is an intel Pentium 4 3.2 GHz Prescott, with 2GB's of DDR400 RAM and a Radeon HD3650 graphics card.
If anyone knows how to fix this lagging issue, I'm all ears (eyes?); if anyone can recommend a different IDE with capabilities similar to Aptana (I do Python, HTML, CSS and JS; I use Git for SCM), I'd be glad to give it a try. Thanks!

A: I'm running a brand new iMac i5 with 8GB RAM and an SSD and Eclipse is slow as hell. I don't know if upgrading your machine is really the solution to your problem.

A: In my case Aptana also was very slow while typing, and it helped to choose
Eclipse > Help > Aptana Troubleshooting > Clear Aptana Log File ...

A: I bet You have default amount of memory assigned to Eclipse in eclipse.ini file - go there and increase those values 2-3 times. Eclipse will work much faster.

A: Aptana is a great software, but you're facing one of it's disadvantages: it's a memory hog.
I'm using Aptana in a 4gb machine, but I remember having the same lags using the same configuration in your example.
If you can't live without Aptana (and Eclipe plugins), I suggest you to buy more RAM and use a HD that's at least 7200 RPM. I'm running in a Vista Machine and it works flawlessly.
If you can live without Aptana, check other Python IDE's in "What IDE to Use for Python" question right here in SO.
My 2 cents: I've used PyScripter for Python, and it's great. PyScripter with notepad++ is a good and fast choice.
Good luck!

A: I'm using the most recent version of Aptana (3.1.3.201205292243) and had this exact same problem.  Increasing the memory allotments did nothing for me.  The problem goes away, however, if I turn off the Word Wrap option in the editor.
This is found in:
 Window->Preferences->Aptana Studio->Editors->Enable Word Wrap

I know, it's a stupid fix, but it works.  :)
Luck, everyone!

A: I have the exactly same problem. Eclipse with Aptana Studio installed is really slow and not usuable for developing. Increasing the memory did not help at all. But what actually help (at least as far as I can tell until now), was to delete the Aptana log files as migg proposed.
(Eclipse Juno, Aptana Studio 3, OS X 10.8.2, Macbook Pro Retina)


text:
Q: Displaying MySQL data in  failing I am simply trying to display an html <select> drop down that displays options from MySQL database rows. As far as I can tell this should be working. However, it is not displaying anything in the drop down. the campaigns table definitely has data in the campaignid and name columns. Not sure why it isn't display anything. Please help.
the form that should display name
<?php
//include db connect
  include ("db_con.php");

   //campaign change form function
  function changeCampaign() {
    //set variables
    $query = mysqli_query($con,"SELECT * FROM campaigns");
    //echo form
    echo '

          <form action="functions/campaign_change.php" name="campaignChange" method="post">

              <select name="campaignList">';
                    //loop campaigns
                    while ($row = mysqli_fetch_array($query)) {
                      echo "<option value='" . $row['campaignid'] . "'>" . $row['name'] . "</option>";
                    }
        echo '</select>

              <input type="submit" value="Load" />

          </form>

';
}
?>

And then I am simply calling the changeCampaign(); function, which IS displaying the form with <select> just no content in it.
The following code was added to show a successful script adding to the same table
here is the form to create a campaign
//campaign creation form function
  function createCampaign() {
    echo '

          <form action="functions/campaign_create.php" name="campaignCreate" method="post">

              <input type="text" name="name" placeholder="Enter Campaign Name" required />

              <input type="submit" name="Create" />

          </form>

';
}

campaign_create.php
<?php
//include db connect
  include ("db_con.php");

//start session
  session_start();

//set variable names
  $username = $_SESSION['username'];
  $campaignname = addslashes($_POST['name']);

//validate campaign name length
  if ((strlen($campaignname) < 6) || (strlen($campaignname) > 55)) {
    echo 'Campaign name must be between 6 and 55 characters - Please go back and try again.';
    exit;
  }

//create new campaign
  $query = mysqli_query($con, "INSERT INTO campaigns (creator, name) VALUES ('".$username."', '".$campaignname."')");
  if ($query) {
    echo 'Campaign created successfully!';
    header( "refresh:2;url=../index.php" );
  } else {
    echo 'There was an unknown error in creating the campaign - Please go back and try again.';
  }

?>

P.S. - Yes, campaignid is a row in the table, and does have data in it.

A: You need to echo a close select tag. Just add this line after your loop and you'll be fine
echo '</select>';

Also try changing the first line of your loop to this:
while ($row = mysqli_fetch_array($con, $query)) {

A: First, your <select> HTML tag is never closed with a </select>.
Second, the $con variable is not usable from within the changeCampaign function scope.  Add global $con; to the beginning of the function to fix it.
Additionally, I prefer to jump in and out of PHP blocks with this kind of stuff.  Consider this code:
<?php
//include db connect
include ("db_con.php");

//campaign change form function
    function changeCampaign() {
    global $con; // we need the connection data in here.
    //set variables
    $query = mysqli_query($con,"SELECT * FROM campaigns");
?>

    <form action="functions/campaign_change.php" name="campaignChange" method="post">

            <select name="campaignList">';
<?php
                    //loop that is NOT displaying the name
                    while ($row = mysqli_fetch_array($query)) {
                        echo "<option value='" . $row['campaignid'] . "'>" . $row['name'] . "</option>";
                    }
?>
            </select>

            <input type="submit" value="Load" />

        </form>

';
<?php
}
?>

In this, you have HTML code that is outputted just as if it had been echoed, but it is much nicer.


text:
Q: cache policy not working with php webservice IOS SDK i was using third party api for json response and i was also using cachePolicy:NSURLRequestReturnCacheDataElseLoad for fast response, but now we have developed our own api but now cachePolicy:NSURLRequestReturnCacheDataElseLoad not working, i mean it is not caching the data
NSString *urlAsString = @"api url";

NSString* webStringURL = [urlAsString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSURL* url = [NSURL URLWithString:webStringURL];

NSURLRequest *urlRequest =
[NSURLRequest
 requestWithURL:url
 cachePolicy:NSURLRequestReturnCacheDataElseLoad
 timeoutInterval:30.0f];

NSOperationQueue *queue = [[NSOperationQueue alloc] init];
[NSURLConnection
 sendAsynchronousRequest:urlRequest
 queue:queue
 completionHandler:^(NSURLResponse *response,
                     NSData *data,
                     NSError *error) {
     if ([data length] >0 && error == nil){

         NSMutableArray *arrayResponse=[NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:&error];

        [self prepareData:arrayResponse];

     }
     else if ([data length] == 0 && error == nil){
         dispatch_async(dispatch_get_main_queue(), ^{
             UIAlertView *alert=[[UIAlertView alloc]initWithTitle:nil message:@"The server is not responding \n please check your internet connection" delegate:nil cancelButtonTitle:nil otherButtonTitles:@"OK", nil];
             [alert show];
             alert=nil;
         });
         NSLog(@"Nothing was downloaded.");
     }
     else if (error != nil){

         dispatch_async(dispatch_get_main_queue(), ^{
             UIAlertView *alert=[[UIAlertView alloc]initWithTitle:nil message:@"The server is not responding \n please check your internet connection" delegate:nil cancelButtonTitle:nil otherButtonTitles:@"OK", nil];
             [alert show];
             alert=nil;
         });
         NSLog(@"Error happened = %@", error);
     }
 }];