text:
Q: Have embedded images open with FancyBox, not in new window This section of code in my /js/global.js file activate each image to open in a new window when clicked.  Is it possible to alter this code to have each open in a FancyBox instead?  I have downloaded a FancyBox plugin for a Vanilla forum I am running, and it currently only targets images embedded in posts After You Click On The Post Itself.  On the main page, clicking on an image opens a new window.
// Shrink large images to fit into message space, and pop into new window when clicked.
// This needs to happen in onload because otherwise the image sizes are not yet known.
    jQuery(window).load(function() {
       var props = ['Width', 'Height'], prop;
       while (prop = props.pop()) {
          (function (natural, prop) {
             jQuery.fn[natural] = (natural in new Image()) ?
             function () {
                return this[0][natural];
             } :
             function () {
                var
                   node = this[0],
                   img,
                   value;
                if (node.tagName.toLowerCase() === 'img') {
                   img = new Image();
                   img.src = node.src,
                   value = img[prop];
                }
                return value;
             };
          }('natural' + prop, prop.toLowerCase()));
       }
       jQuery('div.Message img').each(function(i,img) {
          var img = jQuery(img);
          var container = img.closest('div.Message');
          if (img.naturalWidth() > container.width() && container.width() > 0) {
             img.wrap('');
          }
       });
       // Let the world know we're done here
       jQuery(window).trigger('ImagesResized');
    });

A: Add an specific class to your wrapped images, modifying this line
img.wrap('');

... into this :
img.wrap('');

Then bind fancybox to that selector (".fancybox") in a custom script like :
$(".fancybox").fancybox();

This assumes that you have properly loaded the fancybox js and css files.


text:
Q: Android hide a view partially behind screen Hello I am working with android.I have a custom imageview.I want to hide partial imageview behind the screen. I tried padding=-100... etc. But its not working .How can I hide a view partially behind screen ?

A: use negative margin to parent layout like this, its working
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    **android:layout_marginTop="-20dp"** >

    <ImageView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:background="@drawable/ic_launcher" />

</RelativeLayout>

A: You need to create your view through java or make a drawable of semicircle and set it as background of imageview.
Refer this: Semicircle drawable

redpajama_set_name: RedPajamaStackExchange


text:
Q: Generate a Python dictionary from a list I have a list of product categories which I want to convert to a dictionary.
['Livestock']
['Livestock', 'Poultry']
['Livestock', 'Poultry', 'Chickens']
['Livestock', 'Ruminants']
['Livestock', 'Ruminants', 'Goats']
['Livestock', 'Ruminants', 'Cows']
['Grocery']
['Grocery', 'Food Cupboard']
['Grocery', 'Food Cupboard', 'Canned & Jarred Foods']
['Grocery', 'Food Cupboard', 'Canned & Jarred Foods', 'Soup']
['Grocery', 'Food Cupboard', 'Canned & Jarred Foods', 'Vegetables']

My expected dictionary should look like:
{
  Livestock:
   {
    Poultry: [Chickens],
    Ruminants: [Goats, Cows]
 },
 Grocery:{
    Food Cupboard: {
      Canned & Jarred Foods: [Soup,Vegetables ]
   }
  }
}

A: If you don't care too much about raw speed, this is a fairly simple solution:
cats = [
    ['Livestock'],
    ['Livestock', 'Poultry'],
    ['Livestock', 'Poultry', 'Chickens'],
    ['Livestock', 'Ruminants'],
    ['Livestock', 'Ruminants', 'Goats'],
    ['Livestock', 'Ruminants', 'Cows'],
    ['Grocery'],
    ['Grocery', 'Food Cupboard'],
    ['Grocery', 'Food Cupboard', 'Canned & Jarred Foods'],
    ['Grocery', 'Food Cupboard', 'Canned & Jarred Foods', 'Soup'],
    ['Grocery', 'Food Cupboard', 'Canned & Jarred Foods', 'Vegetables']
]

# only keep lists that aren't the start of another
cats = [c for c in cats if not any(sc[:len(c)] == c for sc in cats if sc != c)]

result = {}
for *nodes, last, leaf in categories:
    current = result
    for node in nodes:
        if node not in current:
            current[node] = {}
        current = current[node]
    if last not in current:
        current[last] = []
    current[last].append(leaf)

print(result)

Output:
{'Livestock': {'Poultry': ['Chickens'], 'Ruminants': ['Goats', 'Cows']}, 'Grocery': {'Food Cupboard': {'Canned & Jarred Foods': ['Soup', 'Vegetables']}}}

Note that this assumes you never pass something like this:
cats = [
    ['apple'],
    ['banana']
]

And then expect something like this:
['apple', 'banana']

The solution expects that there's always at least a single level of dictionary keys.


text:
Q: Kendo observable checkbox not updating through jQuery .prop("checked") I've got a Kendo observable object that is bound to a number of checkboxes. When I update the checkboxes by clicking them, the observable object is correctly updated. However, if I update the checked state through code, the observable object is not updated.
A sample snippet is below and I've got a Kendo UI Dojo. When you click the Red, Green, or Blue checkboxes, the correct information is displayed in the box; however, if you use the "Select All" option, the observable object is not updated.
How can I correctly write the code for the "Select All" checkbox so the observable object is updated along with the checked state?

$(document).ready(function () {
    var colordata = null;
    colordata = kendo.observable({
        colors: []
    });
    kendo.bind($("#chkbox-options"), colordata);

    colordata.bind("change", function(e) {
        var selectedColors = '';

        $.each(colordata.colors, function(key, value){
            selectedColors = selectedColors + " " + value;
        });
        if(colordata.colors.length == 0){
            $("#selected").val('no colors selected');
        }else{
            $("#selected").val('selected colors:' + selectedColors);
        }
    });

    $("#all").on("click", function() {
        $("#chkbox-options input[type='checkbox']").prop("checked", $(this).prop("checked"));
    });
});

<input id="all" type="checkbox" />
Select All

  Red
  <input type="checkbox" id="chk1" value="Red" data-bind="checked: colors" />
  Green
  <input type="checkbox" id="chk2" value="Green" data-bind="checked: colors" />
  Blue
  <input type="checkbox" id="chk3" value="Blue"  data-bind="checked: colors" />

<input id="selected" style="width:100%;" />

A: Your mistake is you are using property change, jquery prop method doesn't trigger colordata change event, jQuery API explains:

For select boxes, checkboxes, and radio buttons, the event is fired immediately when the user makes a selection with the mouse, but for the other element types the event is deferred until the element loses focus

So instead using prop(), you should use click() method. fixed dojo 1
Another approach you could use trigger("change") after use prop(). fixed dojo 2


text:
Q: Why does AUCTeX have \autocite taking two arguments?
Obviously, compiling this just yields

A sample citation: [1, p. 1]arg two?no arg three.

so \autocite itself definitely isn't using the argument.
Why is this so, and how can it be fixed?
Note the red \ when only one argument is given:

A: Apparently the extra opening brace was the culprit. Which can be easily fixed by changing line 306 and line 307 of font-latex.el, saving the file, and compiling AUCTeX again.
So replace the following in line 306
("autocite" "*[{{")
to
("autocite" "[[{")
and line 307
("Autocite" "*[{{")
to
("Autocite" "[[{")


text:
Q: FFmpeg php set image size thumbnail $movie=new ffmpeg_movie(''.$url.'');
$duration = $movie->getDuration();
$uzanti = substr($url , -3);
$duration = date('i:s',''.$duration.'');
$framesay = $movie->getFrameCount();
$framerate = $movie->getFrameRate();
$framehesap = $thumb * $framerate;
$md5 = md5($url);
$frame = $movie->getFrame($framehesap);
$gd = $frame->toGDImage();
imagepng($gd,'../thumb/'.$md5.'.png');

I want to set image size. I'm using ffmpeg as you see. how can I set thumbnail size? (I want 220x130)

A: Use imagescale:
$gd = imagescale($gd, 220, 130);

See here for all info: http://nl3.php.net/manual/en/function.imagescale.php
Edit: fixed it


text:
Q: Is there a way to write programs for photoshop cs5? If I want to write some code for doing photoshop tasks, how would i do that?  What I'm trying to do is have a program that will parse psd files (in photoshop) and go through the groups to check for things in the name, then combine certain layers, and other stuff like that, using variable counters and whatnot.  So like a very customizable action.  Except I want it to be able to make decisions, not just do a static set of operations.  Any points in the right direction? (even just what it's called is okay, i can google)

A: I assume you have already started by searching for photoshop script? Did you see this page?

ooh i thought a script was just a list of commands. guess i'll look into that.

Oh, boy, I hope that comment doesn't restart the age old debate about scripting vs programming languages.  You will not from the link you can use at least vbscript, javascript, and applescript.  Given that Photoshop provides a COM interface, you probably should be able to use any language you want.


text:
Q: Change string encoding of pandas MultiIndex I have a DataFrame with a MultiIndex that I want to convert to utf8. Is there a trick that allows you to do something along the lines of df.index = df.index.str.decode('iso-8859-1').str.encode('utf-8') (which works on single-level Indexes, but not MultiIndexes)?

A: The str methods indeed only work on single levels, not on a Multi-Index. So I think there are two ways with dealing with this: a) retrieve the single levels, change them, reconstruct the multi-index, or b) work on it as columns (by resetting the index, and setting it back afterwards.
Using a dummy dataframe for the example:
In [6]: df = pd.DataFrame({'a':[1,2,3], 'b':['é', 'a', 'b'], 'c':[0.1,0.2,0.3]})

In [7]: df = df.set_index(['a', 'b'])

In [8]: df
Out[8]:
       c
a b
1 é  0.1
2 a  0.2
3 b  0.3

For a), you can use get_level_values to get the individual levels as Index objects:
In [12]: levels = [df.index.get_level_values(i) for i in range(df.index.nlevels)]

In [13]: levels
Out[13]:
[Int64Index([1, 2, 3], dtype='int64', name=u'a'),
 Index([u'é', u'a', u'b'], dtype='object', name=u'b')]

In [14]: levels[1] = levels[1].str.decode('iso-8859-1').str.encode('utf-8')

In [16]: df.index = pd.MultiIndex.from_arrays(levels)

Or for b), reset the index and set it back afterwards:
In [27]: temp = df.reset_index()

In [29]: temp['b'] = temp['b'].str.decode('iso-8859-1').str.encode('utf-8')

In [30]: df = temp.set_index(['a', 'b'])


text:
Q: Как называется сайт, который показывает как "дополняет" компилятор, написанный нами код например, показывает неявные методы аксессоров get/set, неявный конструктор или же приватное поле делегата для события

A: https://sharplab.io например
public class C
{
    public int A { get; set; }
}

Кажется, это то что вам нужно
using System.Diagnostics;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Security;
using System.Security.Permissions;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.Default | DebuggableAttribute.DebuggingModes.DisableOptimizations | DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints | DebuggableAttribute.DebuggingModes.EnableEditAndContinue)]
[assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)]
[assembly: AssemblyVersion("0.0.0.0")]
[module: UnverifiableCode]
public class C
{
    [CompilerGenerated]
    [DebuggerBrowsable(DebuggerBrowsableState.Never)]
    private int k__BackingField;

