text:
Q: python - list to pandas dataframe I have list of strings.
Each string is a sentence with comma delimiter.
RMCs = [
        '$GPRMC,222112.184,A,3713.681121,N,12205.707716,W,2.580,44.9,181018,,,A,V*33',
        '$GPRMC,222113.150,A,3713.804392,N,12205.729394,W,1.435,64.5,181018,,,A,V*32',
        '$GPRMC,222114.153,A,3713.833715,N,12205.736514,W,0.180,323.4,181018,,,A,V*02',
        '$GPRMC,222115.157,A,3713.834953,N,12205.735842,W,0.374,8.8,181018,,,A,V*0E',
        '$GPRMC,222116.163,A,3713.834541,N,12205.733602,W,0.240,346.6,181018,,,A,V*08',
        '$GPRMC,222117.163,A,3713.833123,N,12205.734873,W,0.664,238.3,181018,,,A,V*0E',
        '$GPRMC,222118.166,A,3713.833402,N,12205.733397,W,0.242,308.0,181018,,,A,V*05'
       ]

I want to split each line by the comma and place them into Pandas dataframe.
the expected output should be like the table below:
1  $GPRMC  222112.184  A  3713.681121  N  12205.707716  W  2.580  44.9  181018  NaN  NaN  A  V*33
2  $GPRMC  222113.150  A  3713.804392  N  12205.729394  W  1.435  64.5  181018  NaN  NaN  A  V*32
3  $GPRMC  222114.153  A  3713.833715  N  12205.736514  W  0.180 323.4  181018  NaN  NaN  A  V*02'
.
.
n  $GPRMC  ................................................................

** I can add headers if needed.
Tried in so many ways but could find the most efficient and clean way.
Please assist.

A: Use DataFrame constructor with list comprehension and split:
df = pd.DataFrame([x.split(',') for x in RMCs])
print (df)

       0           1  2            3  4             5  6      7      8   \
0  $GPRMC  222112.184  A  3713.681121  N  12205.707716  W  2.580   44.9
1  $GPRMC  222113.150  A  3713.804392  N  12205.729394  W  1.435   64.5
2  $GPRMC  222114.153  A  3713.833715  N  12205.736514  W  0.180  323.4
3  $GPRMC  222115.157  A  3713.834953  N  12205.735842  W  0.374    8.8
4  $GPRMC  222116.163  A  3713.834541  N  12205.733602  W  0.240  346.6
5  $GPRMC  222117.163  A  3713.833123  N  12205.734873  W  0.664  238.3
6  $GPRMC  222118.166  A  3713.833402  N  12205.733397  W  0.242  308.0

       9  10 11 12    13
0  181018        A  V*33
1  181018        A  V*32
2  181018        A  V*02
3  181018        A  V*0E
4  181018        A  V*08
5  181018        A  V*0E
6  181018        A  V*05

If want also replace empty strings:
df = pd.DataFrame([[i if i != '' else np.nan for i in x.split(',')] for x in RMCs])

print (df)

       0           1  2            3  4             5  6      7      8   \
0  $GPRMC  222112.184  A  3713.681121  N  12205.707716  W  2.580   44.9
1  $GPRMC  222113.150  A  3713.804392  N  12205.729394  W  1.435   64.5
2  $GPRMC  222114.153  A  3713.833715  N  12205.736514  W  0.180  323.4
3  $GPRMC  222115.157  A  3713.834953  N  12205.735842  W  0.374    8.8
4  $GPRMC  222116.163  A  3713.834541  N  12205.733602  W  0.240  346.6
5  $GPRMC  222117.163  A  3713.833123  N  12205.734873  W  0.664  238.3
6  $GPRMC  222118.166  A  3713.833402  N  12205.733397  W  0.242  308.0

       9   10  11 12    13
0  181018 NaN NaN  A  V*33
1  181018 NaN NaN  A  V*32
2  181018 NaN NaN  A  V*02
3  181018 NaN NaN  A  V*0E
4  181018 NaN NaN  A  V*08
5  181018 NaN NaN  A  V*0E
6  181018 NaN NaN  A  V*05


text:
Q: Error in android-phonegap while reading file When i write file, File created successfully, but next time when i read same file and move to other html file (using location.href='filename.html') it show following error:
JSCallback Error: Request failed.
Additional Detail:
I have created one function to check files are present in sdcard or not . If file is present in sdcard then it reads the content of file and navigate to html file in read method of phoneGap else it creates new file, write data in that file using phonegap write method and navigate to html.
In read method when i navigate to that html file and again call function to check file exists or not on onload event it call
"document.addEventListener("deviceready", onDeviceReady, false);" only never go ahead and
"JSCallback Error: Request failed." this error is display on log.

A: My guess is this is an issue asynchronous function call. The js calls to phonegap apis are asyncchronous and you need to wait till your callback gets called to open the file

redpajama_set_name: RedPajamaStackExchange


text:
Q: Should I use minipages to re-create this document in LaTeX? I would like to re-create this document in LaTeX and I was wondering how to proceed. Should I create two minipages, one for the left (45%) and the other for the right (45%)? 10% spacing between them, then create smaller minipages for the word examples?

I tried something like this:

Also, those titles "Rule1", "Rule2", and so on should be in hbox?
Any suggestion is appreciated.


text:
Q: Time Complexity - Reducing Square Matrix to Diagonal Matrix (using Gaussian Row Elimination) Given: A Square Matrix where each entry is an integer (either positive or negative). The magnitude of each integer entry is at most $m$ bits. The size of the Square matrix is $n \times n$.
Objective: Reduce the Square Matrix to a Diagonal Matrix form using Gaussian Row Elimination.
Query: What is the most efficient algorithm and its time complexity for the above?
Comment: Most sources discuss the number of operations but not the total computational complexity. The obvious method is to use the text book method of row elimination. But I am assuming in the worst case, it is possible for the intermediate matrix entries to blow up exponentially in their size (w.r.t. $m$). Thus, I am not clear.
Can someone help with the most efficient algorithm to achieve the above and its time complexity? (a clear reference to a textbook/source where that algorithm as well as its complexity is derived would be equally great).
P.S. I was suggested this link Link but it is not very clear (either Algorithm or its complexity)

A: I'm not sure if you achieve any better time complexity for the entries being integers like you state. You can find a description of this in the following books. Note that Gaussian Elimination doesn't do what you say.

*

*Numerical Linear Algebra -Trefethan and Bau

*Applied Numerical Linear Algebra - Demmel

*Matrix Computations - Golub

There are more efficient methods that are built upon using block matrices and randomized matrices however the following method is Gaussian Elimination or the LU Decomposition. Given
$$ A \in \mathbb{C}^{m \times m} $$
The elimination process is equivalent to the following
$$L_{m-1}\cdots L_{2}L_{1}A = U $$
Here we set
$$ L = L_{1}^{-1}L_{2}^{-1}\cdots L_{m-1}^{-1} \implies A= LU $$
This yields the following algorithm.

with an operation count of $$ \approx \frac{2}{3}m^{3} \textrm{flops} $$
If you are attempting to say diagonalization for eigenvalues. It is possible to use the Cholesky decomposition to perform the eigendecomposition. In which case the flop count would be if you had structure. But you're just going about this all wrong.


text:
Q: Date Calculating Can u give me a simple function in vb.net which can take number of days and date as parameters and subtract these number of days from given date.
Forexample
Private function Calculate(Byval p_number_days,p_date) as date

 Dim calculated_date as Date= (p_date) - (p_number_days)
 return calculated

End Function

A: Private Function Calculate(ByVal p_Number_Days As Integer, ByVal p_Date As DateTime) As DateTime
    Return p_Date.AddDays(p_Number_Days * -1)
End Function

A: Just use the AddDays() method of the DateTime class - MSDN
It can take a negative value as well as positive.

A: You'll have to excuse me, I haven't used VB in a long time, so some syntax might be wrong.
Private Function Calculate(p_days AS Integer, p_date AS Date) AS Date
  Return p_date - TimeSpan.FromDays(p_days)
End Function

A: If you can, always represent number of days as a TimeSpan. It makes the code look much nicer.
Private function Calculate(Byval p_number_days as TimeSpan,p_date as Date) as date
    Return p_date - p_number_days


text:
Q: Dynamically adding RecyclerViews to a LinearLayout does not increase the height I am trying to add many RecyclerViews dynamically to a LinearLayout depending upon the x coordinate of a 2-D array (Set). All the children of each view are not visible (it appears on scrolling the view).
In short, making the RecyclerView's height to WRAP_CONTENT is not stretching the height of RecyclerView.
I want all the children of all the RecyclerViews to be visible and not let any RecyclerView to be scrollable.
Following is the table_layout which I add dynamically:
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Engine"
        android:padding="6dp"
        android:gravity="center"
        android:id="@+id/tv_label"
        android:layout_marginTop="16dp"
        android:background="@color/light_gray"
        android:textSize="@dimen/bid_report_label_text_size"
        android:textColor="@color/white"
        android:textStyle="bold"/>

    <android.support.v7.widget.RecyclerView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/recycler_view"/>

</LinearLayout>

Following is the activity_main layout of activity:
<RelativeLayout
    android:layout_height="match_parent"
    android:layout_width="match_parent"
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools">

    <ScrollView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_above="@+id/button_bid_now"
        android:id="@+id/scrollView">

        <LinearLayout
            android:orientation="vertical"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:id="@+id/linear_layout_content">

            <ImageView
                android:layout_width="match_parent"
                android:layout_height="210dp"
                android:id="@+id/bike_image"
                android:onClick="startImageSlideshow"/>

            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:id="@+id/linear_layout_details"
                android:orientation="vertical"/>
        </LinearLayout>
    </ScrollView>
</RelativeLayout>

I add table_layout to activity_main dynamically.
Please tell me how to make the RecyclerView WRAP_CONTENT?

A: The problem was with ScrollView. Changing it to NestedScrollView solved the problem.


text:
Q: How do I download a PDF with flask I am trying to generate a pdf file download with flask, this is my code:
@app.route('/return-files/')
def return_files_tut():
    from flask import send_file
    with open(os.path.join(app.config['FACTURAS_FOLDER'],'Transferencia_a_otras_cuentas_1.pdf'), 'rb') as static_file:
        return send_file(static_file, attachment_filename='file.pdf')

But I have the following drawback
[2021-06-21 23:34:44 +0000] [12] [ERROR] Error handling request /return-files/
plan-management       | Traceback (most recent call last):
plan-management       |   File "/usr/local/lib/python3.9/site-packages/gunicorn/workers/sync.py", line 136, in handle
plan-management       |     self.handle_request(listener, req, client, addr)
plan-management       |   File "/usr/local/lib/python3.9/site-packages/gunicorn/workers/sync.py", line 182, in handle_request
plan-management       |     resp.write_file(respiter)
plan-management       |   File "/usr/local/lib/python3.9/site-packages/gunicorn/http/wsgi.py", line 385, in write_file
plan-management       |     if not self.sendfile(respiter):
plan-management       |   File "/usr/local/lib/python3.9/site-packages/gunicorn/http/wsgi.py", line 355, in sendfile
plan-management       |     if not util.has_fileno(respiter.filelike):
plan-management       |   File "/usr/local/lib/python3.9/site-packages/gunicorn/util.py", line 574, in has_fileno
plan-management       |     obj.fileno()
plan-management       | ValueError: I/O operation on closed file

A: No need to actually open the file, you can just send the file itself directly...
Note that this code is untested but it should work™
Also, I would not put the import inside the function itself as it will import each time the function is executed.
from flask import send_file

@app.route('/return-files/')
def return_files_tut():
    filename = os.path.join(app.config['FACTURAS_FOLDER'],'Transferencia_a_otras_cuentas_1.pdf')
    return send_file(filename, attachment_filename='file.pdf', as_attachment=True)


