text:
Q: Why do underground cables "require a higher degree of reactive power compensation" than overhead lines? I was reading a brag sheet for a certain company's giant transformers, and I came across this sentence:

Furthermore, in some regions, the existing over head lines are being replaced by underground cables, which require a higher degree of reactive power compensation.

Why is this?

A: Short answer: Underground (U/G) cable uses coaxial with earth gnd shield.
So it is the white PE ( polyethylene ) material that increases underground capacitance since it separates the centre core and the copper braid ground sheath and not the proximity of phase to phase lines (although this has some effect.)
Below is just a single phase example.

The design of power distribution cables has improved over the decades and they now have historical experience on what works best.
They use non-coaxial conductor clad steel core with/without insulation cladding.  This makes the power line capacitance negligible compared to the coaxial cable used for U/G since the insulation line to ground is orders of magnitude higher in coaxial cable.
The ABB unit in question has superior dynamic range for handling the wide range of reactive impedance power factor correction of cables that may include O/H and XLPE coaxial U/G cable.
• Shunt reactors are used to compensate the line shunt
capacitance under light load or no load to regulate voltage.
• Series capacitors are often used to compensate the line
inductive reactance in order to transfer more power and increase network stability
Overhead Cable (triaxial) unsheathed

*

*each 3 wire bundle carries same voltage to reduce arc and wind effects.

Underground (and sometimes overhead) sheathed cable (shielded XLPE cable)

Cross Link shielded high voltage cable always used for underground power lines.
Technical background
The capacitance of a single-phase transmission line is given by the ratio of separation and effective radius.
\$C=\dfrac{2πε}{ln(\frac{D}{r})}\$  Where r is the effective radius of the phase conductor.
O/H lines benefit from spacing 2,3 or 4 conductor far apart for added strength against wind and raised breakdown effects from reduced  E field divergence radius.  This lowers L and raises C slightly but is still very low C values/km compare the high C/km of coaxial U/G cable due to the small gap r of the centre conductor to coaxial sheath.
Below is Telegrapher's model of all transmission lines including ethernet, cable TV, phone lines and AC or DC power lines. (except shunt leakage R is neglected here)
The resistance at DC is not the same as the distributed impedance that affects reflections and surge voltages due to disturbances.

O/H lines are often triaxial as above.
O/H cable is often rated SIL characteristic wave impedance of 400 ohms and U/G cables are 50 ohms =+/-25% depending on ampacity and BIL rating.
This makes black start surge currents higher for U/G cables so shunt reactance needs to be adjusted.
Photos to follow.
Other
Overhead, O/H cables are much cheaper per km to buy and install but frequency of repairs is higher due to lightning, hurricane, and tree exposure. But then they are also faster and cheaper to repair.  But looking at the devastation in Puerto Rico and other locations with poor infrastructure the life cycle cost advantages of underground U/G power cables in spite of higher easement costs, cable cost and repair costs results but at a higher MTBF ( if done properly) results in lower life cycle costs.  Environmental stress always affects these decision.

A: As the conductors of underground lines are packed closer together than for overhead lines, the capacitance is higher. This capacitance can take quite a substantial charging current.
Incidentally, the inductance, as they include a smaller loop area, is lower.

A: Question: Why do underground cables "require a higher degree of reactive power compensation" than overhead lines?
Answer:
Because underground line capacitance for power cables is far higher than overhead line capacitance.
Main reasons for this:

*

*Wires are closer to each other.

*Wires are closer to the earth (within a few inches).
The inductance is lower as well.
Also, because (as a result of above characteristics) underground lines have 20-75 times the line charging current that an overhead line has (depending on line voltage).
Source:
https://www.puc.nh.gov/2008IceStorm/ST&E%20Presentations/NEI%20Underground%20Presentation%2006-09-09.pdf
Also, if you want to take a closer look at the general characteristics of transmission lines via math, you can checkout this document also (others have posted this one as well):
http://www.egr.unlv.edu/~eebag/TRANSMISSION%20LINES.pdf


text:
Q: Difference in adding two images in numpy and opencv when i add two images in opencv, sum is limited to 255. (Both images are of uint8)
ie 175+100 is 255 in opencv.
but if we add it using numpy.add function, result is not a limited one.
ie 175+100 is 19 in numpy.
Question:
1) Why it happen so?
2) Is there a way for np.add to behave like cv2.add? ie limit sum to 255?
Thanks in advance.

A: NumPy uses "modulo" arithmetic on overflow rather than clipping.  This is the behavior of add on uint8 integers in C.   So, 175+100 % 256 = 19 which is the result you are getting.
To get this clipping behavior, you will need to do some work:
Here are a couple of ideas:
1) Use a higher precision:
im1 = im.astype('u2')
im2 = im.astype('u2')
tmp = im1 + im2
result = tmp.clip(0,255).astype('u1')

2) Make sure the result is >= both the input values:
tmp = im1 + im2
mask = (tmp < im1) | (tmp < im2)
tmp[mask] = 255

redpajama_set_name: RedPajamaStackExchange


text:
Q: What are these groups known as, and are their orders multiplicative functions? This question has arisen in my work, and I imagine it is fairly standard to those more algebraic than myself.
Suppose for simplicity that $n$ is odd and squarefree, let $\mathbb{Z}_n^{\times}$ be the unit group of $\mathbb{Z}/n\mathbb{Z}$ and let $H\leq \mathbb Z_n^{\times}$ be a subgroup.
Associated with each divisor $d|n$, one can form a new subgroup, say $H_d$, defined by
$$H_d=\{h\in H: h\equiv 1 \pmod d\}.$$
In other words, the elements of $H_d$ are precisely those that are trivial on $\mathbb{Z}_d^{\times}$.
Firstly, I would like to ask: do these subgroups have a name/standard interpretation in algebraic terms?
Secondly, having tried a few cases (for example when $H$ is a Boolean subgroup) it seems that the $|H_d|$ might be multiplicative functions, that is
$$|H_{de}|=|H_d||H_e|,$$
so I would like to ask if this a known result?

A: Note that for every positive integer $n$, every positive divisor $d$ of $n$, and every subgroup $H\subset(\Bbb{Z}/n\Bbb{Z})^{\times}$, we have $H_d=H\cap\ker\varphi_d=\ker\varphi_d|_H$, where $\varphi_d$ is the natural group homomorphism
$$\varphi_d:\ (\Bbb{Z}/n\Bbb{Z})^{\times}\ \longrightarrow\ (\Bbb{Z}/d\Bbb{Z})^{\times}.$$
I don't know of any standard name for such a subgroup.
It is easy to see that the identity $|H_{de}|=|H_d||H_e|$ cannot hold in general, because $H_{de}\subset H_d$.


text:
Q: Access django database on postgresql from independent python script I have a website built with django and postgresql.
each user (user in django Auth system) on the website have many account models (and other models) .
An app running on windows-python based need to access (read/write) data from the database.
Each app is associated with a specific user.
my questions:

*

*can an app access only specific user data? the account model have an attribute of user so it filter based on that, how can it restrict external app access?

*what is the proper way to read / write from database? can I somehow use the django models as the website do?

A: I think the best way is to build an API layer to exchange data between your Django and your externals. Django rest framework provides a really simply solution to add a REST layer to your app that is also reusable with any other external.
https://www.django-rest-framework.org/
With this approach you centralize and abstract the direct database manipulation in Django, avoiding any external operation that may break it's consistency (for example with an alter table).


text:
Q: Number of permutations where only odd elements must be deranged I am practicing exclusion/ inclusion principle and trying to solve the following problem:
How many permutations of $1,2,3,...,n$ are there in which only the odd integers must be deranged (even integers may be in their own positions)?
My answer is:
$\sum_{j=0}^{n/2} (-1)^j\binom{n/2}{j}(n-j)!$ if $n$ is even
$\sum_{j=0}^{(n-1)/2+1} (-1)^j\binom{(n-1)/2+1}{j}(n-j)!$ if $n$ is odd
Am I right?

A: Your answers are correct. Ignoring the alternating sign, in each summation the $j$ term is the number of ways to choose a set $F$ of $j$ odd numbers from $[n]$ and form a permutation of $[n]$ that fixes $F$ pointwise, so the alternating sum is exactly what the inclusion-exclusion argument requires: $j=0$ starts it off with all possible permutations of $[n]$, $j=1$ subtracts those with at least one specified fixed point, $j=2$ restores those that were subtracted twice, and so on.


text:
Q: NullPointerException when move from FragmentActivity to another FragmentActivity I want to move from Fragment Activity is  as Splash  Screen to another Fragment Activity has tabs but I get NullPointerException when run on device rather than it run on emulator correctly any help? thanks.
Edit : this is logcat
09-10 00:24:05.139: E/AndroidRuntime(20107): FATAL EXCEPTION: main
09-10 00:24:05.139: E/AndroidRuntime(20107): java.lang.RuntimeException: Unable to start activity ComponentInfo{inet.firstproject/inet.firstproject.MainViewActivity}: java.lang.NullPointerException
09-10 00:24:05.139: E/AndroidRuntime(20107):    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2255)
09-10 00:24:05.139: E/AndroidRuntime(20107):    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2309)
09-10 00:24:05.139: E/AndroidRuntime(20107):    at android.app.ActivityThread.access$700(ActivityThread.java:157)
09-10 00:24:05.139: E/AndroidRuntime(20107):    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1289)
09-10 00:24:05.139: E/AndroidRuntime(20107):    at android.os.Handler.dispatchMessage(Handler.java:99)
09-10 00:24:05.139: E/AndroidRuntime(20107):    at android.os.Looper.loop(Looper.java:176)
09-10 00:24:05.139: E/AndroidRuntime(20107):    at android.app.ActivityThread.main(ActivityThread.java:5317)
09-10 00:24:05.139: E/AndroidRuntime(20107):    at java.lang.reflect.Method.invokeNative(Native Method)
09-10 00:24:05.139: E/AndroidRuntime(20107):    at java.lang.reflect.Method.invoke(Method.java:511)
09-10 00:24:05.139: E/AndroidRuntime(20107):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1102)
09-10 00:24:05.139: E/AndroidRuntime(20107):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:869)
09-10 00:24:05.139: E/AndroidRuntime(20107):    at dalvik.system.NativeStart.main(Native Method)
09-10 00:24:05.139: E/AndroidRuntime(20107): Caused by: java.lang.NullPointerException
09-10 00:24:05.139: E/AndroidRuntime(20107):    at inet.firstproject.MainPageActivity.onCreateView(MainPageActivity.java:64)
09-10 00:24:05.139: E/AndroidRuntime(20107):    at android.support.v4.app.Fragment.performCreateView(Fragment.java:1460)
09-10 00:24:05.139: E/AndroidRuntime(20107):    at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:911)
09-10 00:24:05.139: E/AndroidRuntime(20107):    at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1088)
09-10 00:24:05.139: E/AndroidRuntime(20107):    at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1070)
09-10 00:24:05.139: E/AndroidRuntime(20107):    at android.support.v4.app.FragmentManagerImpl.dispatchActivityCreated(FragmentManager.java:1861)
09-10 00:24:05.139: E/AndroidRuntime(20107):    at android.support.v4.app.FragmentActivity.onStart(FragmentActivity.java:547)
09-10 00:24:05.139: E/AndroidRuntime(20107):    at android.app.Instrumentation.callActivityOnStart(Instrumentation.java:1181)
09-10 00:24:05.139: E/AndroidRuntime(20107):    at android.app.Activity.performStart(Activity.java:5336)
09-10 00:24:05.139: E/AndroidRuntime(20107):    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2227)
09-10 00:24:05.139: E/AndroidRuntime(20107):    ... 11 more