    public int A
    {
        [CompilerGenerated]
        get
        {
            return k__BackingField;
        }
        [CompilerGenerated]
        set
        {
            k__BackingField = value;
        }
    }
}


text:
Q: Among the $n$ for which iterating $n\mapsto 2n+1$ eventually hits a prime, can the number of iterations required be arbitrarily large? Suppose we start with an arbitrary positive integer $n$ and iterate the map $n\mapsto 2n+1,$ calling a starting value good if the iterates eventually hit a prime number. Is it possible to prove, assuming good starting values, that the number of iterations required to hit a prime can be arbitrarily large?
Letting $a_n$ be the smallest integer $m \ge 1$ such that $(n+1)2^m-1$ is prime, or $0$ if no such prime exists, we have OEIS A050412, and my question is equivalent to asking whether it is possible to prove that this sequence is unbounded.
Note: Let $x_m$ be the $m$th iterate, $m=1,2,3,\ldots$. If $x_m=(n+1)2^m-1$ for some $m$, then $x_{m+1}=2x_m+1=(n+1)2^{m+1}-1$. We have $x_1=2n+1=(n+1)2^1-1,$ so by induction we have $x_m=(n+1)2^m-1$ for all $m$.

A: The question is tantamount to asking whether, for infinitely many $m$, there exist primes $p\equiv -1\pmod{2^m}$ for which $(p+1)/2^i-1$ is composite for every $1\leq i\leq m$.
Fix distinct primes $q_1,\dots,q_m$ which do not divide $2^k-1$ for any $1\leq k\leq m$, and consider the system of congruences defined by $p\equiv -1\pmod{2^m}$ as well as
$$p\equiv 2^i-1\pmod{q_i}$$
for each $1\leq i\leq m$. Since $q_i\nmid 2^i-1$, none of these congruences are compatible with $q_i\mid p$, so, by the Chinese remainder theorem, they are equivalent to
$$p\equiv A\pmod{2^mq_1q_2\cdots q_m}$$
for some integer $A$ which is not a multiple of any $q_i$, nor of $2$. By Dirichlet's theorem on arithmetic progressions, there exist infinitely many primes satisfying this congruence. But then
$$\frac{p+1}{2^i}-1\equiv 0\pmod{q_i}$$
for each $i$, and so, if $p$ is sufficiently large, none of these numbers may be prime. Thus, for each $m$, there are infinitely many primes satisfying the desired conditions, and so infinitely many integers $n=(p+1)/2^m-1$ for which
$$\{n,2n+1,4n+3,\dots,(n+1)2^{m-1}-1\}$$
are all composite, but $(n+1)2^m-1$ is prime.


text:
Q: How to secure packets from android to http server Is there any way to secure sending of data from my android application to http server? I have read articles that changing http to https will make it easier and secured. If I get to successfully change it to https, is still there not enough security for data-sniffing or will that be enough for security??

A: https means there will be TLS tunnel which means all the data inside http will be encrypted.
Someone can always sniff the traffic but with https the traffic will be encrypted, so they will not be able to see the data, unless they can break the encryption.
There are also different versions of TLS protocol and cipher suits. If you switch to https check if you are using proper ones, not some outdated that can be broken easily.
As to if this will be enough security, it depends on the project/ your company standards for security and compliance.


text:
Q: Get count of HttpCollectionKeys I'm getting the ThrowIfMaxHttpCollectionKeysExceeded() error on a particularly large page, and wanted to know if there was a way to count the number of HttpCollectionKeys my page actually contains before it is submitted.
I want to use this information to try and avoid increasing the MaxHttpCollectionKeys, so NOT this.
<add key="aspnet:MaxHttpCollectionKeys" value="3000" />

Thank you for any information on how to achieve this.
UPDATE:
It turns out Page.Request.Form.Keys.Count is the field I was looking for. I had tried this before, but I was accessing it during Page_Load, and apparently you have to access this during a post back event to get a correct number, which means you have to temporarily set:
<add key="aspnet:MaxHttpCollectionKeys" value="3000" />.

There is still the question of how to access this value before submitting the page, but this is how I was able to get some kind of count at least.

A: Here is an HttpModule that will count the number of keys in each request and record the "high-water mark" of keys used and in the Windows event log:
Using an HTTP Module to assist in adjusting the value of aspnet:MaxHttpCollectionKeys


text:
Q: Duplicate the current line in octave Is there any Method to duplicate the one line of code in octave GUI. Like in eclipse if we want to duplicate a code of line such as:
int a = 5;
We can press Ctrl+Alt+Down to copy it to the next Line.
So is there any shortcut to do this in octave GUI.

A: Move the cursor to the line you want to duplicate, press CTRL and then d together
TL;DR: Ctrl+D


text:
Q: Multiple Ball Program that randomizes the size of the balls I have my program running where I have a variable radius so that the balls can be of a size int, but I would like to know how to make this program more complex with adding random sizes of balls. small,medium,big etc. On line 148 I tried changing it to int radius = (int)(5*Math.random); but it did not work. Must I do something else to my code in order for this to work? And if there are any other hints you may have, they'd be much appreciated. Thanks
import javax.swing.Timer;
import java.util.ArrayList;
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;

public class MultipleBallApp extends JApplet
{
  public MultipleBallApp()
  {
    add(new BallControl());
  }

  class BallControl extends JPanel {
    private BallPanel ballPanel = new BallPanel();
    private JButton jbtSuspend = new JButton("Suspend");
    private JButton jbtResume = new JButton("Resume");
    private JButton jbtAdd = new JButton("+1");
    private JButton jbtSubtract = new JButton("-1");
    private JScrollBar jsbDelay = new JScrollBar();

    public BallControl() {
      // Group buttons in a panel
      JPanel panel = new JPanel();
      panel.add(jbtSuspend);
      panel.add(jbtResume);
      panel.add(jbtAdd);
      panel.add(jbtSubtract);

      // Add ball and buttons to the panel
      ballPanel.setBorder(new javax.swing.border.LineBorder(Color.red));
      jsbDelay.setOrientation(JScrollBar.HORIZONTAL);
      ballPanel.setDelay(jsbDelay.getMaximum());
      setLayout(new BorderLayout());
      add(jsbDelay, BorderLayout.NORTH);
      add(ballPanel, BorderLayout.CENTER);
      add(panel, BorderLayout.SOUTH);

      // Register listeners
      jbtSuspend.addActionListener(new Listener());
      jbtResume.addActionListener(new Listener());
      jbtAdd.addActionListener(new Listener());
      jbtSubtract.addActionListener(new Listener());
      jsbDelay.addAdjustmentListener(new AdjustmentListener()
      {
        @Override
        public void adjustmentValueChanged(AdjustmentEvent e) {
          ballPanel.setDelay(jsbDelay.getMaximum() - e.getValue());
        }
      });
    }

    class Listener implements ActionListener
    {
      @Override
      public void actionPerformed(ActionEvent e) {
        if (e.getSource() == jbtSuspend)
          ballPanel.suspend();
        else if (e.getSource() == jbtResume)
          ballPanel.resume();
        else if (e.getSource() == jbtAdd)
          ballPanel.add();
        else if (e.getSource() == jbtSubtract)
          ballPanel.subtract();
      }
    }
  }

  class BallPanel extends JPanel
  {
    private int delay = 10;
    private ArrayList<Ball> list = new ArrayList<Ball>();

    // Create a timer with the initial dalay
    protected Timer timer = new Timer(delay, new ActionListener() {
      @Override /** Handle the action event */
      public void actionPerformed(ActionEvent e)
      {
        repaint();
      }
    });

    public BallPanel()
    {
      timer.start();
    }

    public void add()
    {
      list.add(new Ball());
    }

    public void subtract()
    {
      if (list.size() > 0)
        list.remove(list.size() - 1); // Remove the last ball
    }

    @Override
    protected void paintComponent(Graphics g)
    {
      super.paintComponent(g);

      for (int i = 0; i < list.size(); i++)
      {
        Ball ball = (Ball)list.get(i); // Get a ball
        g.setColor(ball.color); // Set ball color

        // Check boundaries
        if (ball.x < 0 || ball.x > getWidth())
          ball.dx = -ball.dx;

        if (ball.y < 0 || ball.y > getHeight())
          ball.dy = -ball.dy;

        // Adjust ball position
        ball.x += ball.dx;
        ball.y += ball.dy;
        g.fillOval(ball.x - ball.radius, ball.y - ball.radius,
          ball.radius * 2, ball.radius * 2);
      }
    }

    public void suspend()
    {
      timer.stop();
    }

    public void resume()
    {
      timer.start();
    }

    public void setDelay(int delay)
    {
      this.delay = delay;
      timer.setDelay(delay);
    }
  }

  class Ball
  {
    int x = 0;
    int y = 0; // Current ball position
    int dx = 10; // Increment on ball's x-coordinate
    int dy = 10; // Increment on ball's y-coordinate
    int radius = 5; // Ball radius
    Color color = new Color((int)(Math.random() * 256),
        (int)(Math.random() * 256), (int)(Math.random() * 256));
  }

  /** Main method */
  public static void main(String[] args)
  {
    JFrame frame = new JFrame();
    JApplet applet = new MultipleBallApp();
    frame.add(applet);
    frame.setTitle("MultipleBallApp");
    frame.setLocationRelativeTo(null); // Center the frame
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setSize(400, 200);
    frame.setLocationRelativeTo(null); // Center the frame
    frame.setVisible(true);
  }
}

A: Make sure you do not get 0 as a radius when trying to randomize the ball's radius.
int radius = (int)(4*Math.random()+1);


text:
Q: Retrofit POST Request authentication token not accepting I am trying to send a POST Request to a REST API which I created. For this I am using Retrofit.
Now when I send the request using CURL commands in terminal, the request get accepted and the values are stored. Below is the code:
curl -i -H "Accept: application/json" -H "Content-type: application/json" -H "X-User-Email: abcd@gmail.com" -H "X-User-Token: qQsQobQv-Wmum7bUs4b_"  -X POST -d '{"store": {"code":"0010" } }' http://localhost:3000/api/store.json

The above works completely fine.
Now when I try to send the request using Retrofit in my android app, it says Unauthorization Error in my API. And nothing gets stored.
final String endpoint = "http://localhost:3000/api/store.json"
RequestInterceptor requestInterceptor = new RequestInterceptor() {
            @Override
            public void intercept(RequestFacade request) {
                request.addHeader("Content-Type", "application/json");
                request.addHeader("Accept", "application/json");
                request.addHeader("X-User-Email", email);
                request.addHeader("X-User-Token", auth_token);
            }
        };

        RestAdapter restAdapter = new RestAdapter.Builder()
                .setEndpoint(endpoint)
                .setRequestInterceptor(requestInterceptor)
                .build();

        Service service = restAdapter.create(Service.class);
        service.store(fault, new Callback<StoreResponse>() {
            @Override
            public void success(StoreResponse storeResponse, Response response) {
                Log.d(LOG_TAG, "Success");
            }

            @Override
            public void failure(RetrofitError error) {
                Log.d(LOG_TAG, "Failure" + error.getMessage());
            }
        });

This doesn't work. I don't know what to do. Been stuck here for a while.
Please help!!!
Here is the Service Class:
public interface Service {
    @POST("/")
    public void store(@Body StoreResponse fault, Callback<StoreResponse> responseCallback);
}