text:
Q: Why won't an iframe load in a Lightning component if it extends another Lightning component? I am building a Lightning component that loads an iframe of an internal app. I've brought the component down to its minimum valuable component and I still have the problem.
The component with the iframe:
<aura:component
        implements="flexipage:availableForAllPageTypes"
        extends="c:SimpleBase"
        description="SimpleIframeComponent">

    <iframe src="https://example.com/"
            width="100%"
            height="500px"
            frameBorder="0" />

</aura:component>

The base component:
<aura:component description="SimpleBase" extensible="true" abstract="true">
</aura:component>

So long as I do not extend SimpleBase, the iframe loads. But if I do extend SimpleBase, the iframe won't load.
There are no errors in the developer log (console). Also, watching the network in developer tools, the URL doesn't even load, so it appears the component doesn't render at all when it extends the base component.
Why won't an iframe load in a Lightning component if it extends another Lightning component?

A: You need to use {!v.body} in super component SimpleBase without which the body of sub-component will not load.
Reason: (REFERENCE)

sub component's body is evaluated and passed to a super component to
  use as {!v.body} and that super component's body is evaluated and is
  passed to its super component,


text:
Q: Do monad transformers apply to getting JSON from services? I have a Play! 2 for Scala application that needs to retrieve some data in JSON format from an external service.
The Play! framework allows to make HTTP requests asynchronously by wrapping the response in a Promise. Promise is a monad that wraps a value that will be available in the future.
This is fine, but in my case what I get from the web service is a JSON string. I have to parse it and the parsing might fail. So I have to wrap whatever I get into an Option. The result is that many of my methods are returning Promise[Option[Whatever]]. That is, a value of type Whatever that will be, maybe, available later.
Now whenever I have to operate over such a value I need to map it twice. I was thinking of handling this in the following way:

*

*creating a new type, say Hope[A], that wraps a Promise[Option[A]]

*defining the relevant methods like map (or maybe I should use foreach and inherit from some collection trait?) and flatten

*provide an implicit converter between Promise[Option[A]] and Hope[A].

It is easy to define map - the composition of two functors is again a functor - and flatten can be done explicitly in this case, or whenever composing a monad with Option.
But it is my limited understanding that I do not need to reinvent this stuff: monad transformer exist for exactly this case. Or, well, so I think - I have never used a monad tranformer - and this is the point of the question:

Can monad tranformers be used in this situation? How would I go about actually using them?

A: Using the Scalaz library's OptionT transformer, you should be able to turn values of type Promise[Option[A]] into values of type OptionT[Promise, A].
Using Scalaz 7:
import scalaz.OptionT._
val x: OptionT[Promise, Int] = optionT(Promise.pure(Some(123)))

To use this value, for example to call map or flatMap on it, you will need to provide an appropriate typeclass for Promise (Functor for map, Monad for flatMap).
Since Promise is monadic, it should be possible to provide an instance of Monad[Promise]. (You'll get Functor and Applicative for free, because the typeclasses form an inheritance hierarchy.)  For example (note: I've not tested this!):
implicit val promiseMonad = new Monad[Promise] {
  def point[A](a: => A): Promise[A] = Promise.pure(a)
  def bind[A, B](fa: Promise[A])(f: A => Promise[B]): Promise[B] = fa flatMap f
}

As a simple example, you can now use map on the OptionT[Promise, A], to apply a function of type A => B to the value inside:
def foo[A, B](x: OptionT[Promise, A], f: A => B): OptionT[Promise, B] = x map f

To retrieve the underlying Promise[Option[A]] value from an OptionT[Promise, A], call the run method.
def bar[A, B](x: Promise[Option[A]], f: A => B): Promise[Option[B]] =
  optionT(x).map(f).run

You will gain more benefit from using monad transformers when you can compose several operations of compatible types, preserving the OptionT[Promise, _] type between operations and retrieving the underlying value at the end.
To compose operations in a for-comprehension, you will need functions of type A => OptionT[Promise, B].

A: -- removed --
edit:
Okay, you can simply use the scalaz.OptionT here:
val x = optionT(Promise { /* api call */ some("""{ "foo": "bar" }""") })
val mapped = x.map(Json.parse).run // run return the resulting Promise[Option[T]]


text:
Q: How do you convert a system of symbolic sympy ODEs to matrix form? I am trying to (ultimately) simulate an inverted pendulum having a PID controller.
I am employing the Euler-Lagrange method to derive the equations of motion using SymPy.
I can compute the Euler-Lagrange equations in SymPy just fine.
Now that I have my symbolic differential equations, I would like to write them in matrix form.
It can be done by hand, but I would like to know if SymPy can separate the 2nd time-derivates out, put them in a vector, and put the rest into a matrix.
Here is the code I have so far:
#Import Libraries
import math
import numpy as np
import vpython as vp
import sympy as sp
from sympy import *
from numpy import *
from scipy.integrate import odeint
import matplotlib.pyplot as plt

#Allow display of symbols
sp.init_printing()

#Set up symbolic equations

####Symbolic Variables####
m1, m2 = sp.symbols('m1 m2') #masses of rad & cart
l = sp.symbols('l') #Length of rod
J = sp.symbols('J') #Rotational moment of inertia
t, g, F, b = sp.symbols('t g F b') #Gravitational acceleration, time, forces
z, theta1 = sp.symbols('z, theta1', cls = sp.Function)
x, y =sp.symbols('x y')

#Rotational Inertia
J = (m1*(l/2)**2)/12

####Time Derivatives####
theta1 = theta1(t)
z = z(t)
z_d = sp.diff(z, t)
theta1_d = sp.diff(theta1, t)
z_dd = sp.diff(z_d, t)
theta1_dd = sp.diff(theta1_d, t)

####Coordinates of component centers of mass####
x1 = l/2*sp.sin(theta1) + z
y1 = l/2*sp.cos(theta1)
x2 = z
y2 = 0
v1_sq = sp.diff(x1,t)**2 + sp.diff(y1,t)**2
v1 = sp.sqrt(v1_sq)
v2 = sp.diff(x2,t)

#Kinetic Energy
K1 = (1/2)*m1*(v1**2) + (1/2)*J*(sp.diff(theta1,t)**2)
K2 = (1/2)*m2*(sp.diff(z,t)**2)
K = K1 + K2

#Potential Energy
P = m1*g*l/2*sp.cos(theta1)

#Lagrangian
L = K - P

#Compute the Euler Lagrange Equation

#Compute dL/dq
dL_dz = sp.diff(L, z).simplify()
dL_dtheta1 = sp.diff(L, theta1).simplify()

#Compute dL/dq_dt
dL_dz_dt = sp.diff(L, z_d).simplify()
dL_dtheta1_dt = sp.diff(L, theta1_d).simplify()

#Compute d/dt(dL/dq_dt)
d_dt_dL_dz_dt = sp.diff(dL_dz_dt, t).simplify()
d_dt_dL_dtheta1_dt = sp.diff(dL_dtheta1_dt, t).simplify()

#Compute d/dt(dL/dq_dt) - dL/dq
LE1 = d_dt_dL_dz_dt.simplify() - dL_dz.simplify()
LE2 = d_dt_dL_dtheta1_dt.simplify() - dL_dtheta1.simplify()
LE = LE1 + LE2

I have tried using sympy.linear_eq_to_matrix(equations, *symbols), but the 'symbols' portion is a differentiated variable in my case, causing SymPy to issue this error:
ValueError                                Traceback (most recent call last)
<ipython-input-8-eab6a82bce2c> in <module>
     88
     89 b = sp.linsolve([LE1, LE2], (z_dd, theta1_dd))
---> 90 sp.linear_eq_to_matrix([LE1, LE2], *[z_dd, theta1_dd])

~\Anaconda3\lib\site-packages\sympy\solvers\solveset.py in linear_eq_to_matrix(equations, *symbols)
   2555     for i in symbols:
   2556         if not isinstance(i, Symbol):
-> 2557             raise ValueError(filldedent('''
   2558             Expecting a Symbol but got %s
   2559             ''' % i))

ValueError:
Expecting a Symbol but got Derivative(theta1(t), (t, 2))

Any help would be appreciated.
Thanks.


text:
Q: Custom class in layouts on JetpackCompose I've read the documentation on how to compose basic Layouts . I wonder if a class can be implemented in order to create these views. EG from Android
@Composable
fun ArtistCard(artist: Artist) {
    Row(
        verticalAlignment = Alignment.CenterVertically,
        horizontalArrangement = Arrangement.End
    ) {
        Image(/*...*/)
        Column { /*...*/ }
    }
}

That produces some kind of CardView, but can that be converted in a class that I can just provide the image and title? In order to create a mutable list or I'm missing something else that exists?
I have no code about the class mentioned since I don't know how to start in this case with Jetpack components.


text:
Q: Devise unconfirmed_email when trying to click on confirm account from received email Here's my user model:
class User < ActiveRecord::Base
  devise :database_authenticatable, :registerable,
        :recoverable, :rememberable, :trackable, :validatable,:confirmable

  # Setup accessible (or protected) attributes for your model
  attr_accessible :email, :password, :password_confirmation, :remember_me

end

Here's the schema.rb:
 create_table "users", :force => true do |t|
      t.string   "email",                  :default => "", :null => false
      t.string   "encrypted_password",     :default => "", :null => false
      t.string   "reset_password_token"
      t.datetime "reset_password_sent_at"
      t.datetime "remember_created_at"
      t.integer  "sign_in_count",          :default => 0
      t.datetime "current_sign_in_at"
      t.datetime "last_sign_in_at"
      t.string   "current_sign_in_ip"
      t.string   "last_sign_in_ip"
      t.string   "confirmation_token"
      t.datetime "confirmed_at"
      t.datetime "confirmation_sent_at"
      t.datetime "created_at",                             :null => false
      t.datetime "updated_at",                             :null => false
      t.integer  "profile_id"
      t.string   "profile_type"
end

And in my initializer, devise.rb, I set this:
config.reconfirmable = false

I receive a mail telling me to click on confirm my account, and when I do, I get this error:
NameError in Devise::ConfirmationsController#show