this is oncreateView
   public View onCreateView(LayoutInflater inflater, ViewGroup container,
         Bundle savedInstanceState) {
      if (container == null) {
         return null;
     }
     String []athathTypes={"ggg","lll"};
     Bundle bundle = this.getArguments();
   int type = 0; ;
     if(bundle!=null)
        type= (int) bundle.getLong("Type");

     if(isOnline()){
            con.delegate= this;
            if(isOnline()){
                //con.execute(" http://google.com");
            }
            else
            {
                toast("off line ");
            }
     }
     LinearLayout l= (LinearLayout)inflater.inflate(R.layout.activity_main_page, container, false);
     athathList=(ListView) l.findViewById(R.id.listView1);
   //  athathType=(TextView) l.findViewById(R.id.athathtype);
    // athathType.setText(athathTypes[type]);
     String []images={"a","b"};;
     String[] details={"a","b"};;
     String [] discountedprice={"a","b"};;
     String [] price={"a","b"};;
     String []discount={"a","b"};;
     athathList.setAdapter(new MainAdapter(getActivity(),images,details,discountedprice,price,discount));
     ImageButton deps=(ImageButton) l.findViewById(R.id.departments);
     deps.setOnClickListener(new OnClickListener() {//this is line #64

        @Override
        public void onClick(View arg0) {
            Intent selctionAct=new Intent(getActivity(), SelectionActivity.class);
            startActivity(selctionAct);

        }
    });
     return l;
 }

A:  ImageButton deps=(ImageButton) l.findViewById(R.id.departments);

Is returning null.
The reason you are seeing this when you run it on an actual device and not the emulator is, I suspect, because you have multiple layout defined for activity_main_page. Check all versions of this file (landscape/portrait/large/etc..) and make sure they contain the image button with id "departments".


text:
Q: File doesn't open using fopen() function in C I'm using Ubuntu 18.04 on VMWare Fusion.
I have no idea why the file doesn't open using fopen() function in C.
The code is below.
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>

int main(void) {
          char *fname = "file.txt";
          FILE *fp;

          if((fp = fopen(fname, "w")) != NULL) {
                 fprintf(stderr, "open error for %s, errno = %d\n", fname, errno);
                 exit(1);
         }
         printf("opened!\n");
         free(fp);
         return 0;
}

And the result is below.
$ ./a.out
open error for file.txt, errno = 0

My Ubuntu memory is like that.
$ df -h
Filesystem      Size  Used Avail Use% Mounted on
udev            1.9G     0  1.9G   0% /dev
tmpfs           393M  2.1M  391M   1% /run
/dev/sda1        19G   14G  3.9G  79% /
tmpfs           2.0G     0  2.0G   0% /dev/shm
tmpfs           5.0M  4.0K  5.0M   1% /run/lock
tmpfs           2.0G     0  2.0G   0% /sys/fs/cgroup
tmpfs           393M   16K  393M   1% /run/user/122
tmpfs           393M   36K  393M   1% /run/user/1000

A: this statement
if((fp = fopen(fname, "w")) != NULL) {

should be:
if((fp = fopen(fname, "w")) == NULL) {

I.E. the posted code is checking for the success condition and calling it an error
on a related note:
this statement:
free(fp);

is NOT how to close a file
rather use:
fclose( fp );

also,
df

tells disk space usage
To display the information about files use:
ls -al

Strongly suggest making extensive use of the man pages for any functions you want to use.


text:
Q: Why $\sqrt p \in\mathbb Q(\xi_p)$?
If $p\equiv 1 \, \mathrm {mod} \, 4$ is a prime, then $\sqrt p \in\mathbb Q(\xi_p)$ where $\xi_p$ is the $p$-th root of unity.

How to prove the above claim?
(I need this fact to prove quadratic reciprocity law in J.S. Miline's Algebraic Number Theory on p 143, it metions $p$ is the only prime ramifying in $\mathbb Q [\sqrt p]$, I'm not sure wether it helps or not.)


text:
Q: How to make progress bar fill slowly I have a progressbar in drawable. I want it to fill slowly whenset progress is done. That is it I should be able to see it filling, not in a flash. Also I have a texview inside that progressbar, I want that textview to keep revolving and as soon as the set progress filling completes, the textview should stop revolving and display progress.
Here is my code:
Layout:

    <ProgressBar
        android:id="@+id/circularProgressBar"
        style="?android:attr/progressBarStyleHorizontal"
        android:layout_width="150dip"
        android:layout_height="150dip"
        android:layout_centerInParent="true"
        android:indeterminate="false"
        android:max="100"
        android:progress="0"
        android:progressDrawable="@drawable/progressbar" />

    <TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_centerVertical="true"
        android:textSize="47sp"
        android:textStyle="bold"
        android:textColor="@color/Theme" />
</RelativeLayout>

progressbar.xml
<layer-list xmlns:android="http://schemas.android.com/apk/res/android" >

    <item android:id="@android:id/background">
        <shape
            android:innerRadiusRatio="3"
            android:shape="ring"
            android:thicknessRatio="7.0"
            android:useLevel="false" >
            <solid android:color="@color/Red" />
        </shape>
    </item>
    <item android:id="@android:id/progress">
        <shape
            android:innerRadiusRatio="3"
            android:shape="ring"
            android:thicknessRatio="7.0" >
            <solid android:color="@color/Theme" />
        </shape>
    </item>

</layer-list>

Also, I have a textview inside this progressbar, I want it to keep rotating until the progress is done. How to do that, I have an animation for that but it is not working.
Here is the code:
rotate.xml
<rotate xmlns:android="http://schemas.android.com/apk/res/android" >
android:duration="4000"
android:fromdegrees="0"
android:pivotx="50%"
android:pivoty="50%"
android:todegrees="360"
android:toyscale="0.0"

</rotate>

It gives warnings like this: Unexpected text found in layout file: "android:fromdegrees="0" android:pivotx="50%"
android:pivoty="50%" android:todegrees="360" android:to..."

A: Create a Property for the progress:
final Property<ProgressBar, Integer> progressProperty = new Property<ProgressBar, Integer>(
        int.class, "progress") {
    @Override
    public Integer get(ProgressBar object) {
        return object.getProgress();
    }

    @Override
    public void set(ProgressBar object, Integer value) {
        object.setProgress(value);
    }
};

Create and start an ObjectAnimator for that property on your ProgressBar (mProgressBar):
private void animateProgressBar(int targetProgress) {
    ObjectAnimator anim = ObjectAnimator.ofInt(mProgressBar, progressProperty, targetProgress);
    anim.setInterpolator(new DecelerateInterpolator());
    anim.setDuration(300);
    anim.start();
}

You can costumize the animation with Interpolators, different duration, ecc
You can also use:
private void animateProgressBar(int targetProgress) {
    ObjectAnimator anim = ObjectAnimator.ofInt(mProgressBar, "progress", targetProgress);
    anim.setInterpolator(new DecelerateInterpolator());
    anim.setDuration(300);
    anim.start();
}

without declarying the Property, but I don't like this approach that much.

A: Use this code it will help you.
Required Stuff:

*

*CustomProgressDialog

*anim

*drawble

*layout

1) CustomProgressDialog
package com.est.framework.android.ui;

import android.app.Dialog;
import android.content.Context;
import android.graphics.drawable.AnimationDrawable;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import com.sc.restclient.R;

// TODO: Auto-generated Javadoc
/**
 * The Class CustomProgressDialog.
 */
public class CustomProgressDialog extends Dialog {

    /**
     * Instantiates a new custom progress dialog.
     *
     * @param context the context
     * @param theme the theme
     */
    public CustomProgressDialog(Context context, int theme) {
        super(context, theme);
    }

    /* (non-Javadoc)
     * @see android.app.Dialog#onWindowFocusChanged(boolean)
     */
    @Override
    public void onWindowFocusChanged(boolean hasFocus) {
        ImageView imageView = (ImageView) findViewById(R.id.loadingImageView);
        AnimationDrawable yourAnimation = (AnimationDrawable) imageView.getBackground();
        yourAnimation.start();
    }

    /**
     * Creates the dialog.
     *
     * @param context the context
     * @param title the title
     * @param message the message
     * @return the custom progress dialog
     */
    public static CustomProgressDialog createDialog(Context context,String title) {
        CustomProgressDialog dialog = new CustomProgressDialog(context,android.R.style.Theme_Panel);
        dialog.setContentView(R.layout.dialogimg);

        int width = ViewGroup.LayoutParams.MATCH_PARENT;
        int height = ViewGroup.LayoutParams.MATCH_PARENT;
        dialog.getWindow().setLayout(width, height);

        TextView mloadMsg = (TextView)dialog.findViewById(R.id.loadMsg);
        if (title != null) {
            mloadMsg.setText(title);
        }else{
            mloadMsg.setVisibility(View.GONE);
        }
        dialog.getWindow().getAttributes().gravity = Gravity.CENTER;
        dialog.setCancelable(false);
        return dialog;
    }
}

2) Layout
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@drawable/pop_bg_bitmap"
    android:gravity="center"
    android:orientation="vertical" >

    <ImageView
        android:id="@+id/loadingImageView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_horizontal"
        android:background="@anim/loading_anim" />

    <TextView
        android:id="@+id/loadMsg"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:paddingTop="10dp"
        android:layout_gravity="center_horizontal"
        android:textColor="@color/btn_stroke_text"
        android:text="Loading..." />

</LinearLayout>

3) Anim
<?xml version="1.0" encoding="utf-8"?>
    <animation-list xmlns:android="http://schemas.android.com/apk/res/android"
    android:oneshot="false">
    <item android:drawable="@drawable/progress_1" android:duration="500" />
    <item android:drawable="@drawable/progress_2" android:duration="500" />
    <item android:drawable="@drawable/progress_3" android:duration="500" />
    <item android:drawable="@drawable/progress_4" android:duration="500" />

</animation-list>

4) Drawable
  <?xml version="1.0" encoding="utf-8"?>
<bitmap xmlns:android="http://schemas.android.com/apk/res/android"

    android:src="@drawable/fancybox_overlay"
    android:antialias="false"
    android:dither="true"
    android:tileMode="repeat"
    >
</bitmap>

Images :

*

*fancybox_overlay.png

*progress_1.png

*progress_2.png

*progress_3.png

*progress_4.png

A: You may use Handler and Runnable.
Make the Handler execute postDelayed(yourRunnable, DELAY); in a new method called void next() or something.
In the run() method of yourRunnable, increase the progress position by X amount (very little, like 1 percent or something depending on your desire), and invalidate() your progress bar. After the progress bar increases the progress position by X amount, invoke next() again, which will, execute yourRunnable.run() again, which will increase the progress position by X amount (or you may gradually increase amount using a little more complex math, instead of static X amount), and so goes the cycle until the progress fills up to your desired amount.
private ProgressAnimator animator;

@Override
public void onDraw(Canvas c) {
  super.onDraw(c);
  if (animator.started) {
    animator.next();
  }
}

public void animateProgress(float end, IAnimator.PostAnimationAction postPostAnimationAction) {
  animator.start(end, postPostAnimationAction);
}

private class ProgressAnimator {

  static final long DELAY = 10;

  // NOTE:
  // "MULTIPLY_FACTOR" IS OPTIONAL.
  // I USED THIS TO INCREASE THE PROGRESS SMOOTHLY AT
  // DYNAMIC SPEED, NOT AT STATIC SPEED.
  // IF YOU WANT STATIC INCREASE OF THE PROGRESS,
  // DONT USE THIS.
  static final float MULTIPLY_FACTOR = 0.2f;

  float endPosition;
  float remaining;
  boolean started;
  PostAnimationAction postAnimationAction;

  Handler handler = new Handler();
  Runnable runnable = new Runnable() {

    @Override
    public void run() {
      if (Math.abs(remaining) > 1) {
        raiseProgress(/* pass the current progress position here*/);
      } else {
        end();
      }
    }
  };