EDIT
It is working fine now. Actually my email was not getting stored and so the variable was null. Fixed that and now everything is working fine.

A: Change your "test" class as follow:
final String endpoint = "http://localhost:3000/api"

RestAdapter restAdapter = new RestAdapter.Builder()
                .setEndpoint(endpoint)
                .build();

Service service = restAdapter.create(Service.class);
service.store(fault, new Callback<StoreResponse>() {
    @Override
    public void success(StoreResponse storeResponse, Response response) {
        Log.d(LOG_TAG, "Success");
    }

    @Override
    public void failure(RetrofitError error) {
        Log.d(LOG_TAG, "Failure" + error.getMessage());
    }
});

And your Service interface:
public interface Service {
   @Headers({"X-User-Email: abcd@gmail.com", "X-User-Token: qQsQobQv-Wmum7bUs4b_"})
   @POST("/store.json")
   public void store(@Body StoreResponse fault, Callback<StoreResponse> responseCallback);
}

Or if you need headers with dynamic values:
public interface Service {
   @POST("/store.json")
   public void store(@Header("X-User-Email") String email, @Header("X-User-Token") String token, @Body StoreResponse fault, Callback<StoreResponse> responseCallback);
}


text:
Q: Why can we use Cauchy's integral formula in proving Laurent series? So the Laurent series proof starts as follows.
Let $S\subseteq\mathbb{C}$ a set defined as $S=\{z\in\mathbb{C}\mid R_1<|z-c|<R_2\}$ where $c\in\mathbb{C}$ and let $f:S\to\mathbb{C}$ be holomorphic on $S$. Next we take some $z\in S$ and $R>0$ such that $B(z,R)\subseteq S$. Then we proceed to use the Cauchy integral formula to represent $f(z)$, but doesn't Cauchy integral formula only hold when $f$ is holomorphic on a simply connected set which $S$ clearly isn't?

A: Before using the Cauchy's integral formula, there are several steps utilizing contours. We start with the contour

Then the integral of $\frac{f(z)}{2\pi i(z-w)}$ over the upper half one yields $f(w)$, since we can find suitable simply-connected domain containing the contour and its inside, where $f$ is holomorphic. Also the integral over the lower contour is simply $0$ by Cauchy's integral theorem. Note that the line segments are actually  overlapped. Hence by cancelling integrals over the segments(which are reversed each other) the sum of upper and lower integrals become the integral over the below contour:

Hence we can say that $$f(w) = \frac{1}{2\pi i}\left(\int_{C_1}\frac{f(z)}{z-w}dz-\int_{C_2}\frac{f(z)}{z-w}dz\right)$$ where $C_1, C_2$ are positively oriented circles which lies outside $w$ and inside $w$, respectively.


text:
Q: Ignore logger function in python unit test case I am writing test cases for few python programs. I have used a customize logger function.
logger.info("Some text")
logger.error("some text")

Now the logger is a object been created from some other program. I have a program as "logger_1.py" and I am importing the program in my current program to create a logger object.
from logger_1 import getlogger

global logger
logger = getlogger("addaccess", "_log)

In my unit test case I am getting logger is not defined.
How can I skip the statements which starts with logger in the function that been unit tested or any other way I can mock or patch all the logger statements in the function of the program?

A: There's three options I see:

*

*Don't change anything. Let the logger log and ignore whatever output it produces. Development/Testing/Staging environments should be logging to non-production systems anyway so and output should be able to be discarded without much thought. I'm mostly including this option for the sake of completeness, but for small or unimportant systems this is a valid solution. In your case this also won't work since logger_1.py does not seem to be available during testing.

*Change the code creating the logger, or in this case importing it from another place, so that it uses a different, testing-specific logger and output location. Catching that execution environment (command line, import, something else) can be a bit tricky, though. For example in our systems we usually include a
if __name__ == "__main__":
    #do something with logger

block, so that the logger points to somewhere else if the file is called from the command line as compared to being imported into a test suite.

*You can mock the logger for each test method with a dummy logger:
from unittest import mock, TestCase

create_dummy_logger():
    #create and return a dummy logger
    pass

SomethingTests(TestCase):
    @mock.patch("getlogger", create_dummy_logger)
    test_method_that_logs_something(self):
        pass


text:
Q: How to use assume role credential in dynamodb (aws-sdk javascript)? I already have aws assume role credentials in .aws/credetials file.
how to use it to creat sts or dynamodb like:
const { DynamoDB } = require('aws-sdk');
const { DocumentClient } = DynamoDB;

 const dynamo = new DynamoDB({
 endpoint: process.env.AWS_ENDPOINT,
 region: process.env.AWS_REGION,
 accessKeyId: process.env.AWS_ACCESS_KEY_ID,
 secretAccessKey: process.env.AWS_SECRET_ACCESS_KEY,
 secretToken: process.env.aws_security_token
 });

I mean I got error as:
root@myubuntu:~/work/contacts_api# node ./seed/runner.js

```

Checking if 'contacts' table exists
    { UnrecognizedClientException: The security token included in the request is invalid.
        at Request.extractError (/root/work/contacts_api/node_modules/aws-sdk/lib/protocol/json.js:51:27)
        at Request.callListeners (/root/work/contacts_api/node_modules/aws-sdk/lib/sequential_executor.js:106:20)
        at Request.emit (/root/work/contacts_api/node_modules/aws-sdk/lib/sequential_executor.js:78:10)
        at Request.emit (/root/work/contacts_api/node_modules/aws-sdk/lib/request.js:683:14)
        at Request.transition (/root/work/contacts_api/node_modules/aws-sdk/lib/request.js:22:10)
        at AcceptorStateMachine.runTo (/root/work/contacts_api/node_modules/aws-sdk/lib/state_machine.js:14:12)
        at /root/work/contacts_api/node_modules/aws-sdk/lib/state_machine.js:26:10
        at Request. (/root/work/contacts_api/node_modules/aws-sdk/lib/request.js:38:9)
        at Request. (/root/work/contacts_api/node_modules/aws-sdk/lib/request.js:685:12)
        at Request.callListeners (/root/work/contacts_api/node_modules/aws-sdk/lib/sequential_executor.js:116:18)
      message: 'The security token included in the request is invalid.',
      code: 'UnrecognizedClientException',
      time: 2019-01-07T05:39:54.907Z,
      requestId: 'A5CFV62P0TGHJH7VDIBSL0JRC3VV4KQNSO5AEMVJF66Q9ASUAAJG',
      statusCode: 400,
      retryable: false,
      retryDelay: 5.013458338738063 }

```
I want to know the correct way to initial credetials, if I want to use mfa credetials.

A: I'm guessing that the error here should give you a clue:
"The security token included in the request is invalid"
Did you try printing out the environment value

env | grep aws_security_token

If it's empty you'll have to set the value prior to running your code.
Also, I've noticed that your other aws keys are all caps whereas your aws_security_token is all lowercase.

A: I suspect secretToken isn't a thing.  Here are two examples of how it could be done (how I've done it before).
That said I would encourage the construction and use of a Credentials where ever possible (the second example), but if you wanted to do it inline- that should work too.
/** assume a role and build a DocumentClient object to make a single scan **/
;(async () => {
  const sts = new AWS.STS()
  const assumeRole = await sts
    .assumeRole({
      RoleArn: process.env.ROLE_ARN,
      RoleSessionName: process.env.ROLE_SESSION_NAME,
    })
    .promise()

  const dynamodb = new AWS.DynamoDB.DocumentClient({
    region: process.env.REGION,
    credentials: {
      accessKeyId: assumeRole.Credentials?.AccessKeyId,
      secretAccessKey: assumeRole.Credentials?.SecretAccessKey,
      sessionToken: assumeRole.Credentials?.SessionToken,
    },
  })

  const scan = await dynamodb
    .scan({
      TableName: process.env.TABLE_NAME,
    })
    .promise()

  console.log(scan)
})()

/**
* assume a role and build a Credentials object and use it
* to build a DocumentClient object to make a single scan
**/
;(async () => {
  const sts = new AWS.STS()
  const assumeRole = await sts
    .assumeRole({
      RoleArn: process.env.ROLE_ARN,
      RoleSessionName: process.env.ROLE_SESSION_NAME,
    })
    .promise()

  const credentials = new AWS.Credentials({
    accessKeyId: assumeRole.Credentials?.AccessKeyId,
    secretAccessKey: assumeRole.Credentials?.SecretAccessKey,
    sessionToken: assumeRole.Credentials?.SessionToken,
  })

  const dynamodb = new AWS.DynamoDB.DocumentClient({
    region: process.env.REGION,
    credentials: credentials,
  })

  const scan = await dynamodb
    .scan({
      TableName: process.env.TABLE_NAME,
    })
    .promise()

  console.log(scan)
})()


text:
Q: collections.deque get index of element by value For list we can get index of element list_name.index(3)
How to get index of item in deque.
ex:
d_list = deque([1, 2, 3, 4]) what is the best way to get the index of element 3.
Edit:
I am using Python 2.7.6

A: Just use it like regular lists:
>>> d_list = collections.deque([1, 2, 3, 4])
>>> d_list.index(3)
2

Edit: This is only possible in Python 3.5 right now