undefined local variable or method `unconfirmed_email' for #<User:0xaa53818>

How can I fix it?

A: It was not a problem with Devise, but with me not restarting the development server.


text:
Q: Is D-glottalization a plausible explanation of ambiguity in Donald Trump interview with WSJ? On Jan 11, The Wall Street Journal published an interview with President Trump that contained the following phrase:

With that being said, President Xi has been extremely generous with what he's said, I like him a lot. I have a great relationship with him, as you know I have a great relationship with Prime Minister Abe of Japan and I probably have a very good relationship with Kim Jong Un of North Korea.
I have relationships with people, I think you people are surprised.

The White House subsequently denied this statement, claiming that the President rather said (emphasis mine):

I'd probably have a very good relationship with Kim Jong Un of North Korea

WSJ responded by publishing audio recording that, in their opinion, supports their original transcript. This has been considered adequate evidence by many commentators, for example Newsweek. I, however, beg to differ.
Having listened to the recording carefully, it seems to me that Trump's I was followed by a glottal stop. Why is this important? T-glottalization commonly occurs in American English and I thought Trump could show similar yet less exhibited D-glottalization, which would perfectly resolve the whole controversy.
However, my brief research shows that this sound change is rarely mentioned by phonologists, and attributed mostly to African American speakers, such as this study from Houston area.
Not having reached a conclusion myself, my questions are:

*

*Am I correct transcribing Trump's words as [ʌɪʔ ˈprɒbəbli]?

*Is D-glottalization a thing for a New York white speaker, i.e. would he pronounce I'd as [ʌɪʔ]?

A: To my ears, 45 says "I'd probably..." with an unaspirated d, hardly surprising before another stop in casual, hurried speech that elides most everything. The word would that hangs in the air following this sentence reinforces the conclusion that he said I'd rather than I.

A: I'm going to show the acoustic signals that are on the tape. It's hard to be certain on this one because the normal cues that you'd look for are just very faint or hard to distinguish. I'd be surprised if a linguist comments decisively for the media about what the tape shows going strictly by the physical audio (they might infer using other techniques).
tl;dr you can't tell unless you're able to squint better than me. I can't see glottalization, but it wouldn't be expected anyways (it's normally a cue for coda [t], not [d]).
Below you'll see a spectrogram. This is gotten with the software Praat. I extracted the left channel and had Praat display a spectrogram using a window length of 5 ms and a dynamic range of 35.0 dB.
First, what are you seeing? The spectrogram shows acoustic energy by frequency, with darker spots corresponding to more energy. Between 15.696s and 15.877s is the phrase "and I" or "and I'd". Before that you'll see high frequency noise (sounds like a click or sucking sound). After that you see about 90 ms of silence, followed by the release of the p (noise in the range of the first four vocal formants).
There are three types of cues you can look at (maybe more).

*

*Formant transitions

*Presence/absence of glotallisation

*Stop closure duration

First, formant transitions. Focus on the syllable between 15.794s and 15.877s. You'll see two regions of periodic sound (regular pulses of energy) between around 400--800 Hz and 1400--1800 Hz. These are the first two formants (F1 and F2), and they are determined by the the shape of the oral cavity (created by jaw position and tongue shape). Comparing [a] and [i], F1 should be higher for [a], and F2 should be higher for [i]. So in the diphthong [ai], you are going to see F1 and F2 start out close, then F1 drops while F2 rises. Consonants also affect the shapes of the formants. In the Trump "big league" affair, it was clear that he was saying "big league" because velar consonants like [k] and [g] cause F2 and F3 to "pinch" together. Anyways, a labial consonant like [p] should cause all formants to drop. An alveolar consonant like [d] should cause F1 to drop, and F2 to become more central (close to where it would be for [a] or schwa). Since right before the disputed consonant (is he saying [dp] or [p]?) is [i], which is front and has a high F2, you would expect to see a drop in both F1 and F2 regardless of whether it was [d] or [p]. So I can't draw anything from formant transitions.
As for glottalization. That comes before [t] specifically, not [d] (in fact it makes [t] and [d] easier to tell apart). So we shouldn't expect glottalization. The longer pulse periods starting at 15.696s might be glottalization (he had paused). You don't see the pulses getting irregular as the contested consonant closure is formed, but you wouldn't expect them.
As for closure duration, 90 ms seems a bit long for a stop closure for someone who's speaking fast, so that'd be an argument in favor of [dp], but then again he might have paused for an instant to think what to say next, since he was speaking extemporaneously.

A:
Am I correct transcribing Trump's words as [ʌɪʔ ˈprɒbəbli]?

More like [aɪd̚ prɑbəbli] , with an /aɪ/ diphthong, an /ɑ/ sound, and an unreleased d (see below)

Is D-glottalization a thing for a New York white speaker, i.e. would
  he pronounce I'd as [ʌɪʔ]?

My personal opinion is that linguists are wrong calling this sound a "glottal stop". it's an unreleased D, or simply "an unreleased X".
what can I do? -> [wət̚ kn ai du]
I had this -> [ai həd̚ ðɪs]
shop -> [ʃɑp̚]
Basically, one starts pronouncing the consonant, but stops in the stage when the air is shot from one's mouth. in the T or D case, one puts his tongue where the T/D are made (the alveolar ridge), then continues saying the next consonant, or simply stops there.
It happens in most, if not all, the North American accents, for all the stop consonants (/t/, /d/, /k/, /g/, /p/, /b/) before another consonant or at the end of the sentence.

A: Overview
I'm going to try a little experiment here. I ask for the forbearance of my colleagues on EL&U. I want to share some data, but I do not have the expertise to interpret the data. So I want to make the data available in a Community Wiki answer so experts can weigh in on the data and perhaps draw some meaningful conclusions. You can vote up or down, but please consider holding off on delete votes for a day or two.
If you have any expertise in audio analysis, phonetics, phonology, or reading spectrograms, please feel free to edit this answer to include your interpretation.  To avoid the risk of speculation or bald opining, please support your analysis with as much empirical evidence and authoritative references as you are able.
Media
The audio the WSJ have made available of their interview with President Trump can be downloaded and analyzed in audio analysis tools.
The downloaded video can be accessed here, as well as just the audio track in either .m4a format or converted to .wav format.
Waveforms and Spectrograms
These are screenshots of waveforms (above) and spectrograms (below) of the four times Donald Trump said "I have ... relationship" with various people in his interview with the WSJ. The screenshots were taken in a software application called Sonic Visualizer.
The start and end times are approximate for each utterance of "I have", and the scaling/zooming is likely inconsistent, as it was done manually with no real experience in the software. But they'll give you a broad idea of where to start for your own analysis.
The bolded parts of the text indicate approximately what words are represented in the corresponding screenshot. The sections were calibrated manually.
1. President Xi
Around 6 seconds in, President Trump says:

... President Xi ... I have a great relationship with him ...

Sonic Visualizer session for this quote.
2. Prime Minister Abe
Around 10s in, President Trump says:

... As you know I have a great relationship with Prime Minister Abe ...

Sonic Visualizer session for this quote.
3. Kim Jong Un
Around 16s in, President Trump says (this is the disputed quotation):

... and I['d?] probably have a very good relationship with Kim Jong Un ...

Sonic Visualizer session for this quote.
4. Other people
Around 25s in, President Trump says:

... I have relationships with people ...

Sonic Visualizer session for this quote.
Interpretation, comparison, and contrast
Conclusions


text:
Q: Customizing Bootstrap CSS template I am just getting started with Bootstrap from Twitter and am wondering what the 'best practices' is for customization. I want to develop a system that will take advantage of all the power of a css template (Bootstrap or other), be completely (and easily) modifiable, be sustainable (ie – when the next version of Bootstrap is released from Twitter I don't have to start over.
For example, I want to add background images to the top navigation. It looks like there are 3 ways to go about this:

*

*Modify the .topbar classes in bootstrap.css . I don't particularly like this because I will have lots of .topbar items and I don't necessarily want to modify them all the same way.

*Create new classes with my background images and apply both styles (the new and the bootstrap to my element). This may create style conflicts, which could be avoided by stripping the .topbar class into separate classes and then only using the pieces that are not stepped on by my custom class. Again this requires more work than I think should be necessary and while it is flexible, it won't allow me to easily update bootstrap.css when Twitter releases the next installment.

*Use variables in .LESS to achieve the customization. Offhand this seems like a good approach but having not used .LESS I have concerns about compiling css on the client and about code sustainability.

Though I am using Bootstrap, this question can be generalized to any css template.

A: You can use the bootstrap template from
http://www.initializr.com/
which includes all the bootstrap .less files. You can then change variables / update the less files as you want and it will automatically compile the css. When deploying compile the less file to css.

A: Bootstrap 5 (update 2021)
As explained in the Bootstrap docs, modifying the existing "theme" colors is done using SASS. As with prior versions, you can also override the Bootstrap CSS by adding CSS rules that follow after the bootstrap.css and use the correct CSS specificity.
Bootstrap 5 - change theme colors
Bootstrap 4
I'm revisiting this Bootstrap customization question for 4.x, which now utilizes SASS instead of LESS. In general, there are 2 ways to customize Bootstrap...
1. Simple CSS Overrides
One way to customize is simply using CSS to override Bootstrap CSS. For maintainability, CSS customizations are put in a separate custom.css file, so that the bootstrap.css remains unmodified. The reference to the custom.css follows after the bootstrap.css for the overrides to work...
<link rel="stylesheet" type="text/css" href="css/bootstrap.min.css">
<link rel="stylesheet" type="text/css" href="css/custom.css">

Just add whatever changes are needed in the custom CSS. For example...
    /* remove rounding from cards, buttons and inputs */
    .card, .btn, .form-control {
        border-radius: 0;
    }

Before (bootstrap.css)

After (with custom.css)

When making customizations, you should understand CSS Specificity. Overrides in the custom.css need to use selectors that are the same specificity as (or more specific) the bootstrap.css.

Note there is no need to use !important in the custom CSS, unless
you're overriding one of the Bootstrap Utility
classes. CSS
specificity
always works for one CSS class to override another.

2. Customize using SASS
If you're familiar with SASS (and you should be to use this method), you can customize Bootstrap with your own custom.scss. There is a section in the Bootstrap docs that explains this, however the docs don't explain how to utilize existing variables in your custom.scss. For example, let's change the body background-color to #eeeeee, and change/override the blue primary contextual  color to Bootstrap's $purple variable...
/* custom.scss */

/* import the necessary Bootstrap files */
@import "bootstrap/functions";
@import "bootstrap/variables";

/* -------begin customization-------- */

/* simply assign the value */
$body-bg: #eeeeee;

/* use a variable to override primary */
$theme-colors: (
  primary: $purple
);
/* -------end customization-------- */

/* finally, import Bootstrap to set the changes! */
@import "bootstrap";

This also works to create new custom classes. For example, here I add purple to the theme colors which creates all the CSS for btn-purple, text-purple, bg-purple, alert-purple, etc...
/* add a new purple custom color */
$theme-colors: (
  purple: $purple
);

https://codeply.com/go/7XonykXFvP
With SASS you must @import bootstrap after the customizations to make them work! Once the SASS is compiled to CSS (this must be done using a SASS compiler node-sass, gulp-sass, npm webpack, etc..), the resulting CSS is the customized Bootstrap. If you're not familiar with SASS, you can customize Bootstrap using a tool like this theme builder I created.
Custom Bootstrap Demo (SASS)
Note: Unlike 3.x, Bootstrap 4.x doesn't offer an official customizer tool. You can however, download the grid only CSS or use another 4.x custom build tool to re-build the Bootstrap 4 CSS as desired.

Related:
How to extend/modify (customize) Bootstrap 4 with SASS
How to change the bootstrap primary color?
How to create new set of color styles in Bootstrap 4 with sass
How to Customize Bootstrap

A: The best option in my opinion is to compile a custom LESS file including bootstrap.less, a custom variables.less file and your own rules :

*

*Clone bootstrap in your root folder : git clone https://github.com/twbs/bootstrap.git

*Rename it "bootstrap"

*Create a package.json file : https://gist.github.com/jide/8440609

*Create a Gruntfile.js : https://gist.github.com/jide/8440502

*Create a "less" folder

*Copy bootstrap/less/variables.less into the "less" folder

*Change the font path : @icon-font-path: "../bootstrap/fonts/";

*Create a custom style.less file in the "less" folder which imports bootstrap.less and your custom variables.less file : https://gist.github.com/jide/8440619

*Run npm install

*Run grunt watch
Now you can modify the variables any way you want, override bootstrap rules in your custom style.less file, and if some day you want to update bootstrap, you can replace the whole bootstrap folder !
EDIT: I created a Bootstrap boilerplate using this technique : https://github.com/jide/bootstrap-boilerplate

A: I recently wrote a post about how I've been doing it at Udacity for the last couple years. This method has meant we've been able to update Bootstrap whenever we wanted to without having merge conflicts, thrown out work, etc. etc.
The post goes more in depth with examples, but the basic idea is:

*

*Keep a pristine copy of bootstrap and overwrite it externally.

*Modify one file (bootstrap's variables.less) to include your own variables.

*Make your site file @include bootstrap.less and then your overrides.

This does mean using LESS, and compiling it down to CSS before shipping it to the client (client-side LESS if finicky, and I generally avoid it) but it is EXTREMELY good for maintainability/upgradability, and getting LESS compilation is really really easy. The linked github code has an example using grunt, but there are many ways to achieve this -- even GUIs if that's your thing.
Using this solution, your example problem would look like:

*

*Change the nav bar color with @navbar-inverse-bg in your variables.less (not bootstrap's)

*Add your own nav bar styles to your bootstrap_overrides.less, overwriting anything you need to as you go.

*Happiness.

When it comes time to upgrade your bootstrap, you just swap out the pristine bootstrap copy and everything will still work (if bootstrap makes breaking changes, you'll need to update your overrides, but you'd have to do that anyway)
Blog post with walk-through is here.
Code example on github is here.

A: I think the officially preferred way is now to use Less, and either dynamically override the bootstrap.css (using less.js), or recompile bootstrap.css (using Node or the Less compiler).
From the Bootstrap docs, here's how to override bootstrap.css styles dynamically:

Download the latest Less.js and include the path to it (and Bootstrap) in the <head>.
 <link rel="stylesheet/less" href="/path/to/bootstrap.less">
    <script src="/path/to/less.js"></script>

To recompile the .less files, just save them and reload your page. Less.js compiles them and stores them in local storage.

Or if you prefer to statically compile a new bootstrap.css with your custom styles (for production environments):

Install the LESS command line tool via Node and run the following command:
$ lessc ./less/bootstrap.less > bootstrap.css

A: The best thing to do is.
1. fork twitter-bootstrap from github and clone locally.
they are changing really quickly the library/framework (they diverge internally. Some prefer library, i'd say that it's a framework, because change your layout from the time you load it on your page). Well... forking/cloning will let you fetch the new upcoming versions easily.
2. Do not modify the bootstrap.css file
It's gonna complicate your life when you need to upgrade bootstrap (and you will need to do it).
3. Create your own css file and overwrite whenever you want original bootstrap stuff
if they set a topbar with, let's say, color: black; but you wan it white, create a new very specific selector for this topbar and use this rule on the specific topbar. For a table for example, it would be <table class="zebra-striped mycustomclass">. If you declare your css file after bootstrap.css, this will overwrite whatever you want to.

A: Since Pabluez's answer back in December, there is now a better way to customize Bootstrap.
Use: Bootswatch to generate your bootstrap.css
Bootswatch builds the normal Twitter Bootstrap from the latest version (whatever you install in the bootstrap directory), but also imports your customizations. This makes it easy to use the the latest version of Bootstrap, while maintaining custom CSS, without having to change anything about your HTML. You can simply sway boostrap.css files.

A: Use LESS with Bootstrap...
Here are the Bootstrap docs for how to use LESS
(they have moved since previous answers)

A: you can start with this tool, https://themestr.app/theme , seeing how it overwrites the scss variables, you would get an idea what variable impacts what. its the simplest way I think.
example scss genearation:
@import url(https://fonts.googleapis.com/css?family=Montserrat:200,300,400,700);
$font-family-base:Montserrat;
@import url(https://fonts.googleapis.com/css?family=Open+Sans:200,300,400,700);
$headings-font-family:Open Sans;

$enable-grid-classes:false;
$primary:#222222;
$secondary:#666666;
$success:#333333;
$danger:#434343;
$info:#515151;
$warning:#5f5f5f;
$light:#eceeec;
$dark:#111111;
@import "bootstrap";


text:
Q: PostSharp Caching MethodInterceptionAspect using ASP.NET Core in-memory cache public class CacheAttribute : MethodInterceptionAspect
{
    public override void OnInvoke(MethodInterceptionArgs methodInterceptionArgs)
    {
        if ((methodInterceptionArgs.Method.Name == CacheAspectAction.Get.ToString())
            //&& (Memory.Cache[cacheKey] != null)
            )
        {
        //    methodInterceptionArgs.ReturnValue = HttpRuntime.Cache[cacheKey];
            return;
        }

        object returnVal = methodInterceptionArgs.Invoke(methodInterceptionArgs.Arguments);

        ClanCache(cacheKeyBase, cacheKey);

        if (returnVal != null)
            //Memory.Cache.Insert(cacheKey, returnVal, null, expirationInformation.AbsoluteExpiration, expirationInformation.SlidingExpiration);

        methodInterceptionArgs.ReturnValue = returnVal;
    }
}

How do I access the in-memory cache in ASP.NET Core from any class, including a PostSharp aspect? For example, I need to access IMemoryCache in MethodInterceptionAspect and OnMethodBoundaryAspect.

A: I'm going to assume here that you're using the built-in ASP.NET Core dependency injection and IMemoryCache implementation. However, the example can be easily adapted to other implementations. And I'm going to choose the Global Service Locator approach for resolving dependencies in the aspect. Below is the modified example from the documentation page.
// A helper class that resolves services using built-in ASP.NET Core service provider.
public static class AspectServiceLocator
{
    private static IServiceProvider serviceProvider;

    public static void Initialize(IWebHost host)
    {
        serviceProvider = host.Services;
    }

    public static Lazy<T> GetService<T>() where T : class
    {
        return new Lazy<T>(GetServiceImpl<T>);
    }

    private static T GetServiceImpl<T>()
    {
        if (serviceProvider == null)
            throw new InvalidOperationException();

        return (T) serviceProvider.GetService(typeof(T));
    }
}

public class Program
{
    public static void Main(string[] args)
    {
        IWebHost host = CreateWebHostBuilder(args).Build();

        // Initialize the AspectServiceLocator during ASP.NET Core program start-up
        AspectServiceLocator.Initialize(host);

        host.Run();
    }

    public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
        WebHost.CreateDefaultBuilder(args)
            .UseStartup<Startup>();
}

[PSerializable]
public class CacheAttribute : MethodInterceptionAspect
{
    private static Lazy<IMemoryCache> cache;

    static CacheAttribute()
    {
        // Use AspectServiceLocator to initialize the cache service field at application run-time.
        if (!PostSharpEnvironment.IsPostSharpRunning)
        {
            cache = AspectServiceLocator.GetService<IMemoryCache>();
        }
    }

    public override void OnInvoke(MethodInterceptionArgs args)
    {
        object cacheKey = args.Method.Name;
        object cachedResult;

        if (cache.Value.TryGetValue(cacheKey, out cachedResult))
        {
            args.ReturnValue = cachedResult;
            return;
        }

        args.Proceed();

        cache.Value.Set(cacheKey, args.ReturnValue);
    }
}


text:
Q: apply rank() for a subset of data.table and whole table I have a data.table with numeric X and Y values. I need to mark records with top-5 and bottom-5 Y values from 3 groups: 1) all records, 2) records with X=0, 3) records with X=0.5. My current solution calculates rank() separately by adding corresponding columns to the table:
set.seed(1)
dt1 <- data.table(valueX=round(rnorm(1e6),2),
                  valueY=round(rnorm(1e6),2)) # I also have many other columns that I'll want to keep

dt1[,          all.top:=rank( valueY)]
dt1[,          all.btm:=rank(-valueY)]
dt1[valueX==0,  X0.top:=rank( valueY)]
dt1[valueX==0,  X0.btm:=rank(-valueY)]
dt1[valueX==.5, X5.top:=rank( valueY)]
dt1[valueX==.5, X5.btm:=rank(-valueY)]

dt1[, selected:=(all.top<6 | all.btm<6 |
                 X0.top <6 | X0.btm <6 |
                 X5.top <6 | X5.btm <6 )]

Is there some sort of one-liner that would skip creating intermediate columns?
UPD. Adding some benchmarking: solution with head()/tail() suggested by @chinsoon12 is much faster then using rank():
solution_ranks <- function(inpDT){
  inpDT[,          all.top:=rank( valueY)]
  inpDT[,          all.btm:=rank(-valueY)]
  inpDT[valueX==0,  X0.top:=rank( valueY)]
  inpDT[valueX==0,  X0.btm:=rank(-valueY)]
  inpDT[valueX==.5, X5.top:=rank( valueY)]
  inpDT[valueX==.5, X5.btm:=rank(-valueY)]

  inpDT[, selected:=(all.top<6 | all.btm<6 |
                       X0.top <6 | X0.btm <6 |
                       X5.top <6 | X5.btm <6 )]

  inpDT[,c('all.top','all.btm','X0.top','X0.btm','X5.top','X5.btm'):=NULL]

  return(inpDT)
}

solution_ht <- function(inpDT){
  ht <- function(x, n=5L) unique(c(head(x, n), tail(x, n)))
  inpDT[, rn := .I]
  inpDT[rn %in% inpDT[order(valueY),c(ht(rn),ht(rn[valueX==0]),ht(rn[valueX==0.5]))],
        selected:=TRUE]
  return(inpDT)
}

require(microbenchmark)
print(microbenchmark(
  solution_ranks(dt1),
  solution_ht(dt1),
  times=3L
), signif=3)
#
# Unit: milliseconds
#                expr  min   lq mean median   uq  max neval
# solution_ranks(dt1) 1050 1070 1080   1080 1090 1090     3
# solution_ht(dt1)     113  114  143    116  159  202     3

A: Here is a suggestion:
ht.avg <- function(DT, n=6L) {
    DT[, {
        rnk <- frank(Y)
        rn[rnk < n | (.N + 1L - rnk) < n]
    }]
}

DT[, rn := .I]
setorder(DT, Y)

cols <- c("rn", "X", "Y")
ans <- DT[rn %in% DT[, sort(unique(c(
        ht.avg(.SD), ht.avg(.SD[X==1L]), ht.avg(.SD[X==2L])
    ))), .SDcols=cols]]
setorder(ans, rn)[]

output:
    X   Y  rn
 1: 0   1   1
 2: 0   2   2
 3: 0   3   3
 4: 0   4   4
 5: 0   5   5
 6: 1  26  26
 7: 1  27  27
 8: 1  28  28
 9: 1  29  29
10: 1  30  30
11: 1  46  46
12: 1  47  47
13: 1  48  48
14: 1  49  49
15: 1  50  50
16: 2  51  51
17: 2  52  52
18: 2  53  53
19: 2  54  54
20: 2  55  55
21: 2  71  71
22: 2  72  72
23: 2  73  73
24: 2  74  74
25: 2  75  75
26: 3  96  96
27: 3  97  97
28: 3  98  98
29: 3  99  99
30: 3 100 100
    X   Y  rn

data:
nr <- 100L
DT <- data.table(X=rep(0L:3L, each=nr/4L), Y=1L:nr)


text:
Q: how to do keypress event in jpanel text field? when i select something in combobox :

it show joptionPane Dialog box wiht two inputs.

here i want to first focusing amount field and then, when i entered in amount field its goes to no of App field then enter go to OK .
Here is my code for JOption Dialog:
JTextField xField = new JTextField(5);
JTextField yField = new JTextField(5);
JPanel myPanel = new JPanel();
myPanel.add(new JLabel("Amount:"));
myPanel.add(xField);
myPanel.add(Box.createHorizontalStrut(15)); // a spacer
myPanel.add(new JLabel("No of App:"));
myPanel.add(yField);
int value = 0;
xField.requestFocus();
int result = JOptionPane.showConfirmDialog(null, myPanel, "Please Enter Amount and No.of app", JOptionPane.OK_CANCEL_OPTION);

A: You simply try to focus a component which is not layout in a window.
Replace
xField.requestFocus();

by
SwingUtilities.invokeLater(new Runnable() {
  public void run() {
    xField.requestFocusInWindow();
  }
});

A: You can create your own JDialog on the event that an item has changed to a new item. Then, you can get values entered in the JDialog and appropriately set the information in your parent. If you want to change the order of focus, use a custom focus policy. If you want to change the traversal focus key to the Enter key, you should re-map the key so that it reacts the same as the Tab key. There are several resources online and on this site with information on how to do that.
You should note that the default focus traversal policy is dependent on the order in which you add you elements to your content panel.
I have created a simple example for you on using a JDialog:

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.border.*;

public class RankSelection extends JFrame {
    private static final long serialVersionUID = 1L;
    private JPanel contentPane;
    private JTextField textField;

    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {
            public void run() {
                try {
                    RankSelection frame = new RankSelection();
                    frame.setVisible(true);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }

    public RankSelection() {
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        contentPane = new JPanel();
        contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
        contentPane.setLayout(new BorderLayout(0, 0));
        setContentPane(contentPane);

        JComboBox<String> comboBox = new JComboBox<String>();
        comboBox.setModel(new DefaultComboBoxModel<String>(new String[] {"Slave", "Peasant", "Minion", "Knight", "Bishop", "Prince", "Coder King"}));
        comboBox.addItemListener(new ItemListener() {

            @Override
            public void itemStateChanged(ItemEvent e) {
                if(e.getStateChange() == ItemEvent.SELECTED){
                    Amount amount = new Amount();
                    textField.setText(Integer.toString((Integer) amount.getStinkiness().getValue()));
                }
            }
        });
        contentPane.add(comboBox, BorderLayout.CENTER);

        JLabel lblYourRank = new JLabel("Your Rank");
        contentPane.add(lblYourRank, BorderLayout.NORTH);

        JPanel panel = new JPanel();
        contentPane.add(panel, BorderLayout.SOUTH);

        JLabel lblYourStinkiness = new JLabel("Your Stinkiness:");
        panel.add(lblYourStinkiness);

        textField = new JTextField();
        textField.setEditable(false);
        textField.setEnabled(false);
        textField.setText("0");
        panel.add(textField);
        textField.setColumns(10);
        pack();
    }

}

The custom JDialog:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.border.*;

public class Amount extends JDialog {
    private static final long serialVersionUID = 1L;
    private final JPanel contentPanel = new JPanel();
    private JSpinner amount;
    private JSpinner stinkiness;

    public Amount() {
        setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
        setModalityType(ModalityType.APPLICATION_MODAL);
        getContentPane().setLayout(new BorderLayout());

        contentPanel.setLayout(new FlowLayout());
        contentPanel.setBorder(new EmptyBorder(5, 5, 5, 5));
        getContentPane().add(contentPanel, BorderLayout.CENTER);

        JLabel lblAmount = new JLabel("Amount:");
        amount = new JSpinner();
        JLabel lblStinkiness = new JLabel("Stinkiness:");
        stinkiness = new JSpinner();

        contentPanel.add(lblAmount);
        contentPanel.add(amount);
        contentPanel.add(lblStinkiness);
        contentPanel.add(stinkiness);

        JPanel buttonPane = new JPanel();
        buttonPane.setLayout(new FlowLayout(FlowLayout.CENTER));
        getContentPane().add(buttonPane, BorderLayout.SOUTH);
        JButton okButton = new JButton("OK");
        okButton.setActionCommand("OK");
        buttonPane.add(okButton);
        getRootPane().setDefaultButton(okButton);
        okButton.addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent e) {
                dispose();
            }
        });

        pack();
        setVisible(true);
    }

    public JSpinner getAmount() {
        return amount;
    }

    public JSpinner getStinkiness() {
        return stinkiness;
    }

}


text:
Q: Hide login page and use wp_login_form on ordinary pages I would like to hide site.com/wp-login.php page but also to use wp_login_form() function where I want. Currently this function doesn't work if I hide login page with this code (it redirects to front page)
function go_away() {
        global $action;
        // redirect only if action is login (lost password action is ok)
        if($action === 'login') {
           wp_redirect(site_url());
           exit();
        }
}
add_action( 'login_init' , 'go_away' );
add_action( 'admin_init' , 'go_away' );

And code for login in front-page.php or in sidebar.php is this
wp_login_form(
    array(
    'redirect' => site_url( '/wp-admin/' )
));

How can I make wp_login_form work while hiding login page? Because currently this wp_login_form just keeps redirecting me to front page.


text:
Q: Pass function for child with unknown parameter in Angular I have 2 component (Brand, Product) with pagination and search.
So, I want to create reuse paginator. This paginator component receive
@Input() currentPage: number;
@Input() totalPage: number;

Now, I have (3: current, 6: total)
1, 2, [3], 4, 5, 6

When change page, it call function from parent component like
this.getAllProduct(currentPage, totalPage);

But when I search with pagination, function search in brand(product) component look like
searchBrand(name);

or
searchProduct(name, sku, brand, category, price, ....);

How to pass this function for child component (paginator), when I click page, it call these function

A: Angular has this documentantation page with examples and explanations about how to make your components interact. Read it thoroughly, it will give you all the tools you need: Component Interaction.
To answer to this specific question:

*

*If the action originates in the parent, and you want to invoke a method that exists in the children, either use @Input or ViewChild:

*

*With @Input you can listen for changes in the child by implementing the ngOnChanges method.

*With @ViewChild you can invoke a child's method directly from the parent. This is for more advanced uses, so I doubt you want this for this case.

*If the action originates in the child, and you want to invoke a method that exists in the parent, then use @Output.
For more advanced use cases, you can use a service to communicate both parent and child bidirectionally.


text:
Q: Efficient method for generating a list of values from a column in a data frame based on common secondary columns I have a data frame (df) in Python with 4 columns (ID, Status, Person, Output). Each ID is repeated 6 times and the Output is the same for each ID. For each ID, the Status will be On/Off (3 of each).
I need to generate a new column with a list of people for each unique ID/Status combination. I also need a second new column with a group ID for each unique list of people.
This is my current code which works but is very slow when working with a large data frame due to the apply(list) function. Is there a more efficient way to do this?
people = df.groupby(['ID','Status'])['Person'].apply(list).reset_index(name='Names_ID')
people['Group_ID'] = people['Names_ID'].rank(method='dense')
df = df.drop_duplicates(subset=['ID','Status'])
df = df.merge(people, on = ('ID', 'Status'))

Here is an example input data frame:
df=
ID  Status  Person  Output
0   On  John    1
0   On  Mark    1
0   On  Michael 1
0   Off Peter   1
0   Off Tim     1
0   Off Jake    1
1   On  Peter   0.5
1   On  Dennis  0.5
1   On  Jasper  0.5
1   Off John    0.5
1   Off Mark    0.5
1   Off Michael 0.5
2   On  John    2
2   On  Mark    2
2   On  Larry   2
2   Off Peter   2
2   Off Dennis  2
2   Off Jasper  2

The desired output is:
df =
ID  Status  People                Group_ID  Output
0   On  [John, Mark, Michael ]      0       1
0   Off [Peter, Tim, Jake ]         1       1
1   On  [Peter, Dennis, Jasper ]    2       0.5
1   Off [John, Mark, Michael ]      0       0.5
2   On  [John, Mark, Larry ]        3       2
2   Off [Peter, Dennis, Jasper ]    2       2

A: Try this:
df_out = df.groupby(['ID', 'Status'])['Person'].apply(list).reset_index()
df_out['Group_ID'] = pd.factorize(df_out['Person'].apply(tuple))[0]
df_out

Output:
   ID Status                   Person  Group_ID
0   0    Off       [Peter, Tim, Jake]         0
1   0     On    [John, Mark, Michael]         1
2   1    Off    [John, Mark, Michael]         1
3   1     On  [Peter, Dennis, Jasper]         2
4   2    Off  [Peter, Dennis, Jasper]         2
5   2     On      [John, Mark, Larry]         3

OR
df_out = df.groupby(['ID', 'Status'])['Person'].apply(', '.join).reset_index()
df_out['Group_ID'] = pd.factorize(df_out['Person'])[0]
df_out

A: import pandas as pd
df = pd.read_clipboard()
df

One method is to use shift twice and join the three columns into a list. Then use groupby to figure out the Group_ID and merge it back into the dataframe.
df['Person1'] = df['Person'].shift(-1)
df['Person2'] = df['Person'].shift(-2)
df['People'] = '[' + df['Person'] + ',' + df['Person1'] + ',' + df['Person2'] + ']'
mult_3 = []
for i in df.index:
    if i==0 or i%3 == 0:
        mult_3.append(i)
df = df.loc[df.index.isin(mult_3)].drop(['Person', 'Person1', 'Person2'], axis=1)
df_people = df.groupby('People').Status.count().reset_index().drop(['Status'], axis=1).reset_index()
df = df.merge(df_people, how='left', on='People').rename(columns={'index':'Group_ID'})
df = df[['ID', 'Status', 'People', 'Group_ID', 'Output']]
df

A: Python 3.7.6 and Pandas 1.0.3:  The bottleneck here are probably the apply calls.
people = df.groupby(['ID','Status', "Output"])['Person'].apply(list).reset_index(name = 'People')
people['Group_ID'] = people["People"].apply(str).astype('category').cat.codes

Output:
  ID Status Output                   People  Group_ID
0  0    Off      1       [Peter, Tim, Jake]         3
1  0     On      1    [John, Mark, Michael]         1
2  1    Off    0.5    [John, Mark, Michael]         1
3  1     On    0.5  [Peter, Dennis, Jasper]         2
4  2    Off      2  [Peter, Dennis, Jasper]         2
5  2     On      2      [John, Mark, Larry]         0


text:
Q: Law of total expectation and how prove that two variables are independent I am confused in understanding the formal definition for independence and how does this differ from the law of total expectations.
I thought that $E[u|x]=E[u]$ formally means independence of $u$ and $x$.
However, when I have $E[u|x]=a$ (const) and use the law of total expectations,
$E[u]=E[E[u|x]]=a$
I obtain $E[u]=a$
Don't I have then $a=E[u|x]$ and $a=E[u] \implies a=E[u|x]=E[u] \implies \text{independence between x and u}$?
Something does not add up, as this would mean that we can always establish independence between two variables. Where is my error in thinking?

A: It's impossible to read minds, so to locate any error in thinking let's help you work through as simple an example as possible using the most basic possible definitions and axioms of probability.
Consider a sample space $\Omega = \{au, bu, cu, av, bv, cv\}$ ("$au$" etc. are just names of six abstract things) where all subsets are considered measurable.  Define a probability $\mathbb{P}$ on $\Omega$ in terms of its values on the atoms via
$$\mathbb{P}(au) = \mathbb{P}(cu) = p,\ \mathbb{P}(bu) = r-2p;\quad \mathbb{P}(av) = \mathbb{P}(cv) = q,\ \mathbb{P}(bv) = 1-r-2q$$
where $p,q,r$ are any numbers for which all six probabilities are positive.  For instance, we may take $p=1/6$, $q=1/8$, and $r=1/2$.  Because the sum of the six given probabilities is unity, this defines a valid probability measure.
Define the random variables $U$ and $X$ as
$$U(\omega)=-1, 0, 1$$
depending on whether the initial letter in the name of $\omega$ is $a$, $b$, or $c$ respectively; and
$$X(\omega) = 0,1$$
depending on whether the final letter in the name of $\omega$ is $u$ or $v$ respectively.
This can be neatly summarized in a $3$ by $2$ table of probabilities, headed by values of $U$ and $X$, whose interpretation I trust is evident:
$$\begin{array}{r|cc}
  & \text{X=0} & \text{X=1} \\
\hline
 \text{U=-1} & p & q \\
 \text{U=0} & r-2 p & 1-r-2 q \\
 \text{U=1} & p & q
\end{array}$$
It is then easy to compute the following:

*

*$\mathbb{P}(X=0) = \mathbb{P}(\{au,bu,cu\}) = p + r-2p + p = r$ (sum the left column in the table).

*$\mathbb{P}(U=-1) = \mathbb{P}(\{au,av\}) = p+q$ (sum the top row in the table).
Independence means nothing other than probabilities multiply.  This would imply, among other things, that
$$p = \mathbb{P}(au) = \mathbb{P}(X=0, U=-1) = \mathbb{P}(X=0)\mathbb{P}(U=-1) = r(p+q)$$
(investigate the top left entry in the table).  But this is rarely the case; for instance, $1/6 \ne (1/2)(1/6 + 1/8)$.  Therefore $X$ and $U$ are not independent (except for some special possible combinations of $p$, $q$, and $r$). However,
$$\mathbb{E}(U) = \mathbb{P}(U=-1)(-1) +  \mathbb{P}(U=0)(0) + \mathbb{P}(U=1)(1) = 0$$
That is, the expectation of $U$ is zero. (This should be obvious from the symmetry: the chance that $U=1$ balances the chance that $U=-1$ regardless of the value of $X$.)  However,
$$\mathbb{E}(U|X=0) = \mathbb{P}(U=-1, X=0)(-1) + \cdots + \mathbb{P}(U=1, X=0)(1) = 0,$$
and similarly $$\mathbb{E}(U|X=1) = 0.$$  That is, the conditional expectation of $U$--which is a function--has the constant value zero.  In symbols, we have found that
$$\mathbb{E}(U|X) = 0 = \mathbb{E}(U)$$
and we have a simple, explicit example showing why constant conditional expectation does not imply independence.


text:
Q: Differentiability of $\ f(z) = e^{\bar z}$ Hey so I've just started trying to teach myself complex analysis and Ijudt came accross the following question:
Find the real and imaginary parts of the following function and decide where the function is differentiable and where it is holomorphic. Determine the derivative at the points where the function is differentiable.
$$\ f(z) = e^{\bar z}$$
I have no idea how to go about this question any help would be greatly appreciated, just bare in mind I'm new to complex analysis

A:
"I have no idea how to go about this question"

How about asking yourself simpler questions:

*

*What are the real and imaginary parts of $f$?

*How do the real and imaginary parts of $f$ relate to the differentiability of it? What theorems do you know about complex differentiability?

*Can you find out at what point $f$ is differentiable?

A: Hint: $$e^{\bar{z}}=e^{x-yi}=e^x(\cos(y)-i\sin(y)) $$ and then use the Cauchy Riemann equations.

A: There is actually the following quite elegant criterion:
A function $f$ is differentiable if and only if $\frac{\partial f}{\partial \overline{z}}\equiv 0$.


text:
Q: QGIS2Leaf help when trying to export So when I try to export to leaflet I get this Error and I dont know how to fix it....I went in to QGIS2LEAF export and imorted all my layers and selected OSM basemap and clicked Full screen, selected the ouput folder and when I went to click okay, it stalled and gave me this error.
An error has occured while executing Python code:

Traceback (most recent call last):
  File "C:/Users/RPM94/.qgis2/python/plugins\qgis2leaf\qgis2leafdialog.py", line 297, in export2leaf
    qgis2leaf_exec(self.outFileName, self.basemapName, self.basemapMeta, self.basemapAddress, self.width, self.height, self.extent, self.full_screen, self.layer_list, self.visible, self.opacity, self.encode2JSON,self.createcluster, self.webpage_name, self.webmap_head,self.webmap_subhead, self.legend,self.locate,self.address, self.precision, self.labels, self.labelshover, self.matchCRS, self.selected)
  File "C:/Users/RPM94/.qgis2/python/plugins\qgis2leaf\qgis2leaf_exec.py", line 290, in qgis2leaf_exec
    print '>> ' + crsProj4
UnboundLocalError: local variable 'crsProj4' referenced before assignment

Python version:
2.7.5 (default, May 15 2013, 22:44:16) [MSC v.1500 64 bit (AMD64)]

QGIS version:
2.8.2-Wien Wien, 1b929ef

Python path: ['C:/PROGRA~1/QGISWI~1/apps/qgis/./python/plugins\\processing', 'C:/PROGRA~1/QGISWI~1/apps/qgis/./python', u'C:/Users/RPM94/.qgis2/python', u'C:/Users/RPM94/.qgis2/python/plugins', 'C:/PROGRA~1/QGISWI~1/apps/qgis/./python/plugins', 'C:\\PROGRA~1\\QGISWI~1\\apps\\Python27\\lib\\site-packages\\matplotlib-1.3.1-py2.7-win-amd64.egg', 'C:\\PROGRA~1\\QGISWI~1\\apps\\Python27\\lib\\site-packages\\nose-1.3.3-py2.7.egg', 'C:\\PROGRA~1\\QGISWI~1\\apps\\Python27\\lib\\site-packages\\tornado-4.0.1-py2.7-win-amd64.egg', 'C:\\PROGRA~1\\QGISWI~1\\apps\\Python27\\lib\\site-packages\\backports.ssl_match_hostname-3.4.0.2-py2.7.egg', 'C:\\PROGRA~1\\QGISWI~1\\apps\\Python27\\lib\\site-packages\\certifi-14.05.14-py2.7.egg', 'C:\\PROGRA~1\\QGISWI~1\\bin\\python27.zip', 'C:\\PROGRA~1\\QGISWI~1\\apps\\Python27\\DLLs', 'C:\\PROGRA~1\\QGISWI~1\\apps\\Python27\\lib', 'C:\\PROGRA~1\\QGISWI~1\\apps\\Python27\\lib\\plat-win', 'C:\\PROGRA~1\\QGISWI~1\\apps\\Python27\\lib\\lib-tk', 'C:\\PROGRA~1\\QGISWI~1\\bin', 'C:\\PROGRA~1\\QGISWI~1\\apps\\Python27', 'C:\\PROGRA~1\\QGISWI~1\\apps\\Python27\\lib\\site-packages', 'C:\\PROGRA~1\\QGISWI~1\\apps\\Python27\\lib\\site-packages\\PIL', 'C:\\PROGRA~1\\QGISWI~1\\apps\\Python27\\lib\\site-packages\\jinja2-2.7.2-py2.7.egg', 'C:\\PROGRA~1\\QGISWI~1\\apps\\Python27\\lib\\site-packages\\markupsafe-0.23-py2.7-win-amd64.egg', 'C:\\PROGRA~1\\QGISWI~1\\apps\\Python27\\lib\\site-packages\\pytz-2012j-py2.7.egg', 'C:\\PROGRA~1\\QGISWI~1\\apps\\Python27\\lib\\site-packages\\win32', 'C:\\PROGRA~1\\QGISWI~1\\apps\\Python27\\lib\\site-packages\\win32\\lib', 'C:\\PROGRA~1\\QGISWI~1\\apps\\Python27\\lib\\site-packages\\Pythonwin', 'C:\\PROGRA~1\\QGISWI~1\\apps\\Python27\\lib\\site-packages\\Shapely-1.2.18-py2.7-win-amd64.egg', 'C:\\PROGRA~1\\QGISWI~1\\apps\\Python27\\lib\\site-packages\\six-1.3.0-py2.7.egg', 'C:\\PROGRA~1\\QGISWI~1\\apps\\Python27\\lib\\site-packages\\wx-2.8-msw-unicode', 'C:\\PROGRA~1\\QGISWI~1\\apps\\Python27\\lib\\site-packages\\xlrd-0.9.2-py2.7.egg', 'C:\\PROGRA~1\\QGISWI~1\\apps\\Python27\\lib\\site-packages\\xlwt-0.7.5-py2.7.egg', u'C:/Users/RPM94/.qgis2//python', 'C:\\PROGRA~1\\QGISWI~1\\apps\\qgis\\python\\plugins\\fTools\\tools', 'D:/Presentation']

A: Try to unselect Layer Extent and go with Canvas Extent. This should fix the problem. Yet You can try to export with qgis2web. The fix for qgis2leaf might take a little longer due to missing capacities.

A: qgis2leaf is no longer under active development:
https://github.com/Geolicious/qgis2leaf/issues/269
The issue is therefore perhaps unlikely to be fixed. Consider trying qgis2web as an alternative - it's a merge of qgis2leaf and qgis-ol3. It does not have all of qgis2leaf's functionality for Leaflet export, but it might achieve what you need.


text:
Q: coordinates in an area tag So I've started a web design course about 4 months ago, it's going smoothly and I'm really enjoying it. I'm trying to learn more in my own time and found  tag while searching for something similair.
I don't fully understand it, but I think I get the grasp of it, so basically I'm asking if what I think the cords do is correct.
coords="x1,y1, x2,y2"
Does that create a box, which I can then use a  so when it's pressed linked to another page?

A: I think you're a bit confused.
This function won't perform any doing. In fact, all that is a 'string'. Meaning, if you refer to cords, you will just find 'x1,y1, x2,y2' as the value.
If you're interested in linking content, use 'a' tags. Also, if you'd like to create a nice box, you're going to need some styling knowledge. Remember, as a web designer you create content for the web developer to put together. If you're looking into making the sites, look for a course in 'Web Development'.


text:
Q: crystal to ssrs report conversion - lay out issues-Grouping into sections & DocumentMap I am trying to convert a crystal report to SSRS report manually. In crystal report, grouping is done as shown in the below screen shot [that has header name as' report header'].
Group Name-->and some rows below it.
Is it possible to get similar grouping in SSRS reports. From what I see, grouping is done on columns is SSRS. For ex, see second screen shot[without any header name].
Question:1. Is it possible to get similar grouping in SSRS as it is in crystal.
2.In crystal report, on left side preview, if I click on group name particular group is getting selected. Even if that group is on another, that page becomes visible. Is this functionality possible in SSRS.
Please share the information. Im using SSRS 2008.

A:
Is it possible to get similar grouping in SSRS as it is in crystal.

Yes: not difficult at all. Insert rows for the group headers. One way to do this: when editing the tablix, right click on the subgroup ("Details," for example) in the "Row Groups" portion of the designer window, and select "Add Total -> Before." This gives you the row you want for the group titles. Next delete the columns you want to remove.

2.In crystal report, on left side preview, if I click on group name particular group is getting selected. Even if that group is on another, that page becomes visible. Is this functionality possible in SSRS.

Yes, in SSRS this is called the Document Map.


text:
Q: Finding number of Unique Binary Search Trees given `n` I am solving an algorithm problem:

Given an integer n, return the number of structurally unique BSTs (binary search trees) which has exactly n nodes of unique values from 1 to n.  So, for n=3, the output is: 5.

This problem can be solved, as given in this SO post.
My high level idea:
When I first looked at the problem, I thought of simulation (using recursion and then memoizing the results): for a root k (1<=k<=n), calculate its prospective left and right children and check if they form a valid BST.  If yes, then increment the counter for the current root and return the counter in the end:
class Solution {
public:
    unordered_set<int> visited;
    int helper(int root, int n, int l, int r, int sz) {
        if(root<=0 || root>n) return 0;
        visited.insert(root);
        if(visited.size()==n) return 1;  //visited contains all `n` nodes, so a valid BST is formed if we are here.

        int counter=0;
        for(int i=1; i<=n; i++) {
            int left=root-i, right=root+i;
            if(left>l && left<r) {
                counter+=helper(left,n,l,root,sz+1);
            }
            if(right>l && right<r) {
                counter+=helper(right,n,root,r,sz+1);
            }
            // cout<<"-----> "<<i<<" "<<left<<" "<<right<<" "<<counter<<"\n";
        }
        return counter;
    }

    int numTrees(int n) {
        int counter=0, l=INT_MIN, r=INT_MAX;
        for(int i=1; i<=n; i++) {
            visited.clear();
            int val=helper(i,n,l,r,1);
            // cout<<"i: "<<i<<" val: "<<val<<"\n";
            counter+=val;
        }
        return counter;
    }
};

This returns correct answers upto 3, but then onwards returns wrong answers.  I am about to draw the recursion tree and dive deep, but wanted to see if my high level idea is even promising or if I am down to a wrong start.
Thanks!


text:
Q: Mock objects in Junit test gives NoClassDefFoundError When I mock objects in Junit test cases using of PowerMock and Mockito, I'm getting this exception:
java.lang.NoClassDefFoundError: org/mockito/exceptions/base/MockitoSerializationIssue

A: I got this when combining PowerMock with Mockito. Fixed by using compatible version as shown here: https://github.com/powermock/powermock/wiki/Mockito#supported-versions

A: Check version of your mockito lib.  I see org.mockito.exceptions.base.MockitoSerializationIssue class in 2.0.2-beta. It is not present in 1.9.5 .

A: You don't have to use the beta version. The latest 1.10.x should also work. I had the same problem when using 1.9.5, but changing to 1.10.19 fixed the problem.


text:
Q: Ansible playbook on ubuntu 20 How to write Ansible Playbook to install different applications on different hosts on Ubuntu 20.04
Conditions

*

*When running a playbook it should ask for the host name (we must give the specific host name)

For all the packages we have to give numbers like 1,2,3, .....
After giving the host name it should ask for the package number, at that time we should give that number, the specific package should be installed on the specific host

A: I would organize my Ansible repo to have separate role for each software and then use ansible_hostname fact of gather_facts module as condition to install software for the specific host. I would go with a folder structure like this:
└── ansible_repo
    ├── roles
    │   ├── vim
    │   │   └── tasks
    │   │       └── main.yml
    │   ├── tmux
    │   │   └── tasks
    │   │       └── main.yml
    │   └── vlc
    │       └── tasks
    │           └── main.yml
    ├── inventory
    └── playbook.yml

The contents of the playbook.yml will go along something like this:
# playbook.yml
- hosts: all
  become: true
# run roles
- hosts: all
  roles:
    - vim
    - tmux
    - vlc

The main.yml inside each task will follow this template (there vim is used):
---
# tasks file for vim

- name: Install vim
  apt:
    name:
      - vim
    when gather_facts.ansible_hostname = "host1" or "host3"

You can store the host name in inventory file as well.
While this one would work, but it would not be the best practice, I think. A better way would be to group your hosts based on what packages the need and then use the specific roles for that group.


text:
Q: How to make output in mit-scheme less verbose when it's used for running script I've found this question where people recommend to use mit-scheme for solving exercises from SICP. After doing some python and ruby I'm wondering is it possible to use mit-scheme interpreter/compiler in the same manner how can be used ruby or python? By this I mean simply write the script in vim and run mit-scheme my_script.scm in terminal to see the output.
update
Seems like mit-scheme < my_script.scm does what I was looking for, but its output is too verbose.
Ideally, I'd like to see in the output only things which I deliberately sent to stdout.

A: You are looking for the --silent flag.
Usage: mit-scheme --silent < my-script.scm


text:
Q: How to remove a particular PPA? I have added Transmission PPA. After adding PPA, when I tried to open software updater I got the following messege.
Failed to load the package list
This is a serious problem. Try again later. If this problem appears again, please report an error to the developers.
Even I could'nt open software sources, ubuntu software center, and sypnatic package manager.
What I have to do. Is there any command to remove the PPA.

A: The following command removes the ppa.
$ sudo add-apt-repository --remove ppa:PPANAME
$ sudo apt-get update

A: The answer from Sagar Rakshe is correct.
Here I explain how to perform it manually.
Remove the repository
First, identify your wrong file in /etc/apt/sources.list.d
(you may also have to check the main file /etc/apt/sources.list)
cd /etc/apt/sources.list.d
head *.list

Then, rename the file to disable it:
sudo mv  WRONGFILE.list  WRONGFILE.list.backup

Or instead of renaming the file, create a backup directory and move the file there:
sudo mkdir             backup_on_date_YYYMMDD
sudo mv WRONGFILE.list backup_on_date_YYYMMDD

For your information, add-apt-repository is a python script adding or commenting lines in your *.list files. Personally I prefer to handle myself these operations in order to keep clear & secure *.list files.
Remove the package signing keys
Show the installed apt keys with apt-key list and find the key for the repo you want to remove, for example:
pub   2048R/5044912E 2010-02-11
uid                  Dropbox Automatic Signing Key <linux@dropbox.com>

You can then use sudo apt-key del 5044912E to remove this key.

A: The graphical way of removing ppa repositories is as follows:

*

*open your System Settings

*click on the Softare & Updates icon

*go to the Other Software tab

*select the repository you want to remove

*click the Remove button

I hope this helps


text:
Q: How to Save an Input table in Mining Model Prediction tab in SSAS I am using SSAS (Visual Studio 2010) to create a Decision Tree model. After the model has been created I can go to the Mining Model Prediction tab to "score" another data set against the model.
However, if I close the Mining Structure (or the solution) and open it again the "scoring" data set that I have connected to the model is gone and I have to repeat all the mapping again.
Is there is a way to save not only the Mining Structure but also the scoring data set?
Thank you.

A: Connect to a SQL database, then make a linked server to your SSAS OLAP server, then try this...
insert into myTempResults (columns....)

select columns.... from OPENQUERY(SSAS_OLAP_LINKED_SERVER, 'your mdx query').

you probably need to use FLATTENED in the expression that joins to the mining model
also take a look here for more info..
http://social.msdn.microsoft.com/Forums/sqlserver/en-US/92d22b85-0c8c-4db2-a931-5188f7ad90dc/push-mdx-query-result-to-sql-table-with-in-caption-of-members?forum=sqlanalysisservices


text:
Q: make bigger space for legend in echarts I'm using echarts
this is my chart
this picture shows I lost some of my legends , so,how do I make bigger space for legends, is it possible to set more space for legends? or if it is possible to make my chart smaller how can I do?

A: I put
var option = {
    grid: {
        y: 30,
        y2: 90,
    },

y mean space before chart, y2 - after chart


text:
Q: How to extract matrix together with vocab from gensim word2vec model I've trained a word2vec model like so
from gensim.models import Word2Vec

# create model without initializing
model = Word2Vec(min_count=20,
                 window=5,
                 sample=6e-5,
                 negative=20,
                 workers=cores-1,
                 vector_size=300)

# build vocabulary
w2v_model.build_vocab(sentences, progress_per=10000)

# train model
model.train(sentences, total_examples=w2v_model.corpus_count, epochs=30, report_delay=1)

I'd like to export the model as a dataframe, but not sure how to extract the matrix and vocab together correctly, with the right index positions.
Something like this:

label
V1
V2
V...

government
0.560774564
-0.0464625023
...

state
0.0106112240
0.0464625023
...

....
...
..
.

I've tried this:
tmp = pd.DataFrame(model.syn1neg)
tmp.insert(0, 'label', model.wv.index_to_key)

which does not square up when comparing
>>> model.wv.get_index('government')
10
>>> tmp.loc[[0]]
0 government 0.329972  0.160003 -0.516633  ...  0.460873 -0.170273 -1.621128  1.255289

A: For anyone else looking for a solution to this with gensim 4.x.x here's what I wound up doing:
vocab, vectors = model.wv.key_to_index, model.wv.vectors

# get label and vector index.
label_index = np.array([(voc[0], voc[1]) for voc in vocab.items()])

# init dataframe using embedding vectors and set index as node name
tmp =  pd.DataFrame(vectors[label_index[:,1].astype(int)])
tmp.index = label_index[:, 0]
tmp.to_csv("matrix_with_labels.csv")

Not sure this is the best or proper way but it works.


text:
Q: What use does if_/3 have? The predicate if_/3 seems to be fairly popular among the few main contributors in the Prolog part of Stack Overflow.
This predicate is implemented as such, courtesy of @false:
if_(If_1, Then_0, Else_0) :-
   call(If_1, T),
   (  T == true -> call(Then_0)
   ;  T == false -> call(Else_0)
   ;  nonvar(T) -> throw(error(type_error(boolean,T),_))
   ;  /* var(T) */ throw(error(instantiation_error,_))
   ).

However, I have been unable to find a clear, simple, and concise explanation of what this predicate does, and what use it has compared to e.g. the classical if-then-else construct of Prolog if -> then ; else.
Most links I have found directly use this predicate and provide little explanation as to why it gets used, that a non-expert in Prolog could understand easily.

A: In old-fashioned Prolog code, the following pattern arises rather frequently:

predicate([], ...).
predicate([L|Ls], ...) :-
        condition(L),
        then(Ls, ...).
predicate([L|Ls], ...) :-
        \+ condition(L),
        else(Ls, ...).

I am using lists here as an example where this occurs (see for example include/3, exclude/3 etc.), although the pattern of course also occurs elsewhere.
The tragic is the following:

*

*For an instantiated list, pattern matching can distinguish the first clause from the remaining two, but it cannot distinguish the second one from the last one because they both have '.'(_, _) as the primary functor and arity of their first argument.

*The conditions in which the last two clauses apply are obviously mutually exclusive.

*Thus, when everything is known, we want to obtain an efficient, deterministic predicate that does not leave choice points, and ideally does not even create choice points.

*However, as long as not everything can be safely determined, we want to benefit from backtracking to see all solutions, so we cannot afford to commit to either of the clauses.

In summary, the existing constructs and language features all fall short in some way to express a pattern that often occurs in practice. Therefore, for decades, it seemed necessary to compromise. And you can make a pretty good guess in which direction the "compromises" usually go in the Prolog community: Almost invariably, correctness is sacrificed for efficiency in case of doubt. After all, who cares about correct results as long as your programs are fast, right? Therefore, until the invention of if_/3, this was frequently wrongly written as:

predicate([], ...).
predicate([L|Ls], ...) :-
        (    condition(L) ->
             then(Ls, ...).
        ;    else(Ls, ...).
        )

The mistake in this is of course that when the elements are not sufficiently instantiated, then this may incorrectly commit to one branch even though both alternatives are logically possible. For this reason, using if-then-else is almost always declaratively wrong, and stands massively in the way of declarative debugging approaches due to its violation of the most elementary properties we expect from pure Prolog programs.

Using if_/3, you can write this as:

predicate([], ...).
predicate([L|Ls], ...) :-
        if_(condition(L),
            then(Ls, ...),
            else(Ls, ...)).

and retain all desirable aspects. This is:

*

*deterministic if everything can be safely decided

*efficient in that it does not even create choice points

*complete in that you never incorrectly commit to one particular branch.

The price of this is rather affordable: As Boris mentioned in the comments, you need to implement a reification. I have now some experience with this and found it rather easy with some practice.
Good news everyone: In many cases, condition is of the form (=)/2, or (#=)/2, and the first even ships with library(reif) for free.
For more information, see Indexing dif/2 by Ulrich Neumerkel and Stefan Kral!

A: Let's try to solve a simple problem using if_/3; for example, I will try to partition a list (sorted on a predicate p/2) in two lists: a prefix in which, for every element X, we have p(X, true), and a rest (in which, if the list was sorted on p/2, we would have p(X, false).
I will use the library reif as here. So, here is the complete code of my program:
:- use_module(reif).

pred_prefix(Pred_1, List, L_true, L_false) :-
        pred_prefix_aux(List, Pred_1, L_true, L_false).

pred_prefix_aux([], _, [], []).
pred_prefix_aux([X|Xs], Pred_1, True, False) :-
        if_(    call(Pred_1, X),
                (       True = [X|True0],
                        pred_prefix_aux(Xs, Pred_1, True0, False)
                ),
                (       True = [],
                        False = [X|Xs]
                )
        ).

The predicate passed to this meta-predicate will take two arguments: the first is the current list element, and the second will be either true or false. Ideally, this predicate will always succeed and not leave behind choice points.
In the first argument of if_/2, the predicate is evaluated with the current list element; the second argument is what happens when true; the third argument is what happens when false.
With this, I can split a list in leading as and a rest:
?- pred_prefix([X, B]>>(=(a, X, B)), [a,a,b], T, F).
T = [a, a],
F = [b].

?- pred_prefix([X, B]>>(=(a, X, B)), [b,c,d], T, F).
T = [],
F = [b, c, d].

?- pred_prefix([X, B]>>(=(a, X, B)), [b,a], T, F).
T = [],
F = [b, a].

?- pred_prefix([X, B]>>(=(a, X, B)), List, T, F).
List = T, T = F, F = [] ;
List = T, T = [a],
F = [] ;
List = T, T = [a, a],
F = [] ;
List = T, T = [a, a, a],
F = [] .

How can you get rid of leading 0's for example:
?- pred_prefix([X, B]>>(=(0, X, B)), [0,0,1,2,0,3], _, F).
F = [1, 2, 0, 3].

Of course, this could have been written much simpler:
drop_leading_zeros([], []).
drop_leading_zeros([X|Xs], Rest) :-
    if_(=(0, X), drop_leading_zeros(Xs, Rest), [X|Xs] = Rest).

Here I have just removed all unnecessary arguments.
If you would have to do this without if_/3, you would have had to write:
drop_leading_zeros_a([], []).
drop_leading_zeros_a([X|Xs], Rest) :-
    =(0, X, T),
    (   T == true -> drop_leading_zeros_a(Xs, Rest)
    ;   T == false -> [X|Xs] = Rest
    ).

Here, we assume that =/3 will indeed always succeed without choice points and the T will always be either true or false.
And, if we didn't have =/3 either, you'd write:
drop_leading_zeros_full([], []).
drop_leading_zeros_full([X|Xs], Rest) :-
    (   X == 0 -> T = true
    ;   X \= 0 -> T = false
    ;   T = true, X = 0
    ;   T = false, dif(0, X)
    ),
    (   T == true -> drop_leading_zeros_full(Xs, Rest)
    ;   T == false -> [X|Xs] = Rest
    ).

which is not ideal. But now at least you can see for yourself, in one single place, what is actually going on.
PS: Please read the code and the top level interaction carefully.


text:
Q: Can't install synaptic in kali Following is the error while installing synaptic
*Reading package lists... Done
Building dependency tree
Reading state information... Done
Some packages could not be installed. This may mean that you have
requested an impossible situation or if you are using the unstable
distribution that some required packages have not yet been created
or been moved out of Incoming.
The following information may help to resolve the situation:
The following packages have unmet dependencies:
 libfolks25 : Breaks: libfolks-eds25 (< 0.8.0-2~) but 0.6.9-1+b1 is to be installed
E: Error, pkgProblemResolver::Resolve generated breaks, this may be caused by held packages.****

A: Seeing this error, I guess you used apt to install synaptic.
Sometimes, apt faces errors about dependencies, and can't fix them. If you want to fix this errors and force install synaptic, you have to first install aptitude (an equivalent to apt) with the command apt-get install aptitude.
Then use aptitude to install synaptic with the command aptitude install synaptic. It will tell you that there is an error with dependencies (like apt told you), but it will also propose solutions to fix the errors and install the package you want. Each time it provide you with a solution, read it, then press y if you accept that solution, or n to show another solution, until you find the solution where synaptic will be installed.

A: Messing up with repositories or using experimental repositories also led to this error.
If you're using debian only use the appropriate repositories provided by the distro
Type:-
sudo nano /etc/apt/sources.list

Debian :-
deb http://ftp.debian.org/debian stable main contrib non-free

Kali :-
deb http://http.kali.org/kali kali-rolling main non-free contrib

And
sudo apt update

The error above clearly shows that you're using a experimental repository.
Some packages could not be installed. This may mean that you have
requested an impossible situation or if you are using the unstable
distribution that some required packages have not yet been created


text:
Q: getting the property from ViewModel I got a view model like this:
 public class BaseViewModelTech : INotifyPropertyChanged
{

    static string _TechnicianID;
    public string TechnicianID
    {
        get {
            return _TechnicianID;
        }
        set {

            _TechnicianID = TechnicianID;
            OnPropertyChanged("TechnicianID");
        }

    }

    static string _DeviceID;
    public string DeviceID
    {
        get
        {
            return _DeviceID;
        }
        set
        {
            _DeviceID = DeviceID;
            OnPropertyChanged("DeviceID");
        }

    }

    // In ViewModelBase.cs
    public event PropertyChangedEventHandler PropertyChanged;

    protected virtual void OnPropertyChanged(string propertyName)
    {
        this.VerifyPropertyName(propertyName);

        PropertyChangedEventHandler handler = this.PropertyChanged;
        if (handler != null)
        {
            var e = new PropertyChangedEventArgs(propertyName);
            handler(this, e);
        }
    }

    [Conditional("DEBUG")]
    [DebuggerStepThrough]
    public void VerifyPropertyName(string propertyName)
    {
        // Verify that the property name matches a real,
        // public, instance property on this object.
        if (TypeDescriptor.GetProperties(this)[propertyName] == null)
        {
            string msg = "Invalid property name: " + propertyName;
            Debug.Fail(msg);
        }
    }
}

I send it as parameter to my xaml.cs
 public partial class BaseView   : Window{
  BaseViewModelTech  viewModel;
        public BaseView  (BaseViewModelTech   vm)
        {
            InitializeComponent();
            viewModel = vm;
        }}

what do I write to access it throught xaml using binding?? I failed to understand multiple examples.

A: Change your code behind of your view slightly:
public partial class BaseView   : Window
{
    BaseViewModelTech  viewModel;

    public BaseView  (BaseViewModelTech   vm)
    {
        InitializeComponent();
        viewModel = vm;
        this.DataContext = vm;   // <----------- add this
    }
}

And then in your XAML you can have something like this:
<TextBlock Text="{Binding TechnicianID}" />

Also note that in your setters you want to do the notification after the property value is changed, not before:
    set
    {
        _DeviceID = DeviceID;
        OnPropertyChanged("DeviceID");  // <------ this goes after the member variable change
    }

A: In your case you can't directly refer your ViewModel directly into xaml due to you vm instance being member of your View. So, you should set the DataContext of your view first in code-behind:
  public partial class BaseView   : Window{
  BaseViewModelTech  viewModel;
        public BaseView  (BaseViewModelTech   vm)
        {
            InitializeComponent();
            viewModel = vm;
            this.DataContext=viewModel;
        }}

then in your my xaml.xaml for example for label :
    <Label Content="{Binding TechnicianID }"/>


text:
Q: Curator transaction runtime construction The Apache Curator library for ZooKeeper uses a nice "fluent" syntax. For example, to modify several nodes in a transaction, the code looks something like:
client.inTransaction().
    .setData().forNode(node1Path, data1)
    .and()
    .SetData().forNode(node2Path, data2)
    .and()
    .commit();

This works great and, IMHO, produces very readable code. However, I have a situation where I have to modify a set of ZNodes in a transaction. I don't know until runtime how many nodes, or which nodes, will need to be modified. Thus, I don't think I can use the fluent syntax easily. Looking at the docs, I can manually manage the proxy objects each of the fluent method calls return, but then the code requires explicit use of CuratorTransaction, TransactionSetDataBuilder, CuratorTransactionBridge, etc. It's clearly do-able, but the code starts to look really ugly.
I don't see a non-fluent way to do transactions with Curator. Does anyone know if there is one and/or if there is a "nice" way to build a transaction at runtime? Specifically, given a Map<String, String> mapping from ZNode paths to the data that needs to end up in that ZNode, how would you set all the nodes transactionally?

A: One way to skin the cat?:
CuratorTransaction curatorTransaction = client.inTransaction();

for (Map.Entry<String, String> entry : transactionInfo.entrySet()) {
    curatorTransaction = curatorTransaction
        .setData().forNode(entry.getKey(), entry.getValue()).and();
}

// If there was at least one entry in transactionInfo, and() makes it a CuratorTransactionFinal
if (curatorTransaction instanceof CuratorTransactionFinal) {
    ((CuratorTransactionFinal)curatorTransaction).commit();
}

A: I use the curator for a zookeeper transaction,first I do some like this
uratorTransaction.create().withMode(CreateMode.PERSISTENT_SEQUENTIAL)
                            .forPath().and();then I commit it like bfos',but the commit method can't  returned,and the exception in the log file is like this:
org.apache.zookeeper.KeeperException$ConnectionLossException: KeeperErrorCode = ConnectionLoss
    at org.apache.zookeeper.KeeperException.create(KeeperException.java:99)
    at org.apache.zookeeper.ZooKeeper.multiInternal(ZooKeeper.java:932)
    at org.apache.zookeeper.ZooKeeper.multi(ZooKeeper.java:912)
    at org.apache.curator.framework.imps.CuratorTransactionImpl.doOperation(CuratorTransactionImpl.java:159)
    at org.apache.curator.framework.imps.CuratorTransactionImpl.access$200(CuratorTransactionImpl.java:44)
    at org.apache.curator.framework.imps.CuratorTransactionImpl$2.call(CuratorTransactionImpl.java:129)
    at org.apache.curator.framework.imps.CuratorTransactionImpl$2.call(CuratorTransactionImpl.java:125)
    at org.apache.curator.RetryLoop.callWithRetry(RetryLoop.java:107)
    at org.apache.curator.framework.imps.CuratorTransactionImpl.commit(CuratorTransactionImpl.java:121)


text:
Q: CPrintDialog Creation Failing in Service Mode of an Application I have an application that prints the report automatically. I am using CPrintDialog to get the Printer DC.
void CMyClass::PrintReport()
{
    CDC dc;
    CPrintDialog printDlg(FALSE);
    printDlg.GetDefaults ();
    ::DeleteDC( printDlg.m_pd.hDC );
    LPDEVMODE pDevMode = printDlg.GetDevMode();
    if(pDevMode)
    {
        pDevMode->dmOrientation = DMORIENT_LANDSCAPE;
        ::GlobalUnlock(pDevMode);
    }
    HDC hDC;
    if( (hDC = printDlg.CreatePrinterDC()) == NULL )
    {
        ::GlobalFree( printDlg.m_pd.hDevMode );
        ::GlobalFree( printDlg.m_pd.hDevNames );
        return;
    }
    ::GlobalFree( printDlg.m_pd.hDevMode );
    ::GlobalFree( printDlg.m_pd.hDevNames );
    dc.Attach(hDC);         // Attach a printer DC
    dc.m_bPrinting = TRUE;
    dc.SetMapMode(MM_LOENGLISH);
    /*

        Printing Logic using dc
    */
}

This works fine when I run my application in the Debug mode which comes a a Console application.
But, the CPrintDialog creation is failing when I run the application as a Windows Service.
Am I doing anything wrong? :( Please help me.
Note: The Application is designed in a way to run as a Service in the Installation.

A:
the CPrintDialog creation is failing when I run the application as a Windows Service.

You cannot display dialogs (or any type of user interface) in a Windows Service. So CPrintDialog is never going to work.
But you don't need to create a dialog to get a printer device context, assuming that you already know which printer you want to print to. And since you're running as a non-interactive service, you must already know this, because there's no way that the user can choose a printer.
To do so, just call CreateDC directly, specifying "WINSPOOL" as the device and the name of the printer. You can obtain the name of the desired printer by enumerating the installed printers using the EnumPrinters function. This is all conveniently documented in a how-to article: Retrieve a Printer Device Context.


text:
Q: SharePoint page edit issue I am using SharePoint Server 2007 Enterprise with Windows Server 2008 Enterprise, and I am using publishing portal template. I am using SharePoint Designer 2007 to design pages. When I open the default.aspx under Pages sub-folder of a site, there are two options -- Edit in Browser and Edit Page Layout. I want to know what are the differences between Edit in Browser and Edit Page Layout -- especially what is the function of Edit Page Layout, because when I select Edit Page Layout, WelcomeSplash.aspx opens in SharePoint Designer, other than default.aspx itself (very confused).
thanks in advance,
George

A: The page layout is default.aspx's backing "template". It holds the actual controls. Edit page layouts to move around controls etc. You can also create your own and bind them to content types.
Edit in browser basically means you edit the values of say the title control, or the content of a richtext fieldcontrol. This is usually done through sharepoint's front end web UI. You can also change a page's assigned pagelayout to a different one, i.e. have default.aspx use ArticlePage.aspx as pagelayout instead of WelcomeSplash.aspx. THis is done in the publishing console in the web ui as well.