  /**
   * Constructor.
   *
   */
  ProgressSweepAnimator() {
    init();
  }

  @Override
  public void init() {
    started = false;
  }

  // NOTE:
  // "PostPostAnimationAction" IS OPTIONAL. I CREATED AND USED THIS
  // BECAUSE I WANTED TO DO SOMETHING AFTER THE PROGRESS
  // ANIMATION IS FINISHED.
  public void start(float endPosition, PostAnimationAction postPostAnimationAction) {
    this.endPosition = endPosition;
    start(postPostAnimationAction);
  }

  @Override
  public void start(PostAnimationAction postAnimationAction) {
    // Initialize status.
    started = true;
    this.postAnimationAction = postAnimationAction;

    // Find out the current progress.
    float start = /* get the current progress position here*/;

    remaining = end - start;
    raiseProgress(start);
  }

  @Override
  public void next() {
    handler.postDelayed(runnable, DELAY);
  }

  private void raiseProgress(float from) {
    float toRaise = remaining * MULTIPLY_FACTOR;
    remaining -= toRaise;

    raiseProgressTo(from + toRaise);
  }

  @Override
  public void end() {
    raiseTo(end);
    init();

    // NOTE:
    // THIS IS OPTIONAL BUT MAY BE VERY USEFUL, SO I
    // JUST LEFT THIS OUT HERE.
    // Notify the subscriber about the completion of the Burst action.
    postAnimationAction.onActionComplete();
  }
}

A: I don't know about the text rotation, but for slowly increasing the progress bar, you can try this one:
mProgressBar is a global progress bar variable which is holding the instance of your progress bar
mProgress is a global integer variable initially set to 0, to monitor the current level of your progress bar.
pSize is the amount you want to increase the progress bar from the current level.
pSleepTime is the speed you want the progress bar to fill up. I usually use 50.
private void setProgressBar(int pSize, int pSleepTime) throws InterruptedException {

    for(int i=0;i<pSize && mProgress<100;i++){
        mProgress++;
        Thread.sleep(pSleepTime);
        mProgressBar.setProgress(mProgress);
    }
}

A: Below is the code I am using for gradually filling circular progressbar-
xml
<ProgressBar
        android:id="@+id/progress"
        android:layout_width="100dp"
        android:layout_height="100dp"
        style="?android:attr/progressBarStyleHorizontal"
        android:indeterminate="false"
        android:layout_centerInParent="true"
        android:max="100"
        android:visibility="gone"
        android:progressDrawable="@drawable/background" />

background.xml
<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android" >
    <item android:id="@android:id/secondaryProgress">
        <shape
            android:innerRadiusRatio="3"
            android:shape="ring"
            android:useLevel="true"
            android:thicknessRatio="14.0">

            <gradient
                android:startColor="#999999"
                android:endColor="#999999"
                android:centerColor="#999999"
                android:type="sweep" />
        </shape>
    </item>
    <item android:id="@android:id/background">
        <shape
            android:innerRadiusRatio="3"
            android:shape="ring"
            android:thicknessRatio="14.0"
            android:useLevel="false" >
            <solid android:color="@color/white" />
        </shape>
    </item>
    <item android:id="@android:id/progress">
        <rotate
            android:fromDegrees="270"
            android:pivotX="50%"
            android:pivotY="50%"
            android:toDegrees="270" >
            <shape
                android:innerRadiusRatio="3"
                android:shape="ring"
                android:useLevel="true"
                android:thicknessRatio="14.0">
                <rotate
                    android:fromDegrees="0"
                    android:toDegrees="360"
                    android:pivotX="50%"
                    android:pivotY="50%" />
                <gradient
                    android:startColor="#8E58D4"
                    android:endColor="#8E58D4"
                    android:centerColor="#8E58D4"
                    android:type="sweep" />
            </shape>
        </rotate>
    </item>
</layer-list>

Code
 mProgressBar = (ProgressBar) activity.findViewById(R.id.progress);
 Resources res = getResources();
 Drawable drawable = res.getDrawable(R.drawable.background);
mProgressBar.setProgressDrawable(drawable);
ObjectAnimator animation = ObjectAnimator.ofInt(mProgressBar, "progress", 0, 100);
 animation.setDuration(10000);


text:
Q: Using two LIKE's in different columnName? I'm trying to make a search function in JTable in my program, but i got sql syntax error when i use this syntax. I've been read much question and answer in this problem and i never got the right syntax. Hope you can help me.
private void fillTable(String keyword) throws SQLException{
    if (!keyword.equals("")){
        try( Connection con = DriverManager.getConnection
                            ("jdbc:mysql://localhost:3306/inventory?zero"
                                    + "DateTimeBehavior=convertToNull","root","");
            Statement stmt = con.createStatement();
            ResultSet rs = stmt.executeQuery("SELECT * FROM basis"
                    + "WHERE barcode LIKE '%"+keyword+"%' or "
                    + "namaProduk LIKE '% "+keyword+" %'");
        ){
            jTable1.setModel(buildTableModel(rs));
        }
    }
    else fillTable();
}

A: You are missing 1 space between basis and WHERE (reason for the syntax error).
There is 1 unwanted space between % and your keyword (makes your query irrelevant).
private void fillTable(String keyword) throws SQLException{
    if (!keyword.equals("")){
        try( Connection con = DriverManager.getConnection
                            ("jdbc:mysql://localhost:3306/inventory?zero"
                                    + "DateTimeBehavior=convertToNull","root","");
            Statement stmt = con.createStatement();
            ResultSet rs = stmt.executeQuery("SELECT * FROM basis "
                    + "WHERE barcode LIKE '%"+keyword+"%' or "
                    + "namaProduk LIKE '%"+keyword+" %'");
        ){
            jTable1.setModel(buildTableModel(rs));
        }
    }
    else fillTable();
}

A: What I can see here is that there's a space missing behind the table name "basis". Generally, you should test your SQL statements manually via an existing DB client and then copy them into your code.
If you're open to tools that will ease your pain, try QueryDSL.


text:
Q: Parse into Properties with default values using Commons Digester <properties>
   <property name="p1">v1</property>
   <property name="p2">v2</property>
</properties>

I want to parse this into a Properties object with
{"p1"="v1", "p2"="v2"}. I was able to do this much using commons digester.
forPattern("properties").createObject()
        .ofType(Properties.class);
forPattern("properties/property")
        .callMethod("put").withParamCount(2)
        .withParamTypes(Object.class, Object.class).then()
        .callParam().fromAttribute("name").ofIndex(0).then()
        .callParam().ofIndex(1);

Additionally I also wanted to pass a defaults Properties object that I have. ie instead of new Properties(), I need to do new Properties(defaults) to create the Properties instance. I am aware of .usingConstructor(Properties.class).then() but did not find a way to pass an existing Properties object as an argument.
I am using v3.3.2.
Any help is greatly appreciated

A: Well I figured out this can be done using the FactoryCreateRule
class PropertiesFactory extends AbstractObjectCreationFactory<Properties> {

    Properties defaultProperties;

    public PropertiesFactory(Properties defaultProperties) {
        super();
        this.defaultProperties = defaultProperties;
    }

    @Override
    public Properties createObject(Attributes attributes) throws Exception {
        return new Properties(defaultProperties);
    }

}

...
...

forPattern("properties").factoryCreate()
        .usingFactory(new PropertiesFactory(defaultProperties));
forPattern("properties/property")
        .callMethod("put").withParamCount(2)
        .withParamTypes(Object.class, Object.class).then()
        .callParam().fromAttribute("name").ofIndex(0).then()
        .callParam().ofIndex(1);


text:
Q: How to start an android emulator in ubuntu 16.04? I have android sdk installed, I've looked up directions which say to run ~/android-sdk-linux/tools/android and then click on a tools menu, but there is no tools menu.
I've also tried downloading virtual machine manager, but when I started that emulator it said I needed to insert an sd card.
How do I start an android emulator on ubuntu 16.04?

A: Copy the name of the device that you want to run and then:
cd ~/Android/Sdk/tools && ./emulator -avd NAME_OF_YOUR_DEVICE

In my case:
cd ~/Android/Sdk/tools && ./emulator -avd Nexus_5X_API_23

A: For Ubuntu 16.04 you need to download few things first.
After installing Android Studio.
Goto Tools > Android > AVD Manager > Create new virtual device
follow standard installation for new virtual device.
After Creating virtual device
Goto Tools > Android > SDK Manager > SDK Tools and check Android emulator
Give it a try,if it still doesn't work you need add few libraries.
Goto terminal and execute below commands
 sudo apt-get install lib64stdc++6:i386
 sudo apt-get install mesa-utils
 cd YOURPATH/Android/Sdk/emulator/lib64
 mv libstdc++/ libstdc++.bak
 ln -s /usr/lib64/libstdc++.so.6  libstdc++
This should start your emulator.

A: Run
~/android-sdk-linux/tools/android avd

to start in AVD manager mode.

A: *

*Change directory using: cd /Path/to/Sdk/tools

*Start emulator using: sudo ./emulator -avd NAME_OF_YOUR_DEVICE


text:
Q: calculation of variance Hi I have a question regarding calculation of variance of survey results.
Consider the following example. If 5 (x) people answered a survey which consists of 3 (y) yes (1) or no (2) questions. You would have something like:
    Y1 y2 y3

X1  1. 0. 0

X2  0. 1. 1

X3. 1. 1. 1

X4. 0. 1. 1

X5. 0. 0. 1

If I calculate a total score by calculating the proportion of yes (1) for each respondent and then average this across all respondent. In this case I will calculate the proportion for respondent x1, x2,...,x5. Then take the sum of all and divide by 5. If I calculate a variance for this total, I am wondering if I have to take into consideration the within respondent variance? Or can I just calculate the across respondent variance as the total variance??
If anyone can help that would be great. Thank you.

A: You do not have to take the within respondent variance into account.  In many examples, multiple questions like this indicate strength of agreement with the concept, and you can regard the true concept score as consisting of 0 (all 0s) to 3 (all 1s).


text:
Q: Upload Javascript file using variables EDIT:
I do not want to save to a text file.... I want the user to be able to select their own file and use the variables within that file.
I would like to have the user upload their own "settings.js" file and then the page use the variables once loaded.
How would I change my code to reflect this?
At present I have the following javascript file and HTML code:
Javascript File: settings.js
var myVariable = 6000;

HTML file: index.html

<!DOCTYPE html>

    <meta charset="UTF-8">
    <title>Load Javascript file</title>

Please help.

A: This code will run javascript stored in your JS file. Use FileReader() to read file as text, and use eval(content); to execute that code. If you can execute JavaScript you can do anything you want. Use only variables, or anything else.

var fileInput = document.getElementById('fileInput');
var fileDisplayArea = document.getElementById('fileDisplayArea');

fileInput.addEventListener('change', function(e) {
    var file = fileInput.files[0];
    var textType = /text.*/;

    if (file.type.match(textType)) {
        var reader = new FileReader();

        reader.onload = function(e) {
            var content = reader.result;
            //Here the content has been read successfuly
            eval(content);

        }

        reader.readAsText(file);
    } else {
        document.innerText = "File not supported!"
    }
});
<input type="file" id="fileInput">

A: something like this maybe

document.getElementById("settings").addEventListener("change", function(){
if(this.files[0] && this.files[0].type == "text/javascript"){
     var reader = new FileReader();
      reader.onload = function (e) {
         var settings = e.target.result.split("data:text/javascript;base64,")[1];
         eval(atob(settings));

         //use the loaded var's
         document.getElementById("result").innerText = myVariable;
      }
     reader.readAsDataURL(this.files[0]);
    }
});
<input type="file" id="settings">

A: Here is a full working code for you.
It will read file and print it as text for debugging on the screen and will add the file as script file to the page as well.