A: According to the pythons docs, if you have python3.5 or better, you can use index (as per tobspr's answer).
For older pythons, you can convert the deque to a list and then use index:
In [5]: from collections import deque

In [6]: d_list = deque([1, 2, 3, 4])

In [7]: list(d_list).index(3)
Out[7]: 2

A: If you are using Python 2.x, deque is not a good choice if you want to do lookup. You can either use list or do the following using enumerate():
>>> def index(element, queue):
...     for i, ele in enumerate(queue):
...         if ele == element:
...             return i
...     raise ValueError("{} is not in queue".format(element))

>>> index(2, deque([1, 2, 3, 4]))
1

Alternatively, you can implement your own queue:
>>> class IndexedDeque(deque):
...     def index(self, element):
...         for i, ele in enumerate(self):
...             if ele == element:
...                 return i
...         raise ValueError("{} is not in queue".format(element))

>>> d_list = IndexedDeque([1, 2, 3, 4])
>>> d_list.index(2)
1


text:
Q: Expected value for Head/Tails There are $N$ coins placed in a line. A coin may be facing head/tail direction with $0.5$ probability. Now I need to find number of pairs of coins $(i,j)$ such that $i<j$ and on index $i$ , I should get Head, and on index $j$ I should get Tail. Means head on left and tail on right.
Examples:
HTHTT has 5 pairs
HTHT has 3 pairs
THTH has 1 pair.
Find the expected value of number of such pairs ( when given $N$).

A: Every time you flip a tail, you score a point for each previous head that you've already flipped.
Let $E_n$ be the expected score for $n$ flips. We should have that flipping an $(n+1)$-st coin gives us an expected additional score of $\frac12\cdot\frac{n}2=\frac{n}{4}$.  The reasoning is that half the time we flip a head and get no additional points; and half the time we flip a tail and score a point for each previous head, and we expect half the previous flips to be heads.
Thus $E_n$ obeys the recursion: $E_0=0$ and $E_{n+1}=E_n+\frac{n}{4}$
This solves out to $E_0=E_1=0$ and $E_n=\frac{1+2+\cdots+(n-1)}{4}=\frac{n(n-1)}{8}$ for $n\ge 2$.


text:
Q: How can I keep track of user specifically? Example, via using their permanent private IP Today I decided I want to work more on my framework and want to add rate limiting.  I have done such a thing before and had it working.  It worked by getting your public router mask IP and storing it in a database, then on every request it counts it, and once reached to a limit, it will start blocking you for some time then reset.
The Problem
Well the problem is I was getting the user IP with this code snippet:
$client['IP'] = $_SERVER['REMOTE_ADDR'];

This code gets the public IP of the client or the MASKED IP that your router assigns.  Now this is a problem because if one person on the network is spamming and is the bad guy, the good guy on the network will also be rate limited cause after a certain amount of rate limiting you, it blocks you for a while.
So, in PHP, is there some possible way to keep track of a pin pointed user, so I can have something that will guaranty to pin point the user for at least a week since you ISP keeps changing your IP every 14 days.
Thanks!

A: Not using IP alone you can't, no.
Even if you could get the private IP (which you can't)...

*

*it probably won't be unique (except within that private network),

*it is very unlikely to be permanent (largely because of DHCP),

*the same device can switch networks (e.g. different Wifi networks, or 4G) giving it a different public and private IP each time, and

*many people use more than one device anyway.

One obvious and more reliable way to track users is via your authentication scheme. If users must authenticate before sending requests to your endpoints, you can track the number of requests made by a specific user and put limits on that. (If you want to be subtle you can impose different limits for different endpoints depending on their sensitivity or popularity, or the load they cause on your infrastructure. You could also potentially limit a user per IP, if they connect from more than one IP, and you think it make sense.)
If you allow anonymous access to some or all of the data, then you can track the user a bit using API keys, which you would issue as a GUID to each application or user which registers with the API, but they are not quite as secret. You can then apply rate limits per key and/or per user. That's how big API providers such as Google do it - or, at least it's one technique that they use to help with rate limiting (and other things), anyway.


text:
Q: Dynamic Memory Allocation Functions- Malloc and Free #include<stdio.h>
#include<stdlib.h>
#include<string.h>
int main()
{
char *p;
p = (char *)malloc(4*sizeof(char));
strcpy(p, "abcdabcd");
printf("%s\n", p);
free(p);
printf("%s\n", p);
return 0;
}

I tried running the above code on Ubuntu. Here I am allocating 4 bytes of memory from malloc. I then tried copying 8 bytes into the memory allocated by malloc. I did not get any warning or error. I tried freeing the block of memory and tried using the same memory that was being freed but again no issues at all. It printed the right string. Can someone please explain this behavior?

A: The behavior cannot be meaningfully explained. Your program exhibits undefined behavior, meaning that anything can happen. That "anything" also includes the behavior you observed in your experiment, i.e. "printing the right string".
Today it "printed the right string". Tomorrow it might simply crash. Day after tomorrow it might format your hard drive. That's perfectly permissible under the concept of undefined behavior.

A: Aparrently correct operation is in the class of [undefined behaviour].

A: When a program is started, it is given access to virtual memory through the OS. Usually virtual pages have some minimum size (say 4 kb) and that is the smallest size that they are handled on.
So you request memory with your malloc below this page size, and a whole block is available. Some/None/All of this block may be used by other programs. But it is still technically there:
1 byte | 1 byte | 1 byte | 1 byte | more memory you don't have....
 ^ char p points here

You then start dumping copying a string into the memory starting at p. So you get:
a | b | c | d | the rest of the chars start dumping into somebody elses space!

This overlap is undefined. In other words, we may have unused memory, so everything works today. Tomorrow, that physical memory space is held by the OS, and we fail to overwrite it. The day after, we break some other program. The day after that, we seg fault.
As noted by others, C does not watch out for you.

A: The C language doesn't guarantee any memory checking. Basically, if you write to memory that is not yours (e.g. you write to memory that exceeds the bounds of your array) or if you read from memory that's not yours (e.g. you read from memory you've given up by free-ing it) there is no knowing what will happen.
However, the operating system may or may not prevent you from doing either of these things. Generally, if this happens, you'll get a "Bus Error" or "Segmentation Fault". However, it is also not guaranteed that either of these things will happen.
The best thing to do is to code defensively. Keep track of how long your arrays are and then assert or otherwise check that when you copy into an array you don't exceed the array size.
Another thing you can do is debug. Valgrind is an extremely effective tool for catching problems like the one you describe. It can indicate both situations where you read or write to memory that you haven't malloc'd. It can also identify leaks, such as when you malloc memory and then later forget to free it.

A: I believe it allocates along block alignments, which would be why it gave you some magical extra memory in this case.  Try upping it to a larger byte multiple (eg. 16,64,etc. and it should be more exact, and it might segfault if you go beyond it).  Though keep in mind that if the memory after the malloc'd chunk is also part of your program's memory space...then you won't get a segfault either.
In general, as long as you stay in your programs segment of memory then you can happily read/write all you want (at your own peril of course :D).
If you really want to check your program run it with/in 'valgrind'

A: Everyone who said you've invoked undefined behavior is correct.
The reason it appeared to work correctly is likely a side-effect of the particular implementation of the heap manager on your platform.  For example, many memory managers round up allocations to some convenient size with the smallest size often being 8 or 16 bytes.  You should never depend on such implementation details.
Some platforms have tools for trying to catch these types of assumptions while your developing your program.

A: Like all others have said ,your code results in undefined behavior (anything can happen).
Your heap memory allocator (malloc) is not responsible for the data stored in
the region after you've freed it .
Understanding the responsibilities of malloc will help you explain why you are seeing the result , why its incorrect programming practice and why it wont work all the time .
Malloc is a heap memory allocator (_int_malloc and _int_free) in glibc . You can view its code here [http://code.woboq.org/userspace/glibc/malloc/malloc.c.html#_int_malloc].

Can someone please explain this behavior ?

A comical example would help clarifying your question quickly.
Consider you are renting a room  (memory) from a motel (sbrk(2)) that doesnt have keys to any of  its rooms (memory)! . You go to the receptionist (malloc) and ask for a room (memory) , she gives you one that is available  , you take the room (memory) and use it .
You are done with it and now promise her you arent going to use it again(freeing). She makes an entry in her book that your room (memory) is free and can be alloted to others . It is her wish entirely to give the room to somebody else or not .

You come again after sometime to see your room (receptionist doesnt check you) ,you are lucky if you find nobody using the room  (it looks as messy as you had left!)
The work of the receptionist (malloc) is to allot a room(memory) to you as quickly as possible , trusting that you keep your word after you vacate (free) .Her job is not to prevent you from using any of the rooms (memory) !
The owner (kernel) becomes furious (exception) if you access a place that you are not allowed to (read only region).
Im a newbie and im not sure if its appropriate to answer this way . Let me know if im wrong
I strongly advice you to go through malloc


text:
Q: IDataReader that returns multiple IDataRecords for each object in the input list I am trying to implement the fastest way of importing millions of rows into a SQL table via use of the SqlBulkCopy function and providing it with a custom IDataReader (I am told this would be faster than trying to create a DataTable)
I currently have a list of objects that represent documents we have in our document management system. Each document has a number of properties. Here we will assume it has 4 properties which are its GUID, name, date created, and file size
The SQL table I am putting this into (simplified for the purposes of this question) has 3 columns These are the document GUID, attribute name, and attribute value.
For the first document object in the input list, I would need the IDataReader to return 3 data records for that document. It's only 3 because the document GUID is a value that gets returned on each of the 3 records
eg if i had the following document object
doc.Guid = 7418db3a-6de6-4657-ac0a-c12585c7c3f2
doc.Name = "Test Document"
doc.DateCreated = 28/04/2021
doc.Filesize = 3345

Then the IDataReader would stream out 3 rows like the following:

DocumentGUID
AttributeName
AttributeValue

7418db3a-6de6-4657-ac0a-c12585c7c3f2
Name
Test Document

7418db3a-6de6-4657-ac0a-c12585c7c3f2
DateCreated
28/04/2021

7418db3a-6de6-4657-ac0a-c12585c7c3f2
Filesize
3345

I am using the code from the following website as my starting point:
http://andreyzavadskiy.com/2017/07/03/converting-list-to-idatareader/
For ease, I have copied the code below
public class ListDataReader<T> : IDataReader
        where T : class
{
    #region Private fields
    private IEnumerator<T> _iterator;
    private List<PropertyInfo> _properties = new List<PropertyInfo>();
    #endregion

    #region Public properties
    #endregion

    #region Constructors
    public ListDataReader(IEnumerable<T> list)
    {
        this._iterator = list.GetEnumerator();

        _properties.AddRange(
            typeof(T).GetProperties(
                BindingFlags.GetProperty |
                BindingFlags.Instance |
                BindingFlags.Public |
                BindingFlags.DeclaredOnly
                )
            );
    }
    #endregion

    #region IDataReader implementation
    public int Depth { get; }
    public bool IsClosed { get; }
    public int RecordsAffected { get; }

    public void Close()
    {
        _iterator.Dispose();
    }

    public DataTable GetSchemaTable()
    {
        throw new NotImplementedException();
    }

    public bool NextResult()
    {
        throw new NotImplementedException();
    }

    public bool Read()
    {
        return _iterator.MoveNext();
    }
    #endregion

    #region IDisposable implementation
    public void Dispose()
    {
        Close();
    }
    #endregion

    #region IDataRecord
    public string GetName(int i)
    {
        return _properties[i].Name;
    }

    public string GetDataTypeName(int i)
    {
        throw new NotImplementedException();
    }

    public Type GetFieldType(int i)
    {
        return _properties[i].PropertyType;
    }

    public object GetValue(int i)
    {
        return _properties[i].GetValue(_iterator.Current, null);
    }

    public int GetValues(object[] values)
    {
        int numberOfCopiedValues = Math.Max(_properties.Count, values.Length);

        for (int i = 0; i < numberOfCopiedValues; i++)
        {
            values[i] = GetValue(i);
        }

        return numberOfCopiedValues;
    }

    public int GetOrdinal(string name)
    {
        var index = _properties.FindIndex(p => p.Name == name);

        return index;
    }

    public bool GetBoolean(int i)
    {
        return (bool) GetValue(i);
    }

    public byte GetByte(int i)
    {
        return (byte) GetValue(i);
    }

    public long GetBytes(int i, long fieldOffset, byte[] buffer, int bufferoffset, int length)
    {
        throw new NotImplementedException();
    }

    public char GetChar(int i)
    {
        return (char) GetValue(i);
    }

    public long GetChars(int i, long fieldoffset, char[] buffer, int bufferoffset, int length)
    {
        throw new NotImplementedException();
    }

    public Guid GetGuid(int i)
    {
        return (Guid) GetValue(i);
    }

    public short GetInt16(int i)
    {
        return (short) GetValue(i);
    }

    public int GetInt32(int i)
    {
        return (int) GetValue(i);
    }

    public long GetInt64(int i)
    {
        return (long) GetValue(i);
    }

    public float GetFloat(int i)
    {
        return (float) GetValue(i);
    }

    public double GetDouble(int i)
    {
        return (double) GetValue(i);
    }

    public string GetString(int i)
    {
        return (string) GetValue(i);
    }

    public decimal GetDecimal(int i)
    {
        return (decimal) GetValue(i);
    }

    public DateTime GetDateTime(int i)
    {
        return (DateTime) GetValue(i);
    }

    public IDataReader GetData(int i)
    {
        throw new NotImplementedException();
    }

    public bool IsDBNull(int i)
    {
        return GetValue(i) == null;
    }

    public int FieldCount
    {
        get { return _properties.Count; }
    }

    object IDataRecord.this[int i]
    {
        get { return GetValue(i); }
    }

    object IDataRecord.this[string name]
    {
        get { return GetValue(GetOrdinal(name)); }
    }
    #endregion
}

Can anyone give any guidance on how to amend this to produce the output I want?

A: You can use LINQ's SelectMany with yield return to pass through multiple records to the ListDataReader's constructor, because it will accept any IEnumerable<T>:
var list = new List<Document> {
    new Document {
        Guid = 7418db3a-6de6-4657-ac0a-c12585c7c3f2 ,
        Name = "Test Document",
        DateCreated = 28/04/2021,
        Filesize = 3345,
    }
};

var reader = NewListDataReader(list.SelectMany(doc =>
    new []
    {
        new {
            DocumentGUID = doc.Guid,
            AttributeName = "Name",
            AttributeValue = doc.Name,
        },
        new {
            DocumentGUID = doc.Guid,
            AttributeName = "DateCreated",
            AttributeValue = doc.DateCreated.ToString(),
        },
        new {
            DocumentGUID = doc.Guid,
            AttributeName = "Filesize",
            AttributeValue = doc.Filesize.ToString(),
        },
    }));

You also need this little helper function for anonymous types:
ListDataReader NewListDataReader<T>(IEumerable<T> source)
{
    return new ListDataReader(source);
}

Or you could even make a separate struct instead of the anonymous object:
struct Record
{
    public Guid DocumentGUID;
    public string AttributeName;
    public string AttributeValue;
}


text:
Q: Detect high variability of signal I have a signal that alternate between a high values and low values. Now I want to detect the window where there is a higher variability of the signal to detect abnormal behavior of the system. How can I do that with Python ?
EDIT:
I think that the problem would be solved if I have a function that returns a frequency estimation over a set of data (sample/window of the signal).


text:
Q: Adding Show and Hide button to BottomNavigationView I have this code;
<android.support.design.internal.BottomNavigationItemView
    android:layout_height="wrap_content"
    android:layout_width="match_parent">

    <ListView
        android:id="@+id/list_time"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:divider="#E0E0E0"
        android:dividerHeight="4px" />

</android.support.design.internal.BottomNavigationItemView>

I want to add a bar with a "Show" and "Hide" button to this ItemView. When i click show it will show ListView, when hide it will hide this ListView. Can i do it?

A: You can use these methods to show and hide
    v.setVisibility(View.INVISIBLE);
    v.setVisibility(View.VISIBLE);

A: Or if you want to hide and use the place for other layout components you can use:
v.setVisibility(View.GONE);

A: The show and hide functionality is already given on the answers, so I will add the example for "bar with a Show and Hide button"
<android.support.design.internal.BottomNavigationItemView
    android:layout_width="match_parent"
    android:layout_height="wrap_content">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        android:weightSum="2"
        android:background="#123123">

        <Button
            android:id="@+id/btn_show"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="Show" />

        <Button
            android:id="@+id/btn_hide"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="Hide" />
    </LinearLayout>

    <ListView
        android:id="@+id/list_time"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:divider="#E0E0E0"
        android:dividerHeight="4px" />

</android.support.design.internal.BottomNavigationItemView>

Then apply the onclick functions of the buttons using the other answers.


text:
Q: change width of number clickpick component of Mobiscroll Good day,
There seems to be a bug in Mobiscroll's "number" component because no matter what I try I just can't make the width size I specify.  I must use version 2.14.0 or greater because Custom Theme Builder doesn't work with older versions.  I can resize width on older versions but I cannot use theme builder on older versions.  So I am using Mobiscroll version 2.14.3 with my custom theme.  Below is how I simply use default ios7 theme and width settings still don't work:
showPassengerPicker('#numAdults_rt', '#numChildren_rt', '#numInfants_rt');

function showPassengerPicker(var1, var2, var3)
{
     $(var1).mobiscroll().number({
         theme: 'ios7',
         display: 'inline',
         language: 'en',
         mode: 'clickpick',
         showLabel: false,
         maxWidth: 40,
         minWidth: 40,
         fixedWidth: 40,
         height: 20,
         rows: 3,
         wheels: [
                   [
                    {
                        label: '',
                        keys: [1, 2, 3, 4, 5],
                        values: ['1', '2', '3', '4', '5']
                    }
                   ]
                 ]
         });
}

I am using all available settings in Mobiscroll's docs for setting width but none of them work.
And this is the HTML part:

Please, could somebody let me know how I can reduce the width of number clickpick component so it would have reduced width?  I need to reduce the width but none of the settings work.  What am I doing wrong?
Thank you so much in advance,
Victor.

A: I found the answer by luck.  In mobiscroll.custom-2.14.3.min.css there is a min-width element.  I set min-width:0 everywhere where it had non-zero pixel value.  Now these controls don't have extra space on both sides.


text:
Q: How to install JDK in linux centOS am new to Linux, am trying to install java jdk in linux centOA (which is already downloaded and placed in file manager folder). could you please help me out how to install with commands.

A: Check out this link that provides some options


text:
Q: Show result of this cmdlet: Unlock-ADAccount So basic a question but I cannot find an elegant, easy answer that I know exists. I want to know the result of this command so that I can modify what the script does afterwards:
Unlock-ADAccount -Identity user1234

A: You can evaluate the automatic variable $? to see if the command was successful or not:
Unlock-ADAccount -Identity 'user1234'
if ($?) {
  'Account unlocked.'
} else {
  'Unlocking failed.'
}

Or you can run the command with the parameter -PassThru, so it returns the user object, allowing you to check the lockout status:
Unlock-ADAccount -Identity 'user1234' -PassThru |
  Get-ADUser -Property 'LockedOut' |
  select -Expand 'LockedOut'

You need the additional Get-ADUser, because the default property set does not include the property LockedOut.


text:
Q: how to load fontawesome css only when an icon is used? As it appears here: http://fontawesome.io/get-started/ I don't see any way I can have the min.css file loaded in the head only when an icon is used on the frontend.
I don't want to load that css file on all pages, maybe someone using my theme/plugin may not even use an icon at all! This means one more unnecessary server request. You think I can manage that with fontawesome?
Using WordPress by the way but I think it's the same with any CMS/project.
Thanks a lot!

A: Maybe use Google Tag Manager to load the .css file only on that particular page you are using it? Use custom HTML as the tag, triggered by a single view on the page you want.

A: You can first check if there is any class available on the page, if not then exclude it if true then load. like this in jQuery:
 if ( $('.fa').length > 0 ) { code here }

I havent looked at the documentation but i think FontAwsome uses .fa as classname


text:
Q: Merge data in one table SQL I have 2 tables A, B
Table A:
ID      Value1   Value2
------------------------
1000     10        25
1001      4        12
1002      2         6
1003      1         8

Table B:
ID      Value3   Value4
------------------------
1000     51        12
1003      3        10

What I need is to show the below result:
ID     Value1   Value2   Value3   Value4
-----------------------------------------
1000    10       25       51       12
1001     4       12       NULL     NULL
1002     2        6       NULL     NULL
1003     1        8        3       10

The query I've tried:
SELECT I.AgentId AS AGENT
    ,COUNT(I.Indice) AS [Number of Inbound calls]
    ,AVG(I.WrapupDuration) AS [AVG Wrapup IN]
    ,COUNT(O.Indice) AS [Number of Out calls]
    ,AVG(O.WrapupDuration) AS [AVG Wrapup Out]
FROM [HN_Ondata].[dbo].[vwInboundCalls] I
LEFT JOIN [HN_Ondata].[dbo].vwOutboundCalls O
    ON I.AgentId = O.AgentId
GROUP BY I.AgentId

A: You just need a LEFT JOIN and a query like below, you don't need another table:
SELECT *
FROM TABLE_A A
    LEFT JOIN TABLE_B B ON A.ID = B.ID

A: You have to use LEFT JOIN to achieve your goal.
SELCT * FROM TABELA LEFT JOIN TABLEB ON TABLEA.ID = TABLEB.ID

A: You should use left join
SELECT
     *
FROM
     TABLEA T1
LEFT JOIN
     TABLEB T2
ON
     T1.ID = T2.ID

The LEFT JOIN keyword returns all rows from the left table (table1), with the matching rows in the right table (table2). The result is NULL in the right side when there is no match.


text:
Q: flutter compute function is not working while clicking photo I am making a camera app
but it is not returning File after clicking photo in compute function but when I don't use compute function it returns. here is the code
Future<XFile?> takePicture() async {
// final CameraController? cameraController = camController;

if (controller != null) {
  if (controller!.value.isTakingPicture) {
    // A capture is already pending, do nothing.
    return null;
  }

  try {
    XFile? file = await compute(takePictureCompute, " ");
    log('file received --> ${file?.path}');  /// file?.path is giving null
    return file;
  } on CameraException catch (e) {
    print('Error occured while taking picture: $e');
    return null;
  }
}
return null;
}

static Future<XFile?> takePictureCompute(String val) async {
log('this is initilalized');

return await controller?.takePicture();
}

I am using Camera package ; Please help how can I do it .


text:
Q: I have a 'UIImage' and I want to convert it to NSData to upload on firebase storage I want to upload an Image of type Jpeg to firebase storage
Below is the function to upload to firebase storage
func uploadImageToFirebase (data: NSData){

         let StorageRef = Storage.storage().reference().child("User Products")
        let uploadMetadata = StorageMetadata()
        uploadMetadata.contentType = "image/jpeg"
        StorageRef.putData(data as Data, metadata: uploadMetadata) { (metadata, error) in
            if (error != nil){

                print("I have an error")
            }else {
                print("upload metadata \(String(describing: metadata))")
            }

        }

Here I have the picker controller function which is located in another class called CamViewController
here I call the function from Mainviewcontroller class
var discover = MainViewController()
 func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
        let image = info[UIImagePickerController.InfoKey.originalImage] as? UIImage
          imageCam.image = image

        discover.uploadImageToFirebase(data: image)

        picker.dismiss(animated: true, completion: nil)

    }

I get the error:

Cannot convert value of type UIImage? to expected argument type NSData

A: You need
func uploadImageToFirebase (_ image:UIImage){
  gurad let data = image.pngData() else { return }
  ..... OR
  guard let data = image.jpegData(compressionQuality: 0.5) else { return }

}

discover.uploadImageToFirebase(image)

the error is clear the parameter type is NSData so you can't pass a UIImage


text:
Q: Name of Shift-Key Concept What is the name of the concept or type of key used in shifting characters on a mobile device?
Many common virtual keyboards used in cellphones and advanced mobile devices use a certain paradigm for dealing with shifted characters:

*

*Hitting shift once results in it being depressed for one character - i.e. until the next regular keypress

*Hitting shift a second time locks the shift key indefinitely through multiple keypresses, as with Caps Lock.

*Hitting shift a third time undoes the lock from the second press.

What is it called when the shift key is used this way?  Is it called both "Shift" and "Caps Lock" at the same time?  It has some similarities to the StickyKeys system used by Windows - is it called a "sticky" system of some sort?  Is it a "Shift Lock" or a "Sticky Lock?"

A: It is a toggle rather than a key. Keys and buttons rebound on their own, toggles do not, they flip to the other state.

A: I believe what you are describing is vary similar to sticky keys. I don't believe it has a specific name, however. So I would call it sticky keys.


text:
Q: Nuget Packages missing for IOS in Xamarin Forms Solution in Visual Studio for Mac For some reason that I haven't been able to figure out my packages seem to be missing. If I click 'Restore Packages' everything works fine.
If I add 1 more, it shows that thats the only package I have. I just don't have the option to update packages through the Package Manager.
Here is what I have:

I have researched havent found anything. My droid project works fine. I have compared both .csproj and they seem very similar. Here is the section where the packages are:
  <ItemGroup>
    <Reference Include="System" />
    <Reference Include="System.Xml" />
    <Reference Include="System.Core" />
    <Reference Include="Xamarin.iOS" />
    <Reference Include="Plugin.MediaManager.Abstractions">
      <HintPath>..\packages\Plugin.MediaManager.0.4.5\lib\Xamarin.iOS10\Plugin.MediaManager.Abstractions.dll</HintPath>
    </Reference>
    <Reference Include="Plugin.MediaManager">
      <HintPath>..\packages\Plugin.MediaManager.0.4.5\lib\Xamarin.iOS10\Plugin.MediaManager.dll</HintPath>
    </Reference>
    <Reference Include="Plugin.Settings.Abstractions">
      <HintPath>..\packages\Xam.Plugins.Settings.3.1.1\lib\Xamarin.iOS10\Plugin.Settings.Abstractions.dll</HintPath>
    </Reference>
    <Reference Include="Plugin.Settings">
      <HintPath>..\packages\Xam.Plugins.Settings.3.1.1\lib\Xamarin.iOS10\Plugin.Settings.dll</HintPath>
    </Reference>

Does anyone has a clue on how to fix this?
Thanks

A: Thanks for all the comments. I have found the problem.
A few weeks ago, I got some errors while building the solution and one of the recommended solution was to add this to the .csproj:
<RestoreProjectStyle>PackageReference</RestoreProjectStyle>
That turn out to be the culprit of the problem. I removed that line and everything started to work again.


text:
Q: I type text in my box and it moves the more I type This is my HTML I have 3 boxes with text in them just read the text within the first div.

html,
body {
 background-position: fixed;
 background-attachment: fixed;
 background-size: auto;
 background-color: #e2e1e0;
 background-repeat: no-repeat;
 -webkit-touch-callout: none; /* iOS Safari */
 -webkit-user-select: none;   /* Chrome/Safari/Opera */
 -khtml-user-select: none;    /* Konqueror */
 -moz-user-select: none;      /* Firefox */
 -ms-user-select: none;       /* IE/Edge */
 user-select: none;
 z-index: 1;
}

.header{
font-family: 'Poiret One', Arial;
color: black;
font-size: 2em;
border-radius: 10px;
border-color: black;
border-style:
}

.infodiv {
  background: #fff;
  border-radius: 5px;
  display: inline-block;
  height: 300px;
  margin: 1rem;
  width: 300px;
}

.statsdiv {
  box-shadow: 0 1px 3px rgba(0,0,0,0.12), 0 1px 2px rgba(0,0,0,0.24);
  transition: all 0.3s cubic-bezier(.25,.8,.25,1);
  font-family: 'Oswald', Arial;
}

.statsdiv:hover {
  box-shadow: 0 14px 28px rgba(0,0,0,0.25), 0 10px 10px rgba(0,0,0,0.22);
}

.playerdiv {
  box-shadow: 0 1px 3px rgba(0,0,0,0.12), 0 1px 2px rgba(0,0,0,0.24);
  transition: all 0.3s cubic-bezier(.25,.8,.25,1);
  font-family: 'Oswald', Arial;
}

.playerdiv:hover {
  box-shadow: 0 14px 28px rgba(0,0,0,0.25), 0 10px 10px rgba(0,0,0,0.22);
}

.seconddiv {
  box-shadow: 0 1px 3px rgba(0,0,0,0.12), 0 1px 2px rgba(0,0,0,0.24);
  transition: all 0.3s cubic-bezier(.25,.8,.25,1);
  font-family: 'Oswald', Arial;
}

.seconddiv:hover {
  box-shadow: 0 14px 28px rgba(0,0,0,0.25), 0 10px 10px rgba(0,0,0,0.22);
}

  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">

Heading Placeholder

This first box moves the more I type, it allows me to type up to 3 lines of text but after that it becomes higher in position for example here X X X

This is a current place holder for any text that I plan on putting here in the future. Don't mind this.

This is a current place holder for any text that I plan on putting here in the future. Don't mind this.

I don't think it works well but if you could put it in a notepad real quick it should do the problem that I am having. Currently in the HTML I put 3 letter 'X's remove those 3 X's and the problem should be solved. The issue is that it is only letting me add 3 lines of text.
If you do not understand what I am still trying to say please let me know. I only took 1 class of Computer Science in high school a few years ago so it may be pretty ugly :/

A: Add this CSS
 .infodiv {
  float: left;
  background: #fff;
  border-radius: 5px;
  display: inline-block;
  height: 300px;
  margin: 1rem;
  width: 300px;
 }

A: add  vertical-align:top; to your .infodiv
i.e.:
.infodiv {
  background: #fff;
  border-radius: 5px;
  display: inline-block;
  height: 300px;
  margin: 1rem;
  width: 300px;
  vertical-align:top;
}


text:
Q: Delete topic in Kafka 0.8.1.1 I need to delete the topic test in Apache Kafka 0.8.1.1.
As expressed in the documentation here, I have executed:
bin/kafka-topics.sh --zookeeper localhost:2181 --delete --topic test

However, this results in the following message:
Command must include exactly one action: --list, --describe, --create or --alter

How can I delete this topic?

A: It seems that the deletion command was not officially documented in Kafka 0.8.1.x because of a known bug (https://issues.apache.org/jira/browse/KAFKA-1397).
Nevertheless, the command was still shipped in the code and can be executed as:
bin/kafka-run-class.sh kafka.admin.DeleteTopicCommand --zookeeper localhost:2181 --topic test

In the meantime, the bug got fixed and the deletion command is now officially available from Kafka 0.8.2.0 as:
bin/kafka-topics.sh --delete --zookeeper localhost:2181 --topic test

A: Steps to Delete 1 or more Topics in Kafka
#To delete topics in kafka the delete option needs to be enabled in Kafka server.
1. Go to {kafka_home}/config/server.properties
2. Uncomment delete.topic.enable=true
#Delete one Topic in Kafka enter the following command
kafka-topics.sh --delete --zookeeper localhost:2181 --topic <your_topic_name>

#To Delete more than one topic from kafka
(good for testing purposes, where i created multiple topics & had to delete them for different scenarios)

*

*Stop the Kafka Server and Zookeeper

*go to server folder where the logs are stored (defined in their config files) and delete the kafkalogs and zookeeper folder manually

*Restart the zookeeper and kafka server and try to list topics,

bin/kafka-topics.sh --list --zookeeper localhost:2181
if no topics are listed then the all topics have been deleted successfully.If topics are listed, then the delete was not successful. Try the above steps again or restart your computer.

A: Add below line in ${kafka_home}/config/server.properties
delete.topic.enable=true

Restart the kafka server with new config:
${kafka_home}/bin/kafka-server-start.sh ~/kafka/config/server.properties

Delete the topics you wish to:
${kafka_home}/bin/kafka-topics.sh --delete  --zookeeper localhost:2181  --topic daemon12

A: You can delete a specific kafka topic (example: test) from zookeeper shell command (zookeeper-shell.sh).  Use the below command to delete the topic
rmr {path of the topic}

example:
rmr /brokers/topics/test

A: This steps will delete all topics and data

*

*Stop Kafka-server and Zookeeper-server

*Remove the data directories of both services, by default on windows they are
C:/tmp/kafka-logs and C:/tmp/zookeeper.

*then start Zookeeper-server and Kafka-server

A: As mentioned in doc here

Topic deletion option is disabled by default. To enable it set the server config
  delete.topic.enable=true
  Kafka does not currently support reducing the number of partitions for a topic or changing the replication factor.

Make sure delete.topic.enable=true

A: The command:
bin/kafka-topics.sh --delete --zookeeper localhost:2181 --topic test

unfortunately only marks topic for deletion.
Deletion does not happen.
That makes troubles, while testing any scripts, which prepares Kafka configuration.
Connected threads:

*

*Purge Kafka Queue

*Is there a way to delete all the data from a topic or delete the topic before every run?

A: Deleting topic isn't always working in 0.8.1.1
Deletion should be working in the next release, 0.8.2
kafka-topics.sh --delete --zookeeper localhost:2181 --topic your_topic_name

  Topic your_topic_name is marked for deletion.
  Note: This will have no impact if delete.topic.enable is not set to true.

You may also pass in a bootstrap server instead of zookeeper:
kafka-topics.sh --bootstrap-server kafka:9092 --delete --topic your_topic_name

Is it possible to delete a topic?
Jira KAFKA-1397

A: Andrea is correct. we can do it using command line.
And we still can program it, by
ZkClient zkClient = new ZkClient("localhost:2181", 10000);
zkClient.deleteRecursive(ZkUtils.getTopicPath("test2"));

Actually I do not recommend you delete topic on Kafka 0.8.1.1. I can delete this topic by this method, but if you check log for zookeeper, deletion mess it up.

A: Adding to above answers one has to delete the meta data associated with that topic in zookeeper consumer offset path.
bin/zookeeper-shell.sh zookeeperhost:port
rmr /consumers/<sample-consumer-1>/offsets/<deleted-topic>
Otherwise the lag will be negative in kafka-monitoring tools based on zookeeper.

A: First, you run this command to delete your topic:
$ bin/kafka-topics.sh --delete --bootstrap-server localhost:9092 --topic <topic_name>

List active topics to check delete completely:
$ bin/kafka-topics.sh --list --bootstrap-server localhost:9092

A: This worked for me:
kafka-topics --delete --bootstrap-server localhost:9092 --topic  user-commands
I am using Confluent CLI and run this on the directory I installed it.

A: bin/kafka-topics.sh --delete --zookeeper localhost:2181 --topic <topic-name>

A: If you have issues deleting the topics, try to delete the topic using:
$KAFKA_HOME/bin/kafka-topics.sh --delete --zookeeper localhost:2181 --topic your_topic_name

command. Then in order to verify the deletion process, go to the kafka logs directory which normally is placed under /tmp/kafka-logs/, then delete the your_topic_name file via rm -rf your_topic_name command.
Remember to monitor the whole process via a kafka management tool like Kafka Tool.
The mentioned process above will remove the topics without kafka server restart.

A: Step 1: Make sure you are connected to zookeeper and Kafka running
Step 2: To delele the Kafka topic run kafka-topics script, add the port and --topic with name of your topic and --delete it just delete the topic with success.
# Delete the kafka topic
# it will delete the kafka topic
bin/kafka-topics.sh --zookeeper 127.0.0.1:2181 --topic name_of_topic --delete

A: There is actually a solution without touching those bin/kafka-*.sh: If you have installed kafdrop, then simply do:
url -XPOST http://your-kafdrop-domain/topic/THE-TOPIC-YOU-WANT-TO-DELETE/delete

A: Recent Kafka versions are about to remove the Zookeeper dependency. Therefore, you should instead reference the brokers (through --boostrap-server):
kafka-topics \
    --bootstrap-server localhost:9092,localhost:9093,localhost:9094 \
    --delete \
    --topic topic_for_deletion

A: for confluent cloud use -
$ confluent kafka topic delete my_topic


text:
Q: Using a custom sbt plugin I've created a new scala project and written an AutoPlugin underneath it in a src/main/scala/com/company/plugin directory and a corresponding namespace.  The plugin code is a cut and paste of HelloPlugin3 from [1], however I have changed the names.
Then, in a second sbt project I've updated the project/plugins.sbt file to include my new Hello World plugin.  This second project has other 'business code' in.  When I run sbt in that second project, the plugin is resolved and I've tested that by deleting the jar from underneath the ~/.ivy/local/... and then reloading the project and witnessing sbt complain that it can't find the plugin.  When I publishLocal my plugin project again, that error goes away.
So I'm happy that the plugin is resolved and the jar file is not empty because I have checked its contents.
However, when I do an sbt> about my custom plugin isn't listed and the command I was expecting to be available isn't.  ("[error] Not a valid command: hello").  But the other plugin I list in plugins.sbt (io.spray sbt-revolver) does appear in the output.
Both the plugin project and the second project have scalaVersion  := "2.10.3" specified in their build.sbt files.
I'm using sbt 0.13.6.  Interestingly, and perhaps related, is the sbt command plugins is not apparently valid in this project either, although it works just fine in the plugin project.
What extra step am I missing to make the command available to my second project?  How do I check to see if I've got some particularly messed up sbt config happening?
For convenience, the plugin code is below, but as mentioned, it's a copy from the link underneath it.
package com.company.plugin

import sbt._
import Keys._

object HelloPlugin extends AutoPlugin {

  object autoImport {
    val greeting = settingKey[String]("greeting")
  }

  import autoImport._
  override def trigger = allRequirements
  override lazy val buildSettings = Seq(
    greeting := "Hi",
    commands += helloCommand)
  lazy val helloCommand =
    Command.command("hello") { (state: State) =>
      println("fred")
      state
    }

}

Edit:
The build.sbt for the plugin project as as follows;
sbtPlugin := true

scalaVersion  := "2.10.3"

organization  := "com.company"

name    := "name"

version   := "0.0.1-SNAPSHOT"

The only other file I've created in this project is the .scala file for the plugin itself.
[1] http://www.scala-sbt.org/release/docs/Plugins.html

A: The problem ended up being with the project/build.properties of the project trying to use the plugin.  This file set the sbt version to 0.13.1, which for some reason cases both my plugin and the sbt plugins command to not work.
Changing the value to 0.13.6 made all the problems go away.


text:
Q: Fixed identifier for a machine (uuid.getnode) I'm trying to find something I can use as a unique string/number for my script that is fixed in a machine and easily obtainable(cross-platform). I presume a machine would have a network card. I don't need it to be really unique, but the necessary is it should be fixed in a long run and as rare as possible.
I know MAC can be changed and I'd probably make a warning about it in my script, however I don't expect anyone to change MAC each morning.
What I came up with is uuid.getnode(), but in the docs there is:

If all attempts to obtain the hardware address fail, we choose a random 48-bit number

Does it mean that for each function call I get another random number, therefore it's not possible to use it if MAC is unobtainable?

...on a machine with multiple network interfaces the MAC address of any one of them may be returned.

Does this sentence mean getnode() gets a random(or first) MAC from all available? What if it'd get MAC A in first run and MAC B next time? There'd be no problem if I'd get a fixed list(sort, concatenate, tadaaa!)
I'm asking because I have no way how to test it myself.

A: I managed to test the first part on my android device and on each new python run it created random number, so it's not usable at all for this purpose.
The second problem kind of drowned itself, because if in the docs it mentioned that it may return any one of them, then it's not something you could rely on (+I couldn't find a machine I could test it on). A nice package netifaces came to rescue, which does a similar thing
netifaces.interfaces() # returns e.g. ['lo', 'eth0', 'tun2']

netifaces.ifaddresses('eth0')[netifaces.AF_LINK]
# returns [{'addr': '08:00:27:50:f2:51', 'broadcast': 'ff:ff:ff:ff:ff:ff'}]

However I rather gave up using MACs, I got something rather more stable.
Now to the identifiers:
1) Windows:
Executing this one and getting output may be good enough:
wmic csproduct get UUID

or the one I used and is available in registry (HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Cryptography):
import _winreg
registry = _winreg.HKEY_LOCAL_MACHINE
address = 'SOFTWARE\\Microsoft\\Cryptography'
keyargs = _winreg.KEY_READ | _winreg.KEY_WOW64_64KEY
key = _winreg.OpenKey(registry, address, 0, keyargs)
value = _winreg.QueryValueEx(key, 'MachineGuid')
_winreg.CloseKey(key)
unique = value[0]

2) Linux:
/sys/class/dmi/id/board_serial

or
/sys/class/dmi/id/product_uuid

or if not root:
cat /var/lib/dbus/machine-id

3) Android:
If you are working with python and don't want to mess with Java stuff, then this should work pretty good:
import subprocess
cmd = ['getprop', 'ril.serialnumber']
self.unique = subprocess.check_output(cmd)[:-1]

but if you like Java, then go for this answer although even ANDROID_ID's uniqueness is rather debatable if it's allowed to change, therefore a serial number is most likely a safer bet.
Note that like it's already mentioned in the linked answer, even ril.serialnumber can be null/empty or non-existing (missing key). Same thing happens even with the official Android API where it's clearly stated this:

A hardware serial number, if available.

Mac/iPhone:
I couldn't find any solution as I don't have access to any of these, but if there is a variable that holds the machine id value, then you should be able to get there with simple subprocess.check_output()

A: I wouldn't recommend using a MAC address for a unique machine identifier, since it can change depending on the network being used. Rather, I'd recommend using the machine's native GUID, assigned by the operating system during install. I wrote a small, cross-platform PyPI package that queries a machine's native GUID called py-machineid.
Essentially, it looks like this, but with some Windows-specific WMI registry queries for more a accurate ID. The package also has support for hashing the ID, to anonymize it.
import subprocess
import sys

def run(cmd):
  try:
    return subprocess.run(cmd, shell=True, capture_output=True, check=True, encoding="utf-8") \
                     .stdout \
                     .strip()
  except:
    return None

def guid():
  if sys.platform == 'darwin':
    return run(
      "ioreg -d2 -c IOPlatformExpertDevice | awk -F\\\" '/IOPlatformUUID/{print $(NF-1)}'",
    )

  if sys.platform == 'win32' or sys.platform == 'cygwin' or sys.platform == 'msys':
    return run('wmic csproduct get uuid').split('\n')[2] \
                                         .strip()

  if sys.platform.startswith('linux'):
    return run('cat /var/lib/dbus/machine-id') or \
           run('cat /etc/machine-id')

  if sys.platform.startswith('openbsd') or sys.platform.startswith('freebsd'):
    return run('cat /etc/hostid') or \
           run('kenv -q smbios.system.uuid')

A: For Mac/iphone you can try below command:
import subprocess
subprocess.check_output("ioreg -rd1 -c IOPlatformExpertDevice | grep -E '(UUID)'", shell=True).split('"')[-2] # for me i got it on list value -2 if having any trouble try getting it with any alternative list element.

A: uuid.getnode will return the same value for every call wthinin a single run of your app. If it has to defer to the random algorithm, then you will get a different value when you start a new instance of your app.
The implementation for getNode shows why. This is sort of what the routine looks like in python 3.7 (comments mine, code simplified for clarity)
_node = None

def getnode():

    global _node
    if _node is not None:
        # Return cached value
        return _node

    # calculate node using platform specific logic like unix functions, ifconfig, etc
    _node = _get_node_from_platform()
    if not _node:
        # couldn't get node id from the system. Just make something up
        _node = _get_random_node()
    return _node


text:
Q: load a trained model in other process with tflearn I am trying to save a model and load it in other process with tflearn library...
So I generated the model:
lenx = 21908
leny = 81
# Build neural network
net = tflearn.input_data(shape=[None, lenx])
net = tflearn.fully_connected(net, 8)
net = tflearn.fully_connected(net, 8)
net = tflearn.fully_connected(net, leny, activation='softmax')
net = tflearn.regression(net)

# Define model and setup tensorboard
model = tflearn.DNN(net, tensorboard_dir='tflearn_logs')
# Start training (apply gradient descent algorithm)
model.fit(train_x, train_y, n_epoch=10, batch_size=8, show_metric=True)
model.save('model.tflearn')

That works Ok!
Then in other file, to run in other process I am trying to load it, in this way:
lenx = 21908
leny = 81
# Build neural network
net = tflearn.input_data(shape=[None, lenx])
net = tflearn.fully_connected(net, 8)
net = tflearn.fully_connected(net, 8)
net = tflearn.fully_connected(net, leny, activation='softmax')
net = tflearn.regression(net)

model = tflearn.DNN(net, tensorboard_dir='tflearn_logs')

model.load("model.tflearn")

But I got this error:
ValueError: Cannot feed value of shape (1, 0) for Tensor 'InputData/X:0', which has shape '(?, 21908)'

I have tried many things but it does not work.

A: The architecture of the neural net that you'll be
loading should be the same. Also, you do not have to define
the final layer, because there
will be no training. Don't use the line
net = tflearn.regression(net)

A: I think what you're missing is a "weights_only=True" argument in the load:
model.load("model.tflearn", weights_only=True)


text:
Q: EXTJS 5 : How to sort grid column in EXT JS 5 I recently updated version of EXT JS to 5 and and override of doSort function no longer works. Someone an idea how to do ?
Exampple of override :
{
    text: 'Custom',
    sortable : true,
    dataIndex: 'customsort',
    doSort: function(state) {
        var ds = this.up('grid').getStore();
        var field = this.getSortParam();
        ds.sort({
            property: field,
            direction: state,
            sorterFn: function(v1, v2){
                v1 = v1.get(field);
                v2 = v2.get(field);

                return v1.length > v2.length ? 1 : (v1.length < v2.length ? -1 : 0);
            }
        });
    }
}

Edit 1 :
I just try the solution of @tomgranerod but the me.sortState is always 'undefined'.
So I do this to update my variable :
    sort: function () {
        var me = this,
            grid = me.up('tablepanel'),
            store = grid.store;

        me.sortState = me.sortState === 'ASC' ? 'DESC' : 'ASC';

        Ext.suspendLayouts();
        me.sorting = true;
        store.sort({
            property: me.getSortParam(),
            direction: me.sortState,
            sortFn: function (v1, v2) {
                v1 = v1.get(field);
                v2 = v2.get(field);

                return v1.length > v2.length ? 1 : (v1.length < v2.length ? -1 : 0);
            }
        });
        delete me.sorting;
        Ext.resumeLayouts(true);
    }

But the sortFn funcion is never called. I don't know why.
===> !!!! it works with EXT JS 5.0.1 but the sortFin function is always never called. !!!!
Edit 2 :
This is what i attempt to have :
ASC :
if (v1 and v2 are numbers) return v1 > v2;
else if (v1 is a number and v2 a string) return false;
else if (v1 is a string and v2 a number) return true;
else if (v1 and v2 are strings) return v1 > v2;

DESC :
if (v1 and v2 are numbers) return v1 < v2;
else if (v1 is a number and v2 a string) return true;
else if (v1 is a string and v2 a number) return false;
else if (v1 and v2 are strings) return v1 < v2;

A: You were overriding a private method. So it's almost expected that it would break after a major release. If you look at http://docs.sencha.com/extjs/5.0.0/apidocs/source/Column2.html#Ext-grid-column-Column You'll see that there's no doSort function anymore.
Ext's suggested way is by to use sortType config can take a function which converts your value into something that sorts naturally, usually the easiest thing is to convert it into a number. So if you want something slightly different, you can modify the code I've posted to do what you want without overriding private methods.
Running Example: https://fiddle.sencha.com/#fiddle/8km
var store = Ext.create('Ext.data.Store', {
    fields: [{
        name: 'ref',
        sortType: function(str)  {
            // Ext-JS requires that you return a naturally sortable value
            // not your typical comparator function.
            // The following code puts all valid integers in the range
            // Number.MIN_SAFE_INTEGER and 0
            // And assumes the other values start with T and sorts
            // them as positive integers
            var parsed = parseInt(str, 10);
            if ( isNaN( parsed ) ){
                return parseInt(str.substring(1), 10);
            } else {
                return Number.MIN_SAFE_INTEGER + parsed;
            }
        }
    }],
    data: {
        'items': [
            {'ref': '1'},
            {'ref': '12'},
            {'ref': 'T0134'},
            {'ref': '121878'},
            {'ref': 'T0134343'},
            {'ref': 'T01POPI'},
            {'ref': '103'},
            {'ref': 'T01'}
        ]
    },
    proxy: {
        type: 'memory',
        reader: {
            type: 'json',
            rootProperty: 'items'
        }
    }
});

Ext.create('Ext.grid.Panel', {
    title: 'Grid custom',
    store: store,
    columns: [{
        text: 'Reference',
        dataIndex: 'ref',
    }],
    height: 300,
    width: 400,
    renderTo: Ext.getBody()
});

If you're going to be reusing this functionality, take a look at http://spin.atomicobject.com/2012/07/20/simple-natural-sorting-in-extjs/
/** Sort on string length  */
Ext.apply(Ext.data.SortTypes, {
    myCrazySorter: function (str) {
        // Same as above
    }
});

// And use it like
var store = Ext.create('Ext.data.Store', {
    fields: [{
        name: 'ref',
        sortType: 'myCrazySorter'
    }],

A: The equivalent function to doSort in ExtJS 5, seem to be 'sort', after a quick look at the source code of Ext.grid.column.Column. The sortState parameter that I've used in this example seem to have been introduced in ExtJS 5.0.1.
sort: function () {
            var me = this,
                grid = me.up('tablepanel'),
                direction,
                store = grid.store;

            direction = me.sortState === 'ASC' ? 'DESC' : 'ASC';

            Ext.suspendLayouts();
            me.sorting = true;
            store.sort({
                sorterFn: function (v1, v2) {
                    v1 = v1.get(me.getSortParam());
                    v2 = v2.get(me.getSortParam());

                    return v1.length > v2.length ? 1 : (v1.length < v2.length ? -1 : 0);
                },
                direction: direction
            });
            delete me.sorting;
            Ext.resumeLayouts(true);
        }

However the solution Juan Mendes describe is a much safer and viable solution than overriding the internal sort function.

A: I finally find a way to compare two records during the sort :
1) Define a custom Column :
Ext.define('Eloi.grid.column.ReferenceColumn', {
    extend : 'Ext.grid.column.Column',

    alias  : 'widget.referencecolumn',

    config : {
        ascSorter  : null,
        descSorter : null
    },

    destroy : function() {
        delete this.ascSorter;
        delete this.descSorter;

        this.callParent();
    },

    /**
     * @param {String} state The direction of the sort, `ASC` or `DESC`
     */
    sort : function(state) {
        var me         = this,
            tablePanel = me.up('tablepanel'),
            store      = tablePanel.store,
            sorter     = this[state === 'ASC' ? 'getAscSorter' : 'getDescSorter']();

        Ext.suspendLayouts();
        this.sorting = true;

        store.sort(sorter, state, 'replace');

        delete this.sorting;
        Ext.resumeLayouts(true);
    },

    getAscSorter : function() {
        var sorter = this.ascSorter;

        if (!sorter) {
            sorter = new Ext.util.Sorter({
                sorterFn  : this.createSorter('ASC'),
                direction : 'ASC'
            });

            this.setAscSorter(sorter);
        }

        return sorter;
    },

    getDescSorter : function() {
        var sorter = this.ascSorter;

        if (!sorter) {
            sorter = new Ext.util.Sorter({
                sorterFn  : this.createSorter('DESC'),
                direction : 'DESC'
            });

            this.setAscSorter(sorter);
        }

        return sorter;
    },

    createSorter : function(state) {
        var dataIndex = this.dataIndex;

        return function(rec1, rec2) {
            var v1   = rec1.get(dataIndex),
                v2   = rec2.get(dataIndex),
                num1 = parseInt(v1),
                num2 = parseInt(v2),
                ret;

            if (num1 && num2) {
                ret = num1 > num2 ? 1 : (num1 < num2 ? -1 : 0);
            } else {
                if (!num1 && !num2) {
                    num1 = parseInt(v1.substr(1));
                    num2 = parseInt(v2.substr(1));

                    ret = num1 > num2 ? 1 : (num1 < num2 ? -1 : 0);
                }
                if (!num1) {
                    ret = 1;
                }
                if (!num2) {
                    ret = -1;
                }
            }

            if (state === 'DESC') {
                ret = ret * -1;
            }

            return ret;
        };
    }
});

2) set the new type to the column in your grid (with alias) and don't forget to set properly the requires config :
columns  : [
        {
            xtype     : 'referencecolumn',
            text      : 'Reference',
            dataIndex : 'ref',
            flex      : 1
        }
    ]

A: You need to use
sorterFn  not  sortFn


text:
Q: What is the difference between passing a function name in onclick react and calling it through callback I want to know the difference between these two statements in react.
<Button onClick={this.Callme}></Button>

<Button onClick={()=>this.Callme()}></Button>

Its just syntax or is there any difference in functionality too.Thanks

A: If the function depends on having a calling context of the instance, and the function isn't bound to the current instance already, the first code won't work, because the this inside callMe will be undefined:

class Component extends React.Component {
  name = 'component_name';
  Callme() {
    console.log(this.name);
  }
  render() {
    return (
      <button onClick={this.Callme}>Click</button>
    );
  }
}

// Render it
ReactDOM.render(
  <Component />,
  document.getElementById("react")
);

The second code works, because the this in the anonymous arrow function will inherit the this from the outer scope, the instance:

class Component extends React.Component {
  name = 'component_name';
  Callme() {
    console.log(this.name);
  }
  render() {
    return (
      <button onClick={() => this.Callme()}>Click</button>
    );
  }
}

// Render it
ReactDOM.render(
  <Component />,
  document.getElementById("react")
);

If the Callme method does not need to refer to the instance, then either type of onClick works.
Other solutions to this common problem include:

*

*Binding the method in the constructor (this.Callme = this.Callme.bind(this))

*Binding the method when setting the callback (onClick={this.Callme.bind(this)}>)

*Defining the method as an arrow function in the constructor (or as a class field), rather than as a property of the prototype
class Component extends React.Component {
  this.Callme = () => {
    console.log(this.name);
  }


text:
Q: How to get data between start and endate and also data must be greater than 2018 in SQL Server I want to fetch data between start and end dates and also only the data which is greater than year 2018.
Example:
if Startdate =  2016-01-01,
   Enddate = 2018-03-01

I need to fetch data only from 2018-01-01 to 2018-03-01.
How to do this in SQL Server?

A: I'll assume you're using @Startdate and @Enddate as parameters.
The easiest way is just include the additional criterion in the WHERE clause.
SELECT *
FROM  mytable mt
WHERE mt.startdate >= @Startdate
      and mt.enddate <= @Enddate
      and mt.startdate  >= '20180101';

This is one of those queries though, that when you see it again in 6 months, you'll ask who the heck wrote that crap (before you realise it was you).
While the above is accurate, a more pleasing version (where the logic is much easier to see) is to modify the @Startdate first
IF @Startdate < '20180101' SET @Startdate = '20180101';

SELECT *
FROM  mytable mt
WHERE mt.startdate >= @Startdate
      and mt.enddate <= @Enddate;

A: So, if @startDate and @endDate are parameters. You have to add a AND in order to check if startDate is greater than your base date (2018)
you can also replace the '2018-01-01' with an @baseDate parameter
SELECT
  *
FROM
  yourTable
WHERE
    yourTable.startDate > @startDate
    AND yourTable.startDate > '2018-01-01'
    AND yourTable.endDate < @endDate


text:
Q: Não consigo colocar simbolo hamburguer no Navigation Drawer Panel Estou a tentar colocar um navigation Drawer Panel na minha app, mas não consigo colocar o simbolo hamburguer na minha MainActivity.
O codigo que estou a usar é:
public class MainActivity extends AppCompatActivity
        implements NavigationView.OnNavigationItemSelectedListener {
@Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_main);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        toggle = new ActionBarDrawerToggle(
                this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
        drawer.addDrawerListener(toggle);
        toggle.syncState();

        NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
        navigationView.setNavigationItemSelectedListener(this);

O aspeto é este:

XML do toolbar:
<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

<android.support.design.widget.AppBarLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:theme="@style/AppTheme.AppBarOverlay">

    <android.support.v7.widget.Toolbar
        android:id="@+id/toolbar"
        android:layout_width="match_parent"
        android:layout_height="?attr/actionBarSize"
        android:background="@drawable/toolbar_main">

        <TextView
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:textColor="@color/brown"
            android:textSize="26sp"
            android:textStyle="bold"
            android:text="@string/app_name2"
            android:gravity="center"
            android:id="@+id/toolbar_title"/>

    </android.support.v7.widget.Toolbar>

toolbar_main.xml:
<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
    <item>
        <shape android:shape="rectangle">
            <solid android:color="@color/white" />
        </shape>
    </item>
    <item android:bottom="2dp">
        <shape android:shape="rectangle">
            <gradient android:angle="-90" android:startColor="@color/amarelo1" android:endColor="@color/amarelo2"  />

        </shape>
    </item>
</layer-list>

Já tentei colocar toolbar.setNavigationIcon(R.drawable.ic_drawer); e também não funciona. Alguém consegue ajudar?

A: Mantenha a instância do DrawerToggle e chame o syncState() em onPostCreate
@Override
protected void onPostCreate(@Nullable Bundle savedInstanceState) {
    super.onPostCreate(savedInstanceState);

    this.drawerToggle.syncState();
}


text:
Q: Auto-hide Unity Top Bar I'd like Unity top bar to be hidden, and only appear when the mouse reaches the top of the screen. How do I do that?

A: Short answer
Unfortunately, there is no option in gsettings, nor anywhere else, nor a cli option to do what you want.
That is, without breaking into the code of course.