<!DOCTYPE HTML>

    <input type='file' id='scriptFile'>
    <input type='button' value='Load' onclick='loadScript();'>


text:
Q: changing only the operator in python code I have a piece of code that is repeating with only a math operator changing, i.e:
x1=a+b
x2=a-b
x3=a*b
x4=a/b

is there a way to write a function that receives the operator and only applies that and thus eliminate the need to write almost the same code many times?
hopefully, something like:
def operator_modularity(op):
    return a op b

operator_modularity(+)

A: def operator_modularity(op):
    return eval(f"10 {op} 10")

operator_modularity("+")

A: A great thing about Python is that you can keep pointers to methods.
Another cool thing is the built in operators module that gives you method-call shaped references to said operators. So to do that, you could run the following:
def foo(a, b):
     operators_to_run = [operator.add, operator.sub, operator.mul]
     for op in operators_to_run:
         print(op(a,b))

There's no code repetition, and you get all the operators' results sequentially :)
I hope that answers your question.

A: I guess you could write some code like
def all_four_operations(num1, num2):
    return (num1 + num2, num1 - num2, num1 * num2, num1 / num2)

result_array = all_four_operations(1, 7)
x1 = result_array[0] # x1 = 8
x2 = result_array[1] # x2 = -6
x3 = result_array[2] # x3 = 7
x4 = result_array[3] # x4 = 0.14


text:
Q: Modify prop value before TypeScript check This is the object I've got:
const translations = {
    msg_hello: 'Hello',
    msg_bye: 'Bye'
}

Also I have a function that looks like this:
const generateTranslation = (partialKey: string): keyof typeof translations {
    return `msg_${partialKey}`;
}

is there a way to check if the generated translation key will be valid? For example:
generateTranslation('hello'); // good
generateTranslation('no'); // bad

A: First of all, you need extract allowed values from translations. In order to do that, you need to make translations immutable.
const translations = {
    msg_hello: 'Hello',
    msg_bye: 'Bye'
} as const;

Then, for the sake of readability, you can create helper type:
type Translations = typeof translations;

Thanks to template literals, you can infer the string which goes after underscore _:
type GetSuffix<T> = keyof T extends `msg_${infer Suffix}` ? Suffix : never;

type Test = GetSuffix<Translations> // "hello" | "bye"

Now, you can apply the restiction:

const generateTranslation = <
    Key extends GetSuffix<Translations>
>(partialKey: Key): `msg_${Key}` => `msg_${partialKey}`

Be aware that I have infered partialKey with help of GetSuffix<Translations> which helped me to apply explicit return type msg_${Key}.
WHole example:
const translations = {
    msg_hello: 'Hello',
    msg_bye: 'Bye'
} as const;

type Translations = typeof translations;

type GetSuffix<T> = keyof T extends `msg_${infer Suffix}` ? Suffix : never

type Test = GetSuffix<Translations> // "hello" | "bye"

const generateTranslation = <
    Key extends GetSuffix<Translations>
>(partialKey: Key): `msg_${Key}` => `msg_${partialKey}`

const result = generateTranslation('hello'); // good --->  "msg_hello"
generateTranslation('no'); // bad

Playground

A: I don't think there is an automatic way to do this, for dynamic strings like that where keyof won't retrieve them. But you could manually create a type that is a union of the valid values, and require that the partialKey argument be of that type:
const translations = {
    msg_hello: 'Hello',
    msg_bye: 'Bye'
};

type validPartialKeys = 'hello' | 'bye';

const generateTranslation = function (partialKey: validPartialKeys): keyof typeof translations {
    return `msg_${partialKey}`;
}

generateTranslation('hello'); // good
generateTranslation('no'); // bad


text:
Q: FormatMessage Fails with error code 317 When I executed the following code piece it fails with error code 317. How can solve the issue? We are using Unicode Character Set for the project
  char* pszMessgeBuffer = NULL;
  FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER |
        FORMAT_MESSAGE_FROM_SYSTEM |
        FORMAT_MESSAGE_IGNORE_INSERTS,
        NULL,
        dwErrorId,
        0, // Default language
        (LPTSTR) &pszMessgeBuffer,
        0,
        NULL )

A: Using the error code lookup tool from Visual Studio, 317 is described as

The system cannot find message text
  for message number 0x%1 in the message
  file for %2.

This means that a message description does not exist in the system for the previous error code. The MSDN documentation for FormatMessage with flag FORMAT_MESSAGE_FROM_SYSTEM states that:

Not all Windows Embedded CE–based
  devices will contain the system
  message-table resources. This is a
  selectable part of the Windows
  Embedded CE operating system and is
  often removed to conserve space.

A: I think error 317 is the result of using Win32 function LsaNtStatusToWinError(87), where winstatus 87 means 'The parameter is incorrect'


text:
Q: Minimum area bounded between two curves What is the minimum area bounded between the curve $ y = \dfrac{x^2}4 $ and $y=ax+9$, where $a$ is some real number.
I tried to use application of derivative but not able to reach a final solution.

A: The line $y=ax+9$ will always lie above the parabola $y=\frac{x^2}4$, intersecting when
$$ax+9=\frac{x^2}4\implies x^2-4ax-36=0$$
at two points, $x_1$ and $x_2$, both dependent on $a$. (It's given that $a\in\mathbb R$, so the line is never vertical, hence there are two points of intersection.)
The area between the curves is then a function of $a$,
$$\operatorname{Area}(a)=\int_{x_1(a)}^{x_2(a)}\left((ax+9)-\frac{x^2}4\right)\,\mathrm dx$$
which can be minimized by applying the fundamental theorem of calculus. Can you continue from here?


text:
Q: spring boot adding Manifest entry key respresenting build version in maven pom.xml What I would like to do is be able to put the version of my build into the maven command line and have that build version arrive in the MANIFEST.MF file. I was hoping to use the spring-boot-maven-plugin to do so.
<plugin>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-maven-plugin</artifactId>
  <configuration>
    <!--put something here from the command line? -->
  </configuration>
</plugin>

I'm sorry that I haven't got a broken example for you to troubleshoot, but I can't seem to find any documentation on this the plugin usage examples that I have found don't cover anything like this.


text:
Q: Find the most frequent number in a 3d list I can't find a way to show the most frequent number in this list
a = [1,2,4,5,6,7,15,16,19,23,24,26,27,28,29,30,31,33,36,37,38,39,40,41,42,43,44,45,47,48,49,50,51,52,56,57,58,60]

b = [1,3,4,5,6,8,9,10,15,16,17,18,20,21,22,24,26,28,29,31,32,33,36,37,38,40,41,43,44,47,48,50,52,53,54,56,57,58,60]

c = [2,3,5,6,8,9,12,13,17,19,20,23,25,26,27,28,29,30,31,33,34,35,36,37,40,44,45,47,48,52,53,54,55,56,57,58,60]

d = [2,5,7,9,11,12,13,14,16,18,20,22,23,26,29,30,33,34,36,38,40,41,42,43,44,46,47,49,50,51,53,56,57,58,60]

list_1 = [a,b]
list_2 = [c,d]
lists = [list_1, list_2]

I have tried the collections library with the most_common() funtion but it does't seem to work. Same happens with numpy arrays.
It would be perfect if I could get the top 10 most common number too.
The reason for the list to be multi-dimensional is for easy comparison between months
Jan_22 = [jan_01, jan_02, jan_03, jan_04]
Fev_22 = [fev_01, fev_02, fev_03, fev_04]
months = [Fev_22, Jan_22]

Each month has 4 data sets, making those lists allows me to compare big chunks of data, Top 10 most common values from 2021, most common number in jan, fev, mar, April, may ,jun. Would make it easier and clear
Thanks

A: Maybe I don't fully understand your question, but I don't understand why the list needs to be multi-dimensional if you only want to know the frequency of a given value.
import pandas as pd

a = [1,2,4,5,6,7,15,16,19,23,24,26,27,28,29,30,31,33,36,37,38,39,40,41,42,43,44,45,47,48,49,50,51,52,56,57,58,60]

b = [1,3,4,5,6,8,9,10,15,16,17,18,20,21,22,24,26,28,29,31,32,33,36,37,38,40,41,43,44,47,48,50,52,53,54,56,57,58,60]

c = [2,3,5,6,8,9,12,13,17,19,20,23,25,26,27,28,29,30,31,33,34,35,36,37,40,44,45,47,48,52,53,54,55,56,57,58,60]

d = [2,5,7,9,11,12,13,14,16,18,20,22,23,26,29,30,33,34,36,38,40,41,42,43,44,46,47,49,50,51,53,56,57,58,60]

values = pd.Series(a + b + c + d)
print(values.value_counts().head(10))
print(values.value_counts().head(10).index.to_list())

A: I dont get why are you adding up lists in each step to get a 3D element, you could just use arrays or smth like that, but here is a function that does what you want in a 3d list (returns the x most common elements in your 3d list ,a.k.a list of lists):
import numpy as np

arr = [[1,2,4,5,6,7,15,16,19,23,24,26,27,28,29,30,31,33,36,37,38,39,40,41,42,43,44,45,47,48,49,50,51,52,56,57,58,60],
    [1,3,4,5,6,8,9,10,15,16,17,18,20,21,22,24,26,28,29,31,32,33,36,37,38,40,41,43,44,47,48,50,52,53,54,56,57,58,60],
    [2,3,5,6,8,9,12,13,17,19,20,23,25,26,27,28,29,30,31,33,34,35,36,37,40,44,45,47,48,52,53,54,55,56,57,58,60],
    [2,5,7,9,11,12,13,14,16,18,20,22,23,26,29,30,33,34,36,38,40,41,42,43,44,46,47,49,50,51,53,56,57,58,60]]

def x_most_common(arr, x):
    l =  [el  for l in arr for el in l]
    output = list(set([(el, l.count(el)) for el in l]))
    output.sort(key= lambda i: i[1], reverse=True)
    return output[:x]

# test:
print(x_most_common(arr, 5))

output:
[(56, 4), (36, 4), (47, 4), (58, 4), (5, 4)]


text:
Q: How do I get my dwarfs inside? How do I order everyone inside when I'm being attacked?

A: You need to define a burrow for the safe zone, and a civilian alert that restricts movement to it.

*

*To create the burrow

*

*Press w to go to the burrows screen

*Press a to add a new burrow

*Size the burrow (remember, a  burrow is 3d)

*Choose a name, color, etc

*To create a new alert

*

*Press m to go to the military screen

*Press a to go to the alerts screen

*Press c to create a new alert

*Name it with N

*Now move the cursor to the far right column, which should have the burrow you just created, and hit enter to associate that burrow with your new alert. You'll see a green A next to the burrow when you have that alert selected.

*To activate the alert (as the civilian alert)

*

*Press m to go to the military screen

*Press a to go to the alerts screen

*Press enter while the alert is highlighted.

*To deactivate the alert

*

*Press m to go to the military screen

*Press a to go to the alerts screen

*Select the 'Inactive' alert state, and press enter

*

*See also:

*

*Military Interface

*Scheduling

*Civilian Alert Guide


text:
Q: How to make stata-style marginal effects plots for interactions in multinomial logit models in R? I would like to plot the marginal effects of an interaction in a multinomial logit model (nnet::multinom) according to the example below from the margins package for R, as explained here.
The particular graph I would like to emulate looks like this:

The corresponding code is:
cplot(mod4, x = "wt", dx = "drat", what = "effect", se.type = "shade")

Whereby
mod4 <- glm(am ~ wt*drat, data = mtcars, family = binomial)

Hence, this is a graph in which the marginal effects of one of the interacted variables is displayed on the y-axis and the other interacted variable on the x-axis. It's different from the more typical way of visualizing interaction effects where you'd keep one of the interacted variables constant at a number of different levels (e.g., -SD, mean, SD) and get as many lines in the graph as levels.
Now, the problem is that, when I try this on my nnet::multinom model, I get the following error message:

Error in cplot.multinom(model_2, x = "x1", dx = "x2",  :
Displaying marginal effects is not currently supported for 'polr' models!

So, apparently R's margins package does not seem to support multinomial logit models. Is there another way to make a plot exactly like the one above for a multinomial model in R? There would be a separate facet for each category of the dependent variable like in the example below, which was made in stata:


text:
Q: How to interpolate a string that was sent as an argument? I have limited access to the filesystem, and I want to set up universal notification handler call like that:
notificator.sh "apples" "oranges" "There were $(1) and $(2) in the basket"

notificator.sh contents:
#!/bin/sh
echo $3

And get output looking like:
"There were apples and oranges in the basket"

Is it possible and how? I'd prefer if it was a builtin sh solution.
I'm actually trying to send the result string ($3) as a message to the telegram bot via curl post param, but tried to simplify the situation.

A: With some changes to your $3, we can make this work easily.
First, let's define $1, $2, and $3:
$ set -- "apples" "oranges" 'There were ${one} and ${two} in the basket'

Now, let's force substitutions into $3:
$ one=$1 two=$2 envsubst <<<"$3"
There were apples and oranges in the basket

Notes:

*

*$(1) attempts to run a command named 1 and will likely generate an error even before your script runs.  Use ${var} instead.

*To get this method to work, we needed to rename the variables in $3.

*envsubst is part of the GNU gettext-base package and should be available by default of Linux distributions.
Hat tip to Charles Duffy.
In script form
Consider this script:
$ cat script.sh
#!/bin/sh
echo "$3" | one=$1 two=$2 envsubst

We can execute the above:
$ sh script.sh "apples" "oranges" 'There were ${one} and ${two} in the basket'
There were apples and oranges in the basket

As an alternative (hat tip  again to Charles Duffy), we can use a here-doc:
$ cat script2.sh
#!/bin/sh
one=$1 two=$2 envsubst <<EOF
$3
EOF

Running this version:
$ sh script2.sh "apples" "oranges" 'There were ${one} and ${two} in the basket'
There were apples and oranges in the basket

Alternative
The following script does not require envsubst:
$ cat script3.sh
#!/bin/sh
echo "$3" | awk '{gsub(/\$\{1\}/, a); gsub(/\$\{2\}/, b)} 1' a=$1 b=$2

Running this script with our arguments, we find:
$ sh script3.sh "apples" "oranges" 'There were ${1} and ${2} in the basket'
There were apples and oranges in the basket
$ sh script3.sh "apples" "oranges" 'There were ${1} and ${2} in the basket'
There were apples and oranges in the basket


text:
Q: Add a node above matrix column I am trying to put symbols above and the columns of a matrix and also to the left of its rows. The following working example is basically, what I want, except, that the symbols are within the brackets. I would like to have them outside.
Is there any way to accomplish this?
\documentclass{article}
\usepackage{pgfplots}
\usepackage{tikz}
\usetikzlibrary{matrix,shapes,positioning}

\begin{document}
    $A=$%
    \begin{tikzpicture}[baseline=(A.center)]
    \matrix (A) [matrix of math nodes, ampersand replacement=\&,
    left delimiter=(,right delimiter=)]
    { {} \& {}  \& {}   \& {}   \& {} \\
      {} \& 1   \& 2    \& 17   \& 3 \\
      {} \& 4   \& 1    \& 24   \& 1 \\
      {} \& 0   \& 0    \& 2    \& -0.9 \\
      {} \& 0   \& 7    \& -0.95 \& 2 \\
    };

    \draw [black]  (A-1-2.west)  to (A-1-2.east);
    \draw [black,dashed]  (A-1-3.west)  to (A-1-3.east);
    \draw [black]  (A-1-4.west)--  plot[mark=square*, mark options={fill=black}] (A-1-4.center) -- (A-1-4.east);
    \draw [black]  (A-1-5.west)--  plot[mark=triangle*, mark options={fill=black}] (A-1-5.center) -- (A-1-5.east);

    \draw [black]  (A-2-1.west)  to (A-2-1.east);
    \draw [black,dashed]  (A-3-1.west)  to (A-3-1.east);
    \draw [black]  (A-4-1.west)--  plot[mark=square*, mark options={fill=black}] (A-4-1.center) -- (A-4-1.east);
    \draw [black]  (A-5-1.west)--  plot[mark=triangle*, mark options={fill=black}] (A-5-1.center) -- (A-5-1.east);
    \end{tikzpicture}%
\end{document}

A: You can use the anchors of the matrix nodes and some maths to get the correct points outside of the brackets. You could use the following for instance:
\documentclass{article}
\usepackage{pgfplots}
\usepackage{tikz}
\usetikzlibrary{matrix,shapes,positioning,calc}
\def\hoffset{1}
\def\voffset{.5}

\begin{document}
    $A=$%
    \begin{tikzpicture}[baseline=(A.center)]
    \matrix (A) [matrix of math nodes, ampersand replacement=\&,
    left delimiter=(,right delimiter=)]
    { 1   \& 2    \& 17   \& 3 \\
      4   \& 1    \& 24   \& 1 \\
      0   \& 0    \& 2    \& -0.9 \\
      0   \& 7    \& -0.95 \& 2 \\
    };
    \draw [black]  ($(A-1-1.west)+(-\hoffset,0)$)  to ($(A-1-1.east)+(-\hoffset,0)$);
    \draw [black,dashed]  ($(A-2-1.west)+(-\hoffset,0)$)  to ($(A-2-1.east)+(-\hoffset,0)$);
    \coordinate (A31) at ($(A-3-1.center)+(-\hoffset,0)$);
    \coordinate (A41) at ($(A-4-1.center)+(-\hoffset,0)$);
    \draw [black]  ($(A-3-1.west)+(-\hoffset,0)$)--  plot[mark=square*, mark options={fill=black}] (A31)  -- ($(A-3-1.east)+(-\hoffset,0)$);
    \draw [black]  ($(A-4-1.west)+(-\hoffset,0)$)--  plot[mark=triangle*, mark options={fill=black}] (A41) -- ($(A-4-1.east)+(-\hoffset,0)$);

    \draw [black]  ($(A-1-1.west)+(0,\voffset)$)  to ($(A-1-1.east)+(0,\voffset)$);
    \draw [black,dashed]  ($(A-1-2.west)+(.1,\voffset)$)  to ($(A-1-2.east)+(0,\voffset)$);
    \coordinate (A13) at ($(A-1-3.center)+(0,\voffset)$);
    \coordinate (A14) at ($(A-1-4.center)+(0,\voffset)$);
    \draw [black]  ($(A-1-3.west)+(0,\voffset)$)--  plot[mark=square*, mark options={fill=black}] (A13) -- ($(A-1-3.east)+(0,\voffset)$);
    \draw [black]  ($(A-1-4.west)+(0,\voffset)$)--  plot[mark=triangle*, mark options={fill=black}] (A14) -- ($(A-1-4.east)+(0,\voffset)$);
    \end{tikzpicture}%
\end{document}

You could of course define the coordinates for the positions outside of the matrix once and then simply use this. If you need this kind of thing more often that might be a little cleaner. It should be pretty straightforward to modify this code to suit your needs.

A: I update one of my examples about tikz and matrix. You only need to use some nodes :
 here A-1-1.west and A-5-1.west and you have several possibilities to place your symbols. I used xshiftto do that for the rows but it's the same thing for columns with yshift
   \node [xshift=-1.5 cm] at  (A-1-1.west)   {$\longrightarrow$ first row};
   \node [xshift=-1.5 cm] at  (A-5-1.west)   {$\longrightarrow$ last row};

\documentclass[]{article}
\usepackage[utf8]{inputenc}
\usepackage[upright]{fourier}
\usepackage{tikz}
\usetikzlibrary{matrix,arrows,decorations.pathmorphing}
\usepackage{fullpage}
\begin{document}

\begin{tikzpicture}[>=latex]
% unit
\newcommand{\myunit}{1.2 cm}
% the styles
\tikzset{node style sp/.style={draw,circle,minimum size=\myunit}}
\tikzset{node style ge/.style={circle,minimum size=\myunit}}
\tikzset{arrow style mul/.style={draw,sloped,midway,fill=white}}
\tikzset{arrow style plus/.style={midway,sloped,fill=white}}
% defintion of matrices
\matrix (A) [matrix of math nodes,%
             nodes = {node style ge},%
             left delimiter  = (,%
             right delimiter = )] at (0,0)
{%
  a_{11} &\ldots & a_{1k} & \ldots & a_{1p}  \\
    \vdots & \ddots & \vdots & \vdots & \vdots \\
  \node[node style sp] {a_{i1}};& \ldots%
         & \node[node style sp] {a_{ik}};%
                  & \ldots%
                           & \node[node style sp] {a_{ip}}; \\
  \vdots & \vdots& \vdots & \ddots & \vdots  \\
  a_{n1}& \ldots & a_{nk} & \ldots & a_{np}  \\
};
\node [draw,below] at (A.south) { $A$ : \textcolor{red}{$n$ rows} $p$ columns};
\matrix (B) [matrix of math nodes,%
             nodes = {node style ge},%
             left delimiter  = (,%
             right delimiter =)] at (7*\myunit,7*\myunit)
{%
  b_{11} &  \ldots& \node[node style sp] {b_{1j}};%
                  & \ldots & b_{1q}  \\
  \vdots& \ddots & \vdots & \vdots & \vdots \\
  b_{k1} &  \ldots& \node[node style sp] {b_{kj}};%
                  & \ldots & b_{kq}  \\
  \vdots& \vdots & \vdots & \ddots & \vdots \\
  b_{p1} &  \ldots& \node[node style sp] {b_{pj}};%
                  & \ldots & b_{pq}  \\
};
\node [draw,above] at (B.north) { $B$ : $p$ rows \textcolor{red}{$q$ columns}};
% matrice résultat
\matrix (C) [matrix of math nodes,%
             nodes = {node style ge},%
             left delimiter  = (,%
             right delimiter = )] at (7*\myunit,0)
{%
  c_{11} & \ldots& c_{1j} & \ldots & c_{1q} \\
  \vdots& \ddots & \vdots & \vdots & \vdots \\
    c_{i1}& \ldots & \node[node style sp,red] {c_{ij}};%
                  & \ldots & c_{iq} \\
  \vdots& \vdots & \vdots & \ddots & \vdots \\
  c_{n1}& \ldots & c_{nk} & \ldots & c_{nq} \\
};
\node [draw,below] at (C.south) {$ C=A\times B$ : \textcolor{red}{$n$ rows}  \textcolor{red}{$q$ columns}};
% arrows
\draw[blue] (A-3-1.north) -- (C-3-3.north);
\draw[blue] (A-3-1.south) -- (C-3-3.south);
\draw[blue] (B-1-3.west)  -- (C-3-3.west);
\draw[blue] (B-1-3.east)  -- (C-3-3.east);
\draw[<->,red](A-3-1) to[in=180,out=90]
      node[arrow style mul] (x) {$a_{i1}\times b_{1j}$} (B-1-3) ;
\draw[<->,red](A-3-3) to[in=180,out=90]%
      node[arrow style mul] (y) {$a_{ik}\times b_{kj}$} (B-3-3);
\draw[<->,red](A-3-5) to[in=180,out=90]%
      node[arrow style mul] (z) {$a_{ip}\times b_{pj}$} (B-5-3);
\draw[red,->] (x) to node[arrow style plus] {$+\raisebox{.5ex}{\ldots}+$} (y)%
                  to node[arrow style plus] {$+\raisebox{.5ex}{\ldots}+$} (z);
                  %
                  % to (C-3-3.north west);
\draw[->,red,decorate,decoration=zigzag] (z) -- (C-3-3.north west);
\node [xshift=-1.5 cm] at  (A-1-1.west)   {$\longrightarrow$ first row};
\node [xshift=-1.5 cm] at  (A-5-1.west)   {$\longrightarrow$ last row};
\end{tikzpicture}
\end{document}

A: I wanted to learn how to use package blkarray and here you have the result. Your example just need TiKZ (which is already loaded by pgfplots) for drawing mark symbols because matrix is defined with a blockarray environment.
\documentclass{article}
\usepackage{pgfplots}
\usepackage{blkarray}

\begin{document}
\[A=
\begin{blockarray}{ccccc}
&\tikz{\draw (0,0)--++(0.5,0);}&\tikz{\draw[dashed] (0,0)--++(0.5,0);}&\tikz{\draw (0,0)--++(0.5,0) plot[mark=square*,mark options={fill=black}] (0.25,0);}&\tikz{\draw (0,0)--++(0.5,0) plot[mark=triangle*,mark options={fill=black}] (0.25,0);}\\
\begin{block}{c(cccc)}
\tikz{\draw (0,0)--++(0.5,0);}&1&2&17&3\\
\tikz{\draw[dashed] (0,0)--++(0.5,0);}&4&1&24&1\\
\tikz{\draw (0,0)--++(0.5,0) plot[mark=square*,mark options={fill=black}] (0.25,0);}&0&0&2&-0.9\\
\tikz{\draw (0,0)--++(0.5,0) plot[mark=triangle*,mark options={fill=black}] (0.25,0);}&0&7&-0.95&2\\
\end{block}
\end{blockarray}
\]
\end{document}


text:
Q: MariaDB JSON Functions with Arrays I have JSON arrays stored as strings in a MariaDB table. I want to return the rows when certain key-values are present anywhere in the array.
I performed the following test....
set @json='[{"name":"Albert","state":"IL"},{"name":"John","state":"CA"}]'

Executed the following query ...
select json_value(@json,'$[0].name')='Albert'

It got me the desired result which is...
1

Even the following query also gave me the same result(may be '*' is treated as the first element)...
select json_value(@json,'$[*].name')='Albert'

But when I provide the second name("John") in the condition, I do not get any result...
select json_value(@json,'$[*].name')='John'

Result...
0

So my observation is that when we provide the array index the "json_value" function is able to return the desired result.
Is there a way where I can avoid specifying the array index and search the desired key-value?

A: As commented by @dbfiddle I tried using JSON_SEARCH function.
Here is what I tried to get the desired result.
create table label_test(labels VARCHAR(1000));

insert into label_test values ('[{"name":"Albert","state":"IL"},{"name":"John","state":"CA"}]');

select * from label_test where JSON_SEARCH(labels,'all','John') like '"$[%].name"';

The result is the whole row as expected.
[{"name":"Albert","state":"IL"},{"name":"John","state":"CA"}]


text:
Q: Implementing hook_user_insert doesn't login my user I'm trying to forward the users to a specific page after they create their account, but when they get there, they are not logged in.
function mymodule_user_insert(&$edit, $account, $category) {
  drupal_goto("node/3");
}

Should I add something to make sure the user gets logged in, after his account is created?

A: hook_user_insert() is invoked after a user account is being inserted in the database table, which would happen when one of administrator users creates a user account from the administrative pages, or when a module programmatically create a user account.
The purpose of the hook is to save custom data that the module associates with the user account. Calling drupal_goto() in that case is wrong.
To redirect a user after registration, you could implement code similar to the following one. ("mymodule" is just an example of short name for a module; change it to the short name of the module you are using/creating.)
function mymodule_form_ user_register_form_alter(&$form, &$form_state) {
  // Add a form submission handler to the registration form.
  $form['#submit'][] = 'mymodule_user_register_submit';
}

function mymodule_user_register_submit($form, &$form_state) {
  $form_state['redirect'] = 'where you want to redirect the user';
}

Consider that when this code is executed, the users still need to log in, and (depending on the site settings) they could need to first receive the email that Drupal sends to the users, when it is set to first verify the email address reported by the registering users.
If you want to redirect the user after the login, you should implement hook_user_login(), but the user needs to first log in.

A: That's not the place to do it, as that should only be used to post custom additions to the database, see the documentation here.
The easiest way to do it would be to use the login destination module as that is already tried and tested and does what you are after. To see how they do it take a peek at the source.
http://drupal.org/project/login_destination
Alternatively you should add your code to hook_user_login


text:
Q: Django ValueError: I/O operation on closed file, after using clean_() on FileField I am attempting to create a page with a formset to allow the user to upload CSV files, the contents of which I want to validate before saving.
I have a formset where each form has some CharFields pre-populated and then a FileField.
I want to validate the contents of the CSV before I save it to a location on the disk, as they must be a very specific format. My current code performs this validation in a custom clean_<fieldname>() function for the FileField in the form.
The validation all appears to work, however, when I attempt to write the file to the intended location on the disk I get a ValueError: I/O operation on closed file.
I am using Python 3.4.3 with Django 1.11 and my code is below.
I've only included the function which is giving the error in csv_funcs.py, specifically on the call to csv_f.chunks which tries to do self.file.seek(0).
The other functions in that file which perform validation don't explicitly call close() on the file object anywhere, although they do use csv.DictReader on it after which I always seek(0) to return to the start of the file.
forms.py
class CsvUploadForm(forms.Form):
    nom = forms.CharField(widget=forms.HiddenInput())
    machine = forms.CharField(widget=forms.HiddenInput())

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.fields['id'] = forms.CharField(widget=forms.TextInput(attrs={'readonly':'readonly'}))
        self.fields['library'] = forms.CharField(widget=forms.TextInput(attrs={'readonly':'readonly'}))
        self.fields['filepath'] = forms.FileField(widget=forms.FileInput(attrs={'accept': ".csv"}), required=False)
        self.metadata = defaultdict()

    def clean_filepath(self):
        csv_binary = self.cleaned_data.get('filepath')
        ## If they supplied a filepath, do some validation
        if csv_binary is not None:
            csv_file = TextIOWrapper(csv_binary, encoding='ASCII')
            version = csv_funcs._get_csv_version(csv_file)
            if version == bc_version.unknown:
                 raise forms.ValidationError("The CSV version could not be determined!")
            expected_name = csv_funcs._get_expected_name(self.cleaned_data['nom'], self.cleaned_data['id'], self.cleaned_data['library'], version)
            if csv_file.name != expected_name:
                self.add_error('filepath', forms.ValidationError("Filename did not match the expected name for this format! Expected {} but got {}".format(expected_name, csv_file.name)))
            self.metadata['version'] = version
            ## DO SOME VALIDATION
            content_info = csv_funcs._validate_contents(csv_file, version)
            self.metadata['num_bc'] = content_info[0]
            self.metadata['type'] = content_info[1]
            csv_binary.seek(0)

        return csv_binary

views.py
def process_uploads(request):
    UploadFormset = formset_factory(CsvUploadForm, extra=0)
    if request.method == "POST":
        uploads = UploadFormset(request.POST, request.FILES)
        if uploads.is_valid():
            result_list = []
            for u in uploads:
                uclean = u.cleaned_data
                if uclean.get('filepath'):
                    csv_funcs._write_csv(uclean['filepath']), u.metadata['version'], uclean['nom'], uclean['machine'])
                    result = 'SAVED: {}_{}_{}_{}_{}_{}_{}_{}'.format(uclean['nom'], uclean['id'], uclean['machine'], uclean['library'], uclean['filepath'].name, u.metadata['version'], u.metadata['num_bc'], u.metadata['type'])
                else:
                    result = 'No file provided for {}_{}_{}_{}'.format(uclean['nom'], uclean['id'], uclean['machine'], uclean['library'])
                result_list.append(result)
            return render(request, 'results.html', {'results': result_list})
        else:
            return render(request, 'ids.html', {'formset': uploads, 'nom': 'FAIL', 'machine': 'FAIL'})

csv_funcs.py
def _write_csv(csv_f, version, nom, machine):
    output_path = os.path.expanduser(csv_dirs[version].substitute(nom=nom, machine=machine))
    os.makedirs(output_path, exist_ok=True)
    with open(os.path.join(output_path, csv_f.name), "wb") as f_out:
        for chunk in csv_f.chunks():
            f_out.write(chunk)

Trace
Traceback:

File "/home/admin/.virtualenvs/barcode_uploader/lib/python3.4/site-packages/django/core/handlers/exception.py" in inner
  41.             response = get_response(request)

File "/home/admin/.virtualenvs/barcode_uploader/lib/python3.4/site-packages/django/core/handlers/base.py" in _get_response
  187.                 response = self.process_exception_by_middleware(e, request)

File "/home/admin/.virtualenvs/barcode_uploader/lib/python3.4/site-packages/django/core/handlers/base.py" in _get_response
  185.                 response = wrapped_callback(request, *callback_args, **callback_kwargs)

File "/home/admin/project_dev/barcode_uploader/upload_app/views.py" in process_uploads
  47.                   csv_funcs._write_csv(uclean['filepath']), u.metadata['version'], uclean['nom'], uclean['machine'])

File "/home/admin/project_dev/barcode_uploader/upload_app/csv_funcs.py" in _write_csv
  28.       for chunk in csv_f.chunks():

File "/home/admin/.virtualenvs/barcode_uploader/lib/python3.4/site-packages/django/core/files/uploadedfile.py" in chunks
  96.         self.file.seek(0)

Exception Type: ValueError at /upload_app/uploaded/
Exception Value: I/O operation on closed file.

Potential Solution
I think I have isolated the call to TextIOWrapper as the culprit. I have implemented the Python3 work-around from this question and it now successfully saves, although I have no idea if avoiding the GC in this way is problematic.


text:
Q: HTTPS background images using ip address? I have a website using CodeIgniter (an older version that has been upgraded over time by several developers). The site works 100% fine using HTTP (my test environment can't use HTTPS) but when I switch to HTTPS all of the CSS background images switch to using the IP Address?

In every page, I include the following snippet for ease of use, but it is producing the same IP address so I figured the problem is in the site_url() function - image_url() just adds to site_url().
<script type="text/javascript">
    var BASE_URL = '<?= site_url() ?>'; // http://555.555.55.555/
    var IMG_PATH = '<?= image_url() ?>'; // http://555.555.55.555/images/main
</script>

I don't have a 'live test environment' to test changes and am stumped. I believe the below overridden function force_ssl() may hold the problem, but have no idea why or what is causing the problem. (The force_ssl() function came from here.)
I am using the CodeIgniter carabiner plugin to serve up the CSS/JS and have the following function to force SSL/HTTPS in my my_helper.php:
if (!function_exists('force_ssl')) {
    function force_ssl() {
        if (ENVIRONMENT != 'development') {
            $CI = & get_instance();
            $CI->config->config['base_url'] = str_replace('http://', 'https://', $CI->config->config['base_url']);
            if ($_SERVER['SERVER_PORT'] != 443) {
                redirect($CI->config->config['base_url'] . $CI->uri->uri_string());
            }
        }
    }
}

/**
 * Override the site_url function so it does https
 *
 * @param <type> $uri
 * @return <type>
 */
function site_url($uri = '', $https = FALSE, $only_images_js_css = true) {
    if ($https || (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off' || $_SERVER['SERVER_PORT'] == 443)) {
        if (ENVIRONMENT != 'production') {
            $secure_connection = FALSE;
        } else {
            $secure_connection = TRUE;
        }
    } else {
        $secure_connection = FALSE;
    }

    $CI = & get_instance();
    if (!$secure_connection) {
        return str_replace("https://", "http://", $CI->config->site_url($uri));
    } else {
        // fallback - .htaccess should cover this - but just to make sure...
        // If we only want the images, js, css, etc. to have https://
        if ($only_images_js_css === true) {
            $needs_ssl = false;
            $extensions_to_check = array(".js", ".css", ".jpg", ".gif", ".png", ".ico");
            foreach ($extensions_to_check as $extension_to_check) {
                if (stristr($uri, $extension_to_check) !== FALSE) {
                    $needs_ssl = true;
                    break;
                }
            }
            if ($needs_ssl === true) {
                return str_replace("http://", "https://", $CI->config->site_url($uri));
            } else {
                return str_replace("https://", "http://", $CI->config->site_url($uri));
            }
        } else {
            return str_replace("http://", "https://", $CI->config->site_url($uri));
        }
    }
}

Is there a better way to do this? (i.e. switch from HTTP to HTTPS) and/or what is wrong with my site_url() and/or force_ssl() functions?

A: I am not sure that the issue is related to these functions. They are getting their data from base_url config. If the base_url is not set Codeigniter tries to guess the protocol, domain and path to your installation. I would think it was a server setup issue since Codeigniter uses $_SERVER['HTTP_HOST'] to get the domain/ip.
if ($this->config['base_url'] == '')
{
    if (isset($_SERVER['HTTP_HOST']))
    {
        $base_url = isset($_SERVER['HTTPS']) && strtolower($_SERVER['HTTPS']) !== 'off' ? 'https' : 'http';
        $base_url .= '://'. $_SERVER['HTTP_HOST'];
        $base_url .= str_replace(basename($_SERVER['SCRIPT_NAME']), '', $_SERVER['SCRIPT_NAME']);
    }
    else
    {
        $base_url = 'http://localhost/';
    }

    $this->set_item('base_url', $base_url);
}

A: The Problem turned out to be part of my CSS magnification (had been previously modified to allow for some re-configuration of the CodeIgniter folders)
Using the codeigniter Carabiner plugin - cssmin.php was the file of problem.... https://github.com/tonydewan/Carabiner


text:
Q: can google maps show KML custom icons at any zoom level? I have a KML file that defines custom icons. The custom icons will all show up if I zoom in but when I zoom out some get converted into the default Blue marker. It seems to happen where icons group together.
Is google maps replacing multiple markers by a simpler default marker?
Is there a way for the KML to tell google maps to use the custom icons at any zoom level?


text:
Q: Set one element above another and have width of both the element equal I want to set the text field above the black image and i want the width of text field should be equal to image.
I dont want to put hardcoded dimensions. Also both the blocks should qually cover the screen horizontally.
Here is my code `
            <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
                xmlns:custom="http://schemas.android.com/apk/res-auto"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:id="@+id/RL_childLeft1"
                android:layout_alignParentLeft="true"
                android:layout_alignParentStart="true">

                <com.ism.eshita.incentivemanagmentsystem.Speedometer.Speedometer
                    android:id="@+id/Speedometer"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_gravity="center"
                    android:background="#000000"
                    custom:currentSpeed="100"
                    custom:maxSpeed="300" />

                <LinearLayout
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_alignParentBottom="true"
                    android:orientation="vertical">

                    <TextView
                        android:id="@+id/tv_bg1"
                        android:layout_width="match_parent"
                        android:layout_height="wrap_content"
                        android:background="@color/PrimaryDark2"
                        android:gravity="center"
                        android:text="BG"
                        android:textColor="@color/white"
                        android:textSize="20sp"
                        android:textStyle="bold" />

                    <TextView
                        android:id="@+id/tv_performance1"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:background="@color/PrimaryDark2"

                        android:gravity="center"
                        android:paddingBottom="5dp"
                        android:text="Performance"
                        android:textColor="@color/white" />
                </LinearLayout>
            </RelativeLayout>

            <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
                xmlns:custom="http://schemas.android.com/apk/res-auto"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_alignParentRight="true"
                android:layout_alignParentEnd="true"
                >

                <com.ism.eshita.incentivemanagmentsystem.Speedometer.Speedometer
                    android:id="@+id/Speedometer2"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_gravity="center"
                    android:background="#000000"
                    custom:currentSpeed="100"
                    custom:maxSpeed="300" />

                <LinearLayout
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_alignParentBottom="true"
                    android:orientation="vertical">

                    <TextView
                        android:id="@+id/tv_bg2"
                        android:layout_width="match_parent"
                        android:layout_height="wrap_content"
                        android:background="@color/PrimaryDark2"
                        android:gravity="center"
                        android:text="BG"
                        android:textColor="@color/white"
                        android:textSize="20sp"
                        android:textStyle="bold" />

                    <TextView
                        android:id="@+id/tv_performance2"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:background="@color/PrimaryDark2"

                        android:gravity="center"
                        android:paddingBottom="5dp"
                        android:text="Performance"
                        android:textColor="@color/white" />
                </LinearLayout>
            </RelativeLayout>
        </RelativeLayout>


text:
Q: Show x-labels as time every two hours with pgfplots{dateplot} I'm trying to plot a simple graph from .csv. I'm using the answer of https://tex.stackexchange.com/a/83929/164280 as basis. I get a could not parse input '00:00:00' as floating point error. I do want to plot the data as time series. How do I work around this?
MWE:
\documentclass[11pt, twoside, a4paper]{report}
\usepackage{pgfplots}
\begin{document}
    \begin{figure}
        \begin{tikzpicture}
        \begin{axis}
        \addplot table [x=Time, y=AC, col sep=semicolon] {mayriso.csv};
        \end{axis}
        \end{tikzpicture}
    \end{figure}
\end{document}

Datafile snippet:
Time;AC
00:00:00;-0.4442
00:01:00;-0.4445

Edit:
Thanks to marmot, this is now my new MWE:
\documentclass[11pt, twoside, a4paper]{report}
\usepackage[inner = 25mm, outer = 25mm,  top = 30mm, bottom = 20mm, headheight = 13.6pt]{geometry}
\usepackage{pgfplots}
\usepgfplotslibrary{dateplot}
\pgfplotsset{
    compat=1.16,
    }

\begin{document}

\begin{figure}[h]
    \centering
    \begin{tikzpicture}
    \begin{axis}[width = 0.7\textwidth, height = 0.4\textwidth, date coordinates in=x, xticklabel={\hour.\minute},
    ymin=0, ylabel={AC output power (kW)}, axis lines*=left,ymajorgrids,]
    \addplot [ultra thick, smooth, green!50!black,] table [x=Time, y=AC, col sep=semicolon] {riso.csv};
    \end{axis}
    \end{tikzpicture}
    \caption{caption}
    \label{fig:other version}
\end{figure}

\end{document}

The issue is that the x labels are ugly. I want the x-labels to show hours at regular intervals, so 00:00, 02:00, 04:00 or something like that. I also want the graph x label to start at 00:00 and end at 24:00. How do I do this?

A: Well, it complains that it is not a floating number because it is none. One workaround is to use dateplot, prepend year, month and day and then do the plot.
\documentclass[11pt, twoside, a4paper]{report}
\usepackage{filecontents}
\begin{filecontents*}{mayriso.csv}
Time;AC
2018-08-08 00:00;-0.4442
2018-08-08 00:01;-0.4445
\end{filecontents*}
\usepackage{pgfplots}
\usepgfplotslibrary{dateplot}
\begin{document}
    \begin{figure}
        \begin{tikzpicture}
        \begin{axis}[date coordinates in=x,
        xticklabel={\hour.\minute}]
        \addplot table [x=Time, y=AC, col sep=semicolon] {mayriso.csv};
        \end{axis}
        \end{tikzpicture}
    \end{figure}
\end{document}

Or you need to find a way that your data gets interpreted. Perhaps the dateplot library could be a good starting point to write such a parser. Or you work with symbolic coordinates, but then of course the values won't determine the x coordinates.

If someone sees that, here is where I am stuck. I tried many things, but could not convince pgfplots to parse the times coordinates.
\documentclass[11pt, twoside, a4paper]{report}
\usepackage{pgfplots}
\usepgfplotslibrary{dateplot}
\pgfplotsset{compat=1.16}
\usepackage{filecontents}
\begin{filecontents*}{mayriso.csv}
Time;AC
00:00:00;-0.4442
00:01:00;-0.4445
\end{filecontents*}
\makeatletter
\def\myparse#1:#2:#3 #4{%
        \pgf@xa=#1pt
        \pgf@xb=#2pt
        \divide\pgf@xb by60
        \advance\pgf@xa by\pgf@xb
        \pgf@xb=#3pt
        \divide\pgf@xb by3600
        \advance\pgf@xa by\pgf@xb
        \ifdim\pgf@xa<0pt
                \pgf@xa=0pt
        \fi
        \edef#4{\pgf@sys@tonumber\pgf@xa}%
}%
\newcommand\TimeParse[1]{\myparse#1 \tmp%
\tmp
}
\makeatother

\begin{document}
\TimeParse{00:01:00}
        \begin{tikzpicture}
        \begin{axis}
        %\addplot table [x expr=\TimeParse{\thisrow{Time}}, y=AC, col sep=semicolon] {mayriso.csv};
        \end{axis}
        \end{tikzpicture}
 \end{document}

It does parse the time, just not in the plot.


text:
Q: How long should a WIndows Vista disk shrink take? Sorry if I'm asking this in the wrong place, but I recently found an old Inspiron 530 with Windows Vista Home Premium (In my Attic). I want to install Ubuntu and use it as a Minecraft Server. I read that I needed to create a disk partition, so I decided to shrink the C: drive by 82700 Megabytes. I still want the data on it. It's been over 12 hours (I started at about 4:00 Central Time on July 27th). I am wondering:

*

*Is this normal?

*Should I do something?

*If so, how do I cancel the shrink?

Thanks in advance, I'll let y'all know if it finishes.
EDIT:
Well, I decided to try Ctrl + Alt + Delete after some time, and the screen went black. I pressed the power button on the computer, and the "Are you sure you want to shut down?" notice appeared. I clicked cancel, to find Windows Management Console open. I clicked the red X, and restarted the computer. Nothing blew up, vanished, or got destroyed. I would not recommend doing this. However, if anyone knows how long it should take, or if there's a safer way of canceling the shrink, I'd love to know.


text:
Q: Javascript perform an action when for loop ends I want to show a loading gif while loop is being executed. And when the loop finishes hide it. For loop lasts for several seconds.
$("#loading").removeClass('hidden');
        for (var i = 0; i < 10; i++)
        {
            clearInfo(i);
            loadInfo(i, getInfo());
        }
$("#loading").addClass('hidden');

This is not working. I suppose the last addClass is executed just after the removeClass and is not waiting for the loop...
One approach should be, insert the loop in a function with callback, but isn't there any easier way?
Regards,

A: JavaScript is running in a single thread. Blocking this thread by complex synchronous computation is not a good idea. Checkout WebWorkers.
If loadInfo is asynchronous operation you can use promises like this:
// show your loading indicator

var promises = [];
for (var i = 0; i < 10; i++) {
    clearInfo(i);

    // loadInfo returns promise
    promises.push(loadInfo(i, getInfo()));
}
Q.all(promises)
  .then(function () {
    // hide your loading indicator
  });

Solution with callbacks will be a messy and dirty (according to my personal opinion).

A: I would probably do something along the lines of this:
$("#loading").removeClass('hidden');
for (var i = 0; i < 10; i++) {
    clearInfo(i);
    loadInfo(i, getInfo());
    if ( i == 9 ) {
        // this is the final pass through the loop
        $("#loading").addClass('hidden');
    }
}


text:
Q: NSTableView with NSCheckBox cells - how to intercept row selection? I have a NSTableView with cells that contain NSCheckBox. I'd like to change the behaviour of it so that any row in the table can be clicked and the checkbox in that row toggles on/off accordingly.
I figured it can be done with
    func tableView(tableView: NSTableView, shouldSelectRow row: Int) -> Bool {
}

This method provides the index of the clicked row and I could use this to toggle the checkboxes from there on programmatically. But the problem is that the NSCheckBox intercepts mouse clicks on its row. Is there any way to disable this so that the rows can be clicked fully? Setting the enabled state of the NSCheckBox to false would allow this but it also greys out the checkbox and its title.
EDIT:
To clarify what I need: The (view-based) table cell view contains a checkbox. If a user clicks the checkbox, it toggles but when the row is clicked anywhere where no checkbox is, nothing happens. I want the row to be clicked and the checkbox toggles accordingly. So essentially I want the checkbox to be non-clickable and the table row to notify the checkbox inside it when the row is clicked.

A: In a cell-based table view, you can implement -selectionShouldChangeInTableView:. I assume this will also work for a view-based table view.
- (BOOL)selectionShouldChangeInTableView:(NSTableView *)tableView
{
    NSInteger clickedColumn = tableView.clickedColumn;
    NSInteger attributeEnabledColumn = [tableView columnWithIdentifier:@"attributeEnabled"];

    if (clickedColumn == attributeEnabledColumn) {
        NSInteger clickedRow = tableView.clickedRow;

        if (clickedRow >= 0) {
            NSArrayController  *attributesArrayController = self.attributesArrayController;
            NSMutableDictionary *attributeRow = [attributesArrayController.arrangedObjects objectAtIndex:clickedRow];
            BOOL attributeEnabled = [attributeRow[kAttributeSelectionAttributeEnabledKey] boolValue];

            attributeRow[kAttributeSelectionAttributeEnabledKey] = @(!attributeEnabled);
        }

        return NO;
    }

    return YES;
}

A: Your approach is fine so far, you can click on the table row and this toggles the checkbox state.
As you said, the checkbox can be clicked on its own which doesn't trigger the table row selection. You need to subclass the NSTableCellView and assign this subclass to the cell's class property. Within that custom class file you can react on the checkbox toggle and change the underlying datasource of your table.
import Cocoa

class MyTableCellView: NSTableCellView {
    @IBOutlet weak var checkbox: NSButton!  // the checkbox

    @IBAction func checkboxToggle(sender: AnyObject) {
        // modify the datasource here
    }
}

EDIT:
Here is a code snippet where a checkbox is toggled when the user clicks anywhere on the table cell:
func tableView(tableView: NSTableView, shouldSelectRow row: Int) -> Bool {
    if let cell = tableView.viewAtColumn(0, row: row, makeIfNecessary: false) as? MyTableCellView {
        cell.checkbox.state = cell.checkbox.state == NSOnState ? NSOffState : NSOnState
    }

    return false
}

Note that it still needs a subclass for the table cell where you place an @IBOutlet to your checkbox to make it accessible in code.

A: Apple provide you with the opportunity to intercept a number of NSEvent types via the following NSEvent class method:

Any time an event whose type property matches the mask you passed in to the first argument of the above method, the block (second argument) executes. This block gives you the opportunity to do a number of things: you can carry out additional processing then let the event carry on as usual, you can modify the event, or you cancel the event altogether. Crucially anything you put in this block happens before any other event processing.
In the snippet below any time a checkbox is clicked, the incoming event is doctored to make the event behave as it the click took place outside of the checkbox, but inside the checkbox's NSTableCellView superview.

func applicationDidFinishLaunching(aNotification: NSNotification) {

    NSEvent.addLocalMonitorForEventsMatchingMask(.LeftMouseDownMask,
        handler: { (theEvent) -> NSEvent! in

        var retval: NSEvent? = theEvent
        let winPoint = theEvent.locationInWindow

        // Did the mouse-down event take place on a row in the table?
        if let row = self.tableView.rowContainingWindowPoint(winPoint) {

            // Get the view on which the mouse down event took place
            let view = self.tableView.viewAtColumn(0,
                row: row,
                makeIfNecessary: true) as! NSTableCellView

            // In my demo-app the checkbox is the NSTableCellView's last subview
            var cb = view.subviews.last! as! NSButton
            let cbBoundsInWindowCoords = cb.convertRect(cb.bounds, toView: nil)

            // Did the click occur on the checkbox part of the view?
            if CGRectContainsPoint(cbBoundsInWindowCoords, theEvent.locationInWindow) {

                // Create a modified event, where the <location> property has been
                // altered so that it looks like the click took place in the
                // NSTableCellView itself.
                let newLocation = view.convertPoint(view.bounds.origin, toView: nil)
                retval = theEvent.cloneEventButUseAdjustedWindowLocation(newLocation)
            }
        }

        return retval

    })
}

func tableView(tableView: NSTableView, shouldSelectRow row: Int) -> Bool {

    if let view = self.tableView.viewAtColumn(0,
        row: row,
        makeIfNecessary: true) as? NSTableCellView {

        var checkbox = view.subviews.last! as! NSButton
        checkbox.state = (checkbox.state == NSOnState) ? NSOffState : NSOnState
    }
    return true
}

////////////////////////////////////////////////////////////////

extension NSTableView {

    // Get the row number (if any) that coincides with a specific
    // point - where the point is in window coordinates.
    func rowContainingWindowPoint(windowPoint: CGPoint) -> Int? {
        var rowNum: Int?
        var tableRectInWindowCoords = convertRect(bounds, toView: nil)
        if CGRectContainsPoint(tableRectInWindowCoords, windowPoint) {
            let tabPt = convertPoint(windowPoint, fromView: nil)
            let indexOfClickedRow = rowAtPoint(tabPt)
            if indexOfClickedRow > -1 && indexOfClickedRow < numberOfRows {
                rowNum = indexOfClickedRow
            }
        }
        return rowNum
    }
}

extension NSEvent {

    // Create an event based on another event. The created event is identical to the
    // original except for its <location> property.
    func cloneEventButUseAdjustedWindowLocation(windowLocation: CGPoint) -> NSEvent {
        return NSEvent.mouseEventWithType(type,
            location: windowLocation,
            modifierFlags: modifierFlags,
            timestamp: timestamp,
            windowNumber: windowNumber,
            context: context,
            eventNumber: eventNumber,
            clickCount: clickCount,
            pressure: pressure)!
    }
}


text:
Q: Redis performance I'm learning Redis and trying to measure its time performance. In this setup I set 5 000 000 keys and measured the time for each unique operation.
I have got the following plot (x-label is the number of operations (set), y-label is the time in milliseconds):

I'm noticing that the performance of Redis is going extremely down. I have also measured the performance with 1 000 000  keys:

I can monitor the constant areas with bad performance. Anyway the operating time goes down after some interval of time.
My question is if somebody has done similar researches in the area of Redis performance, could he/she discuss these results. For me it is very interesting and important to understand the reason the server does such "time jumping" and how I can improve its performance.
If somebody needs my Python-code:
def setKeyValue(key, value):
    assert (key != None), "Please, get a key"
    redis_server.set(key, value);

def loopKeyValues(number):
    timeUse = []
    start_tot = time.time()
    for x in range(number):
        start = time.time()
        #setHashKeyValue('mydata',x, x**2)
        setKeyValue(x, x**2)
        end = time. time()
        timeUse.append(end-start)
    end_tot = time.time()
    time_total = end_tot - start_tot
    plt.plot(timeUse)
    plt.ylabel("time")
    plt.show()
    return time_total;


text:
Q: How to set an index in the name of the file from a Registry Value using CreateFile? I would like to create a .txt file on any directory, let's say: C:\Demo.txt but I would like to add an index retrieved by a Registry Value using the CreateFile function (I think that's the function I have to use for that).
For example, if the DWORD DemoValue has a content of "2", the file would be: Demo(2).txt
Can I do that with CreateFile and RegQueryValueEx?
Thanks!

A: There's no way to do it "automatically" - you would have to retrieve the registry value using RegQueryValueEx(), build the filename using a formatted string function like StringCchPrintf() and then create the file.


text:
Q: AWS S3 storage copy functionality How does any storage provider gives copy functionality, for instance aws S3 is giving bucket to bucket copy, where does the actual transfer of bit happens?
On executing the copy cmd using aws sdk it does wait for copy to complete but none of the bits are transferred via my machine.

A: When you copy files from one S3 bucket to another ( ex - aws s3 cp s3://bucket1 s3://bucket2), the process of transferring data will happen in the AWS owned private networks or over the public networks (internet). Files will not get downloaded from the source S3 bucket to your computer and re-uploaded to the destination bucket from your computer.


text:
Q: Sports series? I'm confused how to calculate using an inequality Ok so the inequality on this problem is throwing me off
Suppose that two teams (team A and team B) play a series of games to determine a winner. In a best-of-three series, the games end as soon as one team has won two games. In a best-of-five series, the games end as soon as one team has won three games, and so on. Assume that team A's probability of winning any one game is p, where .5 < p < 1. Also assume that the outcomes are independent from game to game.
What is the exact probability team A will win a three game series, as a function of p? I know this should be straightforward, I just can't seem to grasp it

A: P(A win series) = P(WW)+P(LWW)+P(WLW)
$$P(A)=p^2+p^2(q)+p^2(q)=p^2+2p^2q$$
P(B win series) = P(LL)+P(LWL)+P(WLL)
$$P(B)= q^2+2q^2p$$
$$P(A)+P(B)=p^2+q^2+2p^2q+2q^2p=1$$
In a best of $2n+1$ case
$$P_{2n+1}(A)=p^{n+1}+\binom{n+1}{1}p^{n+1}q+\binom{n+2}{2}p^{n+1}q^2....+\binom{2n}{n}p^{n+1}q^n \\ =p^{n+1}\sum_{k=0}^n\binom{n+k}{k}q^k$$


text:
Q: Change mat-datepicker selected date value according to a time zone In ts. I have used a  (dateChange)="setToDate($event.value)" to get selected date.
<mat-form-field appearance="outline">
        <input matInput [matDatepicker]="picker2" readonly = "readonly"  [(ngModel)] = "grid.todate"
            (dateChange)="setToDate($event.value)" [min]="grid.fromdate">
        <mat-datepicker-toggle matSuffix [for]="picker2"></mat-datepicker-toggle>
        <mat-datepicker #picker2></mat-datepicker>
    </mat-form-field>

I want to change that selected date to the server time zone witch is in GMT.
I have tried DatePip.
public setToDate(data: any): void {
    const todayDate  = new Date();
    this.todate = data._d;
    const changedDate = new DatePipe('en-Us').transform(data.toDate(), 'full', 'GMT');
}

The date picker picked the date at 00.00 am. Date pip will not give the time in GMT.
Here's a the example >
https://stackblitz.com/edit/material-date-picker-csyldt?embed=1&file=app/app.component.ts

A: Change your setDate method like below,
setDate(date: string) {
  this.date = date;
  this.gmtDate = new Date(date).toUTCString();
}

A: You can use moment to convert your time to UTC. There is no offset in UTC and GMT.
For date you just pass today date in the function.
var utcDate = new moment("2020-01-24T11:00", "YYYY-MM-DDTHH:mm").utc();

A: I have found a solution to convert that picked date to any time zone date(with the time it picked)
setDate(newdate: string) {
    const _ = moment();
    const date = moment(newdate).add({hours: _.hour(), minutes:_.minute() , seconds:_.second()});
    this.date = date.toDate();
    this.gmtDate = new DatePipe('en-Us').transform(date, 'full', '+530');
  }
}

https://stackblitz.com/edit/material-date-picker-csyldt?embed=1&file=app/app.component.ts
I have edited the stackblitz for the ones having the same problem.

A: For me, the best solution was to define the default timezone provider in the app.module.ts as follow:
{ provide: DATE_PIPE_DEFAULT_TIMEZONE, useValue: 'UTC' },