text:
Q: How do I split a string by specific pairing groups? I am writing my own JSON parser in Java and I am looking for a way to split a string by a comma or a colon, that are outside [], {} or "" pairs.
I found a tutorial via Google, and it works. The issue is, that it also captures the commas inside those brackets, and I need it to ommit them. I don't know how to edit the regular expression to exclude captured commass from one of these bracket pairs. I tried something like ",(?=([^\"\\{\\[]*\"[^\"\\}\\]]*\")*[^\"]*$)", but it doesn't work. It messes it up even more. The same also applies to the colon separation, which is used in separation of key and value of a JSON object.
Is there a way to combine the "", {} and [] pairs together in the regex in such way that it works? Sorry if I look like a lame, but I really can't figure out how the regex should look like.
BTW, this is a code snippet I want to use it in:
public class JavaJSON {
    private HashMap<String, Object> content;

    // Constructors

    /**
     * Create new empty JSON object
     */
    public JavaJSON() {
        this.content = new HashMap<>();
    }
    // ...

    /**
     * Parse a JSON string to a JSON object
     *
     * @param JSON JSON string to be converted to JSON object
     * @return JSON object from given string
     */
    public static JavaJSON parse(@NotNull String JSON) {
        if (!JSON.startsWith("{") || !JSON.endsWith("}")) return null;
        // If this is not a valid JSON string, return nothing.

        JavaJSON output = new JavaJSON();

        String content = JSON.substring(1, JSON.length() - 1);
        if (content.length() == 0) return output;    // if empty, return an empty JSON object

        // Regex literals
        String commaSeparated = ",(?=([^\"]*\"[^\"]*\")*[^\"]*$)";  // TODO: Change commaSeparated to capture any {} [] "" pair group
        String colonSeparated = ":(?=([^\"]*\"[^\"]*\")*[^\"]*$)";  // TODO: Change colonSeparated to capture any {} [] "" pair group

        String[] tokens = content.split(commaSeparated);

        if (tokens.length == 0) return null;
        // Don't know exactly if this is going to happen, but better be sure

        for (String token : tokens) {
            String rawToken = token.trim();

            if (rawToken.length() == 0) return null;
            // Omitted comma, extra comma, etc. = JSON error

            String[] mapToken = rawToken.split(colonSeparated);
            if (mapToken.length < 2 || mapToken.length > 2) return null;
            // Expected format = {"foo": "bar"}; format isn't valid

            String mapKey = mapToken[0].trim();
            String mapValue = mapToken[1].trim();

            if (!mapKey.startsWith("\"") || !mapKey.endsWith("\"")) return null;
            // Key must be a string

            String rawMapKey = mapKey.substring(1, mapKey.length() - 1);    // get quote-less variant
            if (rawMapKey.length() == 0) return null;
            // Key must not be empty

            // check errors
            if (mapValue.startsWith("{") && !mapValue.endsWith("}")) return null;
            // Not a valid JSON object
            if (mapValue.startsWith("[") && !mapValue.endsWith("]")) return null;
            // Not a valid JSON array
            if (mapValue.startsWith("\"") && !mapValue.endsWith("\"")) return null;
            // Not a valid string

            // get value object
            Object rawMapValue;

            // parse value object
            if (mapValue.startsWith("\"") && mapValue.endsWith("\"")) {
                rawMapValue = mapValue.substring(1, mapValue.length() - 1);
            } else if (mapValue.startsWith("{") && mapValue.endsWith("}")) {
                rawMapValue = parse(mapValue);
            } else if (mapValue.startsWith("[") && mapValue.endsWith("]")) {
                rawMapValue = parseArray(mapValue);
            } else {
                try {
                    rawMapValue = Long.parseLong(mapValue);
                } catch (Exception e) {
                    try {
                        rawMapValue = Double.parseDouble(mapValue);
                    } catch (Exception f) {
                        return null;
                        // Not a valid number
                    }
                }
            }

            output.update(rawMapKey, rawMapValue);
        }

        return output;
    }

    // ...
}


text:
Q: Constant probability for multivariate normal random variable. I couldn't figure out the following problem.
Consider a multivariate normal random variable in $\mathbb{R}^n$, with the covariance matrix being something like $\sigma^2 \cdot I_n$, where $\sigma \in \mathbb{R}^+$ is a positive value and $I_n$ is the $n$-dimensional identity matrix.
Let $\phi(x)$ be its density distribution, and let $B(r)$ be the euclidean ball centered in the origin of radius $r$.
I have to find a good approximation of the smallest $r$ such that $\int_{B(r)} \phi(x) \ \text{d}x $ is at least a constant, say $1/2$. In particular, I'm interested in the relation between $r$ and $\sigma$. We know that for dimension $n=1$, $r = \sigma$ answers the question. What about dimension $n > 1$?
Many thanks.

A: The PDF (assuming no mean) is:
$$\phi(x)=\frac{\exp\left(-\frac12x^T\Sigma^{-1}x\right)}{\sqrt{|2\pi\Sigma|}}$$
Where $\Sigma$ is your covariance matrix and $|\Sigma|$ is the determinant of the matrix $\Sigma$. In your case, $\Sigma$ is very simple so we can rewrite the PDF as:
$$\phi(x)=\frac{\exp\left(-\frac{\sigma^2}2x^Tx\right)}{\left(2\pi\sigma^2\right)^\frac n2}$$
So we see that this depends only on $x^Tx$, which is the square of the distance from the point to the origin (i.e.: it lies on the ball of radius $\sqrt{x^Tx}$). This should be enough to solve your problem.
EDIT:
You can rewrite:
$$\phi(\rho)=\frac{\exp\left(-\frac{\sigma^2\rho^2}2\right)}{\left(2\pi\sigma^2\right)^\frac n2}$$
where $\rho=\sqrt{x^Tx}$. Your integral becomes:
$$\int_{B(r)}\phi(x)dx = \int_0^r\phi(\rho)S_n(\rho)d\rho$$
where $S_n(\rho)$ is the area of the $n$-sphere of radius $\rho$. See for example:
https://en.wikipedia.org/wiki/N-sphere#Volume_and_surface_area
Depending on the value of $n$, you will get a closed form of the integral.

A: I found an answer for the problem, which I write here since it can be useful.
The squared radius of a standard normal random $n$-vector $(X_1, \dots, X_n)$ is given by the Chi-squared distribution with degree of freedom $n$, i.e. $\chi_n^2 = \sum_{i=1}^n {X_i^2}$, where $X_i \sim N(0,1)$ for $i = 1, \dots, n$.
Laurent and Massart show a concentration bound for it (page 1325, eq. 4.3): for any positive $x$,
$$
\text{Pr}\left[\chi_n^2 \ge n + 2\sqrt{n x} + 2x \right] \le e^{-x}.
$$
We can take $x=1$, which implies that $\text{Pr}\left[\chi_n^2 \ge n + 2\sqrt{n} + 2 \right] \le e^{-1}$.
In our case, we have $X = \sigma \cdot (X_1, \dots, X_n)$ where $X_i$ is a standard normal r.v. Thus, $\chi_n^2 = \frac{\lvert\lvert X \rvert\rvert_2^2}{\sigma^2}$.
Hence, if $r \ge \sigma \sqrt{5n} \ge \sigma \sqrt{n + 2\sqrt{n} + 2}$, we have
$$
\int_{B(r)} \phi(x) \ \text{d}x  \ge 1 - \frac{1}{e} \ge \frac{1}{2}.
$$

redpajama_set_name: RedPajamaStackExchange


text:
Q: Accessing realm database across activities I have 3 different activities. 1 extends Application and realm is configured in this activity. 2. Data is added to Realm from 2nd activity . 3. Data is to be displayed in the 3rd activity. I am unable to do the 3rd part. I am unable to get an instance of Realm in the 3rd activity. The following is Application(1st activity that I mentioned)
@Override
    public void onCreate() {
        super.onCreate();
        Realm.init(this);
        RealmConfiguration realmConfiguration = new RealmConfiguration.Builder().build();
        Realm.setDefaultConfiguration(realmConfiguration);
    }

the following is the code for adding data to realm which is in a fragment inside 2nd activity(PurchaseDetailsActivity).
private void addDataToRealm(DBPurchase model) {
        mRealm.beginTransaction();
        DBPurchase dbPurchaseModel = new DBPurchase();
        dbPurchaseModel.setId(id);
        dbPurchaseModel.setAmountPayed(model.getAmountPayed());
        dbPurchaseModel.setCredit(model.getCredit());
        mRealm.insertOrUpdate(dbPurchaseModel);
        mRealm.commitTransaction();
        id++;

the last one is the fragment which is inside 3rd Activity.
@Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_purchase_items, container, false);
        purchaseTotalListAdapter = new PurchaseTotalListAdapter(getContext(), mDBPurchaseArrayList, PurchasesTotalListFragment.this);
        RecyclerView recyclerView = (RecyclerView) view.findViewById(R.id.recycler_view);
        recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
        recyclerView.setAdapter(purchaseTotalListAdapter);
        Realm.getDefaultInstance();
        return view;
    }


text:
Q: How to pause a video from another widget in flutter So I have a project here that displays large amounts of images and videos, the problem is that when the user is scrolling and a video is playing at the same time, it really ruins the performance of the entire app and the FPS drops from 60 to around 30. I think the way of fixing this is just pausing the video while the user is scrolling. How could I go about getting it to do this?
I'm using this plugin for the video: https://pub.dev/packages/video_player
This is the parent component, with the video widget inside it, so as you can see, it just loops through an array and displays pictures and images. What I want to know is: how to let the video widget know whether the user is scrolling or not, and inside of the video widget there is a pause and play method, so depending on whether the user is scrolling or not, it will pause/play
(FeedVideoItem = video widget)
Parent Widget:
  @override
  Widget build(BuildContext context) {
    return SafeArea(
      child: SingleChildScrollView(
        child: Column(
          children: <Widget>[
              if (loaded)
            if (_feedDatas.length > 1)
              for (var item in _feedDatas)
                if (item.isImage)
                  FeedImageItem(
                    item: item,
                  )
                else
                // VIDEO WIDGET
                  new FeedVideoItem(videoData: item)
            else
              Center(child: Text('Loading, do hot restart to display')),
          ],
        ),
      ),
    );
  }

Video Widget (FeedVideoItem):
class FeedVideoItem extends StatefulWidget {
  final videoData;

  FeedVideoItem({this.videoData}) : super();

  @override
  _FeedVideoItemState createState() => _FeedVideoItemState(videoData);
}

class _FeedVideoItemState extends State<FeedVideoItem> {
  FeedItem item;
  _FeedVideoItemState(this.item);

  VideoPlayerController _controller;
  bool startedPlaying = false;

  Future<void> initialiseVideoPlayerFuture;

  @override
  void initState() {
    _controller = VideoPlayerController.network(item.url);
    initialiseVideoPlayerFuture = _controller.initialize();
    _controller.setLooping(true);
    _controller.setVolume(1.0);
    super.initState();
  }

  @override
  void dispose() {
    _controller.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Padding(
      padding: const EdgeInsets.only(bottom: 15.0),
      child: Column(
        children: <Widget>[
          Stack(
            children: <Widget>[
              FutureBuilder(
                future: initialiseVideoPlayerFuture,
                builder: (context, snapshot) {
                  if (snapshot.connectionState == ConnectionState.done) {
                    return InkWell(
                      onTap: () {
                        setState(() {
                          if (_controller.value.isPlaying) {
                            _controller.pause();
                          } else {
                            _controller.play();
                          }
                        });
                      },
                      child: AspectRatio(
                        aspectRatio: _controller.value.aspectRatio,
                        child: VideoPlayer(_controller),
                      ),
                    );
                  } else {
                    //TODO: Add placeholder image
                  }
                },
              ),
              InkWell(
                child: Icon(
                  _controller.value.isPlaying ? Icons.pause : Icons.play_arrow,
                  color: Colors.white,
                ),
              )
            ],
          ),
        ],
      ),
    );
  }
}


text:
Q: Category menu item and its last 10 posts as sub-menu i have some posts categories as element of a main navigation menu, and i'd like to display the ten lasts posts of this category as sub menu.
ex:  Category1
         Lastpost1
         Lastpost2
The main menu is build in the admin panel, and i'm wondering if there is a hook or something to achieve that automatically.
I know how to hardcode that, but i'd like to keep using the cool menu edition from admin panel.
any ideas?

A: I finally achieve it with this code in function.php
// Front end only, don't hack on the settings page
if ( ! is_admin() ) {
// Hook in early to modify the menu
// This is before the CSS "selected" classes are calculated
add_filter( 'wp_get_nav_menu_items', 'display_lasts_ten_posts_for_categories_menu_item', 10, 3 );
}

// Add the ten last posts of af categroy menu item in a sub menu
function display_lasts_ten_posts_for_categories_menu_item( $items, $menu, $args ) {

$menu_order = count($items); /* Offset menu order */
$child_items = array();

// Loop through the menu items looking category menu object
foreach ( $items as $item ) {

    // Test if menu item is a categroy and has no sub-category
    if ( 'category' != $item->object || ('category' == $item->object && get_category_children($item->object_id)) )
        continue;

    // Query the lasts ten category posts
    $category_ten_last_posts = array(
            'numberposts' => 10,
            'cat' => $item->object_id,
            'orderby' => 'date',
            'order' => 'DESC'
    );

    foreach ( get_posts( $category_ten_last_posts ) as $post ) {
        // Add sub menu item
        $post->menu_item_parent = $item->ID;
        $post->post_type = 'nav_menu_item';
        $post->object = 'custom';
        $post->type = 'custom';
        $post->menu_order = ++$menu_order;
        $post->title = $post->post_title;
        $post->url = get_permalink( $post->ID );
        /* add children */
        $child_items[]= $post;
    }
}
return array_merge( $items, $child_items );
}

This will display as sub menu, the ten last posts of a category placed as menu item or sub menu item in admin panel.
This code is highly inspired from this: http://codeseekah.com/2012/03/05/list-all-posts-in-wordpress-navigation-menu/


text:
Q: Geometric progression formula. how to get to n = something? I know that the formula for Geometric progression is
$$ a_n = a_1\cdot q^{n-1} $$
I want to get an expression like that: " $n =$ something ". I have no idea how to do it, because the n is in the exponentiation.

A: Hint:
$$
\log |a_n|=\log |a_1| +(n-1)\log |q|.
$$


text:
Q: Save Excel Workbook in VSTO Addin C# I've coded an Excel Addin which, when a button is pressed, changes the content of some cells.
Now I wanted to add the functionality to save the workbook to a new file after these replacements took place.
Here is my go at it and somehow this doesn't quite work like I imagined.
This is the code to save the file in my ThisAddIn.cs:
public static void saveasnewfile()
        {
            Globals.ThisAddIn.Application.ActiveWorkbook.SaveCopyAs(@"C:\XXXX.XLS");
        }

And this is how I call this function (say when a button is pressed):
//...
ThisAddIn.saveasnewfile();
//...

Now when I press said button I get this error message:

Microsoft Excel cannot access the file 'C:\XXXX.XLS'. There are
  several possible reasons:
• The file name or path does not exist.
   • The file is being used by another program.
   • The workbook you are trying to save has the samename as a currently open workbook.

Which seems kind of strange to me. Of course the file does not exist, since I want to create it...
So what am I missing here?
I would like to add the functionality to prompt the user for a path with a savefiledialog later. So some tips there would help as well :)

A: SOLUTION:
For anyone that might stumble on the same thing, here is how I implemented it with the SaveFileDialog:
var saveDialog = new SaveFileDialog() //create new instance of savefiledialog
{
    Title = "Save As", //sets title of dialog box
    Filter = "Excel Worbook (*.xlsx)|*.xlsx", //filter for .xlsx files
    AddExtension = true, //automatically adds the .xlsx extension
    CheckPathExists = true //checks if the given path really exists
}

if (saveDialog.ShowDialog() == DialogResult.OK)
{
Globals.ThisAddIn.Application.ActiveWorkbook.SaveCopyAs(saveDialog.FileName);
}


text:
Q: C# FormattableString concatenation for multiline interpolation In C#7, I'm trying to use a multiline interpolated string for use with FormttableString.Invariant but string concatenation appears to be invalid for FormttableString.
Per the documentation: A FormattableString instance may result from an interpolated string in C# or Visual Basic.
The following FormttableString multiline concatenation does not compile:
using static System.FormattableString;
string build = Invariant($"{this.x}"
                       + $"{this.y}"
                       + $"$this.z}");

Error CS1503 - Argument 1: cannot convert from 'string' to
  'System.FormattableString'

Using an interpolated string without concatenation does compile:
using static System.FormattableString;
string build = Invariant($"{this.x}");

How do you implement multiline string concatenation with the FormattableString type?
(Please note that FormattableString was added in .Net Framework 4.6.)

A: The Invariant method is expecting the parameter of FormattableString type.
In your case, the parameter  $"{this.x}" + $"{this.y}" becomes "string" + "string' which will evaluate to string type output. That's the reason you are getting the compile error as Invariant is expecting the FormattableString and not string.
You should try this for single line text -
public string X { get; set; } = "This is X";
public string Y { get; set; } = "This is Y";
public string Z { get; set; } = "This is Z";
string build = Invariant($"{this.x} {this.y} {this.z}");

Output -

This is X This is Y This is Z

And to implement multiline interpolation, you can build the FormattableString  like below and then use the Invarient.
FormattableString fs = $@"{this.X}
{this.Y}
{this.Z}";
string build = Invariant(fs);

Output -

This is X
This is Y
This is Z


text:
Q: Spring security remember me failing on IE10 Spring security was working fine in all terms except for remember-me feature(simple remember me approach not using persistent approach).
If I log in as a user with the remember me checked and if I close the browser (Chrome) and reopen and hits the same , The app was redirected to the login screen which shouldn't have been the case.
My config xml for spring security had just <security:remember-me>
initially.
Then later I added <security:remember-me use-secure-cookie="false"/>
and it worked like a charm in CHROME. So now if the user logs in with the remember me checked and closes the browser and reopens the browser , then the app is redirected with the logged on user to the home page.
But now the same piece of code seems not to work in IE10. And I need it to get done from versions of 9 (IE9 and above).
Tried a lot scenarios. But cant get to the root cause. Any help would be appreciated.


text:
Q: WampServer: php-win.exe The program can't start because MSVCR110.dll is missing if I try to install WampServer the above error appears. I already tried to install all the programs which were recommended, for example here:
WAMP shows error 'MSVCR100.dll' is missing when install
But nothing helps. What can I do to install WampServer?

A: What solves my problem:
I am using 64 bit Windows 7, so I thought I could install 64 bit Wamp. After I Installed the 32-bit version the error does not appear. So something in the developing process at Wamp went wrong...

A: During the download of wamp server from wampserver website you get a warning..

WARNING : Vous devez avoir installé Visual Studio 2012 : VC 11
  vcredist_x64/86.exe Visual Studio 2012 VC 11 vcredist_x64/86.exe :
  http://www.microsoft.com/en-us/download/details.aspx?id=30679

So if you install the vcredist_xxx.exe it will be ok

A: As far as I am aware, the MSVCRxxx.dlls are in %SystemRoot%\System32 (usually C:\Windows\System32).
The xxx refers to the version of the MS Visual C Runtime (hence MSVCR...)
However, the complication seems to be that the xxx version is not the same as the two digits of the year "version".
For example,  Visual C Runtime 2013 yields MSVCR120.dll and "...Runtime 2012" yields MSVCR110.dll.  And then Microsoft packages these as vcredist_x86.exe or vcredist_x64.exe, seemingly irrespective of the xxx version or the Visual Studio version number (2012, 2013 etc) - confused? You have every right to be!
So, firstly, you need to determine whether you need 32 bit, 64 bit or even both (some PHP distributions apparently do need both), then download the relevant vcredist... for the bits AND for the Visual Studio version.  As far as I can tell, the only way to tell which vcredist... you have is to start to install it.  Recent versions give an intro screen that quotes the Visual Studio version and the xxx version.  I have renamed by vcredists to something like vcredist_x64_2012_V11.exe.
[EDIT] Forgot to add earlier that if you are simply looking to "install" the missing DLL (as opposed to resolve some bigger set of issues), then you probably won't do any harm by simply installing the relevant vcredist for your architecture (32 bit, 64 bit) and "missing" version.

A: Windows 10 x64 released August 2015 - same issue arising. MSVCR110.dll is also found in the sysWOW64 folder (which is where I found it, copying to system32 does not help). To resolve:

*

*uninstall the x86 versions of  VC 11 vcredist_x64/86.exe for 2012 and 2013

*uninstall WAMP Server 2.5

*delete (maybe back up first) the WAMP folder

*restart windows

*reinstall WAMP 2.5

Hopefully like me you have a MySQL database backup handy!


text:
Q: LayoutParams type changed at runtime. ClassCastException: ViewGroup$LayoutParams cannot be cast to ViewGroup$MarginLayoutParams I try to set layout params programmatically. In my fragment in onCreate method, I set LayoutParams of the ScrollView and it works. But also, I have an observer and in this observer when some condition is true I change layout params of this ScrollView again. But the problem is that the same code which is in onCreate doesn't work in an observer. Below is a fragment of onCreate method when I set layout params and set an observer. The method which changes layout params is copy-pasted so it is a little strange why it is working and a milliseconds after doesn't.
onCreate:
Log.d("Setting height in onCreate method")
binding.scrollRoot.layoutParams = ViewGroup.LayoutParams(
    ViewGroup.LayoutParams.MATCH_PARENT,
    binding.txtCars.lineHeight * SIZE + 10
)

cars.observe(viewLifecycleOwner, Observer {
    if (it.size < SIZE)
    {
        Log.d("Setting height in observer method")
        binding.scrollRoot.layoutParams = ViewGroup.LayoutParams(
            ViewGroup.LayoutParams.MATCH_PARENT,
            binding.txtCars.lineHeight * (it.size) + 10
        )
    }
    binding.txtCars.text = formatCars(it, requireContext())
})

Logcat:
D/AppDebug: Setting height in onCreate method
D/AppDebug: Setting height in observer method
I/zygote64: Method exceeds compiler instruction limit: 25337 in void org.ccil.cowan.tagsoup.HTMLSchema.<init>()
D/AndroidRuntime: Shutting down ViewModel
E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.example.fuelmanager, PID: 8034
    java.lang.ClassCastException: android.view.ViewGroup$LayoutParams cannot be cast to android.view.ViewGroup$MarginLayoutParams
        at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:6662)
        at android.widget.FrameLayout.onMeasure(FrameLayout.java:185)
        at android.view.View.measure(View.java:22216)
        at androidx.constraintlayout.widget.ConstraintLayout.internalMeasureChildren(ConstraintLayout.java:1227)
        at androidx.constraintlayout.widget.ConstraintLayout.onMeasure(ConstraintLayout.java:1572)
        at android.view.View.measure(View.java:22216)
        at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:6671)
        at android.widget.FrameLayout.onMeasure(FrameLayout.java:185)
        at android.view.View.measure(View.java:22216)
        at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:6671)
        at android.widget.FrameLayout.onMeasure(FrameLayout.java:185)
        at android.view.View.measure(View.java:22216)
        at androidx.drawerlayout.widget.DrawerLayout.onMeasure(DrawerLayout.java:1156)
        at android.view.View.measure(View.java:22216)
        at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:6671)
        at android.widget.FrameLayout.onMeasure(FrameLayout.java:185)
        at androidx.appcompat.widget.ContentFrameLayout.onMeasure(ContentFrameLayout.java:143)
        at android.view.View.measure(View.java:22216)
        at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:6671)
        at androidx.appcompat.widget.ActionBarOverlayLayout.onMeasure(ActionBarOverlayLayout.java:403)
        at android.view.View.measure(View.java:22216)
        at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:6671)
        at android.widget.FrameLayout.onMeasure(FrameLayout.java:185)
        at android.view.View.measure(View.java:22216)
        at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:6671)
        at android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java:1539)
        at android.widget.LinearLayout.measureVertical(LinearLayout.java:823)
        at android.widget.LinearLayout.onMeasure(LinearLayout.java:702)
        at android.view.View.measure(View.java:22216)
        at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:6671)
        at android.widget.FrameLayout.onMeasure(FrameLayout.java:185)
        at com.android.internal.policy.DecorView.onMeasure(DecorView.java:831)
        at android.view.View.measure(View.java:22216)
        at android.view.ViewRootImpl.performMeasure(ViewRootImpl.java:2596)
        at android.view.ViewRootImpl.measureHierarchy(ViewRootImpl.java:1638)
        at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:1892)
        at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1522)
        at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:7292)
        at android.view.Choreographer$CallbackRecord.run(Choreographer.java:981)
        at android.view.Choreographer.doCallbacks(Choreographer.java:790)
        at android.view.Choreographer.doFrame(Choreographer.java:721)
        at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:967)
        at android.os.Handler.handleCallback(Handler.java:808)
        at android.os.Handler.dispatchMessage(Handler.java:101)
        at android.os.Looper.loop(Looper.java:166)
        at android.app.ActivityThread.main(ActivityThread.java:7529)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:245)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:921)

After research, I found this question

Here you're replacing existing layout params of correct type AbsListView.LayoutParams with more generic ViewGroup.LayoutParams. Layout params type is that of the parent container of the view.
If you need to modify existing layout params, access them with getLayoutParams(), modify it, and call requestLayout() to notify that the layout has changed.

So I made it in that way:
Log.d("Setting height in observer method")
val layoutParams = binding.scrollRoot.layoutParams
layoutParams.height = binding.txtCars.lineHeight * (it.size) + 10

And it works.
But my question is how is it possible that type of ViewGroup/ScrollView LayoutParams changed. What happened after onCrete() that makes this error in the observer?


text:
Q: Python3: Function to return the number of ways to make change n using 2p and 1p coins and the list of solution tuples I'm trying to write a function TwoPandP which takes an integer n and returns both the number of ways to make change and the list of solution tuples. If the number of ways to make change is not zero, then the second value is a list of solution tuples, where the 2's occur at the start of the tuples. The order of the solutions within the list does not matter.
For example, TwoPandP(11) should return ChangeTwoPandP(5) should return (3, [(2,2,1), (2,1,1,1), (1,1,1,1,1)]) (or with the tuples in a different order) and ChangeFivePandP(-1) should return (0, []).
I've tried:
def TwosandOnes(n):
k = n // 2
list = [[1 for i in range(n)]]
for i in range(k):
list.append([2 for i in range(i+1)])
for j in range(n - sum(list[i+1]) + 1):
if sum(list[i]) != (n):
list[i].append(1)
tuple(list[i])
return((k + 1), list)

but the function never append's the 1's to the last solution tuple. How do I alter the function to append all the 1's it's supposed to?


text:
Q: Is there a way if a video file has pixelation in FFmpeg? I am trying to identify if a video file has pixelation or not,
Currently, I have a watch folder where videos are dropped, I have a trigger every 120 seconds that check the folder to see if there are any video files.
If there is a file, it uses MediaInfo command-line to extract the encoding of the video and audio.
I also use ffprobe on a video to see if it throws out an error like moov atom not found to know if the video is corrupted.
However, I want to be able to tell if a video file has a pixelation. I know that I can use str, std, to print out the debug logs.
However, I am finding it difficult to find documentation on how to detect pixelation.
Do you guys know if there a way to tell that a video file may have pixelation, even through a log output of the video?
I am already running a script that reads a log and finds information on the log to tell me about packet drops in a stream, so if you know how I output such log that tells if there is pixelation, or if the debug log has certain information that tells this, please let me know.

A: Any lost packet will inadvertently lead to decoding errors (both in video/audio streams), so in principle you already have your solution if you inspect the debug log while decoding. Is there a mismatch or decoding error? Then your file has probably been corrupted.
The "problem" is that decoding is somewhat robust against losses, and errors from lost frames or parts of frames can be concealed by the decoder. This depends on the decoder; some to better than others here.
How to tell if a file has problems?
So, a file may only have few lost packets, and you'd consider it as faulty when looking at the bitstream only (i.e. the ffmpeg log), but it will decode just fine, and a human viewer will not be likely to notice the error. At some point, of course, a human will definitely notice these problems.
That means you're going to either need some threshold as to how many packet errors are acceptable, or a more detailed analysis on the pixel level. That means: decode the video and analyze the pixels whether you can detect errors stemming from packet/slice losses (what you are calling "pixelation"). Of course, it'd be easier if you had access to the original video to compare with, but I assume that is not the case.
You have to decide what that threshold is. Take a sample of videos and label them: are they "pixelated" or not? This is nothing that an algorithm can simply decide for you. Then match your count of packet errors against your binary decision of whether to accept or reject the video. You should hopefully see some correlation there, although, of course, it will vary a lot depending on which frame is lost or how much loss there was.
Are there any algorithms for that?
There are of course algorithms that can help estimating the quality of a decoded video if you don't have a reference. These are called "no-reference" pixel-based quality models.
Some algorithms you may want to look into:

*

*AGH University has some indicators for detecting issues in video streams, like blurring and blockiness.

*VQEG has a list of no reference metric resources with some pointers

*The LIVE lab at the University of Texas have developed some no-reference image and video quality algorithms

All of those metrics are not quite good in terms of predicting human perception. It's very likely that you'll get some false positives.
An even better way to predict the quality of such videos would be to use "hybrid no-reference" algorithms which take both the bitstream and the video pixels into account. There are some standardized algorithms out there (e.g. ITU-T J.343.1), for which Rohde & Schwarz offers a commercial implementation (see page 20-23 for the issues that you are probably facing).


text:
Q: Priority of logical operations I need to create a truth table for the expression
$$\overline{YZ\implies X}$$ Negation must be made at the beginning, before the rest of the actions, or at the very end? In the case of the negation of individual variables, then I understand that first it is done, and then the rest of the action?

A: Given that the overline covers the whole expression $YZ \Rightarrow X$, the negation is applied to that whole latter expression. That is,  you need to first figure out the value of $YZ \Rightarrow X$, and then negate that. So it is the last operation you do for this expression.


text:
Q: How to move image on screen? I want to move an image on the screen and I am able to do that, but not properly. The image goes downward fine and I want it to start going upward in another direction once it has moved to the bottom of the screen.
Here is what I have tried. In the code below, margenMaXX is the width of screen and margenmaxy is height of screen
protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // setContentView(R.layout.activity_main);
Thread myThread = new Thread(new UpdateThread());
        myThread.start();

public class UpdateThread implements Runnable {

            @Override
            public void run() {
                //... code to manipulate position
                while (i<margenMaxX){
                    if(j<margenmaxy) {
                    try {
                        runOnUiThread(new Runnable() {

                            @Override
                            public void run() {
                                /*mDrawable.setBounds(i, j ,i+ width, i+ height);
                                 mDrawable.draw(cc);
                                 invalidate();*/
                            }
                        });
                       Thread.sleep(200);
                        i=i+10;
                        j=j+10;
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }else if(j>=margenmaxy-height){
                    try {
                        runOnUiThread(new Runnable() {

                            @Override
                            public void run() {
                                /*mDrawable.setBounds(i, j ,i+ width, i+ height);
                                 mDrawable.draw(cc);
                                 invalidate();*/
                            }
                        });
                       Thread.sleep(200);
                        i=i-10;
                        j=j-10;
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                }
                }
            }

public class AnimatedView extends ImageView {

        public AnimatedView(Context context) {
            super(context);
            // TODO Auto-generated constructor stub

            mDrawable =  new ShapeDrawable(new OvalShape());
            mDrawable.getPaint().setColor(0xffffAC23);

        }
         protected void onDraw(final Canvas cc) {
            final Context context = null;

            mDrawable.setBounds(i, j ,i+ width, i+ height);
            mDrawable.draw(cc);
            invalidate();
                    }
    }

Update 1:
Using this code, the ball is going upwards and to another side after it hits the ground. Now, I want the ball to come back when it hits the right boundary. I did coding for that but it is not coming back. My final goal is to develop a game in which the ball must come from either left or right. It must hit the ground and go in the opposite direction, hit the wall and come back. The ball must do this work as long as the game is going on.
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    // setContentView(R.layout.activity_main);
    Thread myThread = new Thread(new UpdateThread());
        myThread.start();

    public class UpdateThread implements Runnable {
    boolean mMoveDown=false;
    boolean mMoveUp = false;
        @Override
        public void run() {
            while(!mMoveUp) {
                // Move the image down and right.
                try {
                    runOnUiThread(new Runnable() {

                        @Override
                        public void run() {

                        }
                    });
                   Thread.sleep(200);
                    i=i+10;
                    j=j+10;

                // Try posting a runnable to the UI thread to update the view.

                } catch (InterruptedException e) {
                    e.printStackTrace();
                }if(j >= margenmaxy)
                {
                    // Change to moving up phase.
                    mMoveUp = true;
              }

            }

            while(mMoveUp){
                try {

                runOnUiThread(new Runnable() {

                    @Override
                    public void run() {

                    }
                });
                Thread.sleep(200);
                i=i + 10;
                j=j - 10;
            } catch (InterruptedException e) {
                e.printStackTrace();
            } if(i >= margenMaxX)
                {
                    // Change to moving up phase.
                    mMoveDown = true;
              }
        }while(mMoveDown){
            try {

                runOnUiThread(new Runnable() {

                    @Override
                    public void run() {

                    }
                });
                Thread.sleep(200);
                i=i - 10;
                j=j + 10;
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }

        }
}

public class AnimatedView extends ImageView {

        public AnimatedView(Context context) {
            super(context);
            // TODO Auto-generated constructor stub

            mDrawable =  new ShapeDrawable(new OvalShape());
            mDrawable.getPaint().setColor(0xffffAC23);

        }
         protected void onDraw(final Canvas cc) {
            final Context context = null;

            mDrawable.setBounds(i, j ,i+ width, j+ height);
            mDrawable.draw(cc);
            invalidate();
        }
}

A: This code has two conditional statements that overlap. However, the second one is checked only if the first fails. The second condition is:
(j >= margenmaxy - height)

This automatically implies
    (j < margenmaxy)
Because margenmaxy, and height are both positive. When you check the condition like this:
if(j<margenmaxy) {
    // Do downward animation.

} else if(j>=margenmaxy-height){
    // Do upward animation.
}

What happens is that what you expect will happen for the phase where the image moves down. But as soon as you try move the image up, the (j < margenmaxy) condition is satisfied again, and the code tries to move the image down. The moment you move it down, the first condition is no longer valid. Since you have this construct inside a loop, it results in a "bouncing" behaviour.
To sort this problem out, you need to change the logic. One simple way to do this is to have a boolean hold the state of the animation. This state variable is changed depending on whether the image has hit the screen's bottom or not.
public class UpdateThread implements Runnable {

    // Variable to store the animation state.
    boolean mMoveUp = false;
    @Override
    public void run() {

        //... code to manipulate position
        while (i<margenMaxX) {
            // IF the animation is in the moving down phase
            if(!mMoveUp) {
                // Move the image down and right.
                i += 10;
                j += 10;

                // Try posting a runnable to the UI thread to update the view.
                try {
                    runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                            /*mDrawable.setBounds(i, j ,i+ width, i+ height);
                             mDrawable.draw(cc);
                             invalidate();*/
                    }
                    });
                    Thread.sleep(200);

                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            // We're moving upwards.
            else {
                // Move up and left
                i -= 10;
                j -= 10;

                try {
                    runOnUiThread(new Runnable() {

                        @Override
                        public void run() {
                            /*mDrawable.setBounds(i, j ,i+ width, i+ height);
                             mDrawable.draw(cc);
                             invalidate();*/
                        }
                    });
                    Thread.sleep(200);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                } // Catch!
            } // Else!

            // Check to see if we've hit the bottom of the screen
            if(j >= margenmaxy - height)
            {
                  // Change to moving up phase.
                  mMoveUp = true;
            }
            // Note, you can use an altered form of this to switch back and forth
            // between moving up and down.
        } // while(i < margenmaxx)!
    } // run()!
} // UpdateThread!

As an added note, since you are moving the ball left and right, you might end up hitting those boundaries as well. You really should implement better checking for that. As a second note, this is probably not the best way to accomplish a moving image in Android. And finally, a more general solution is to use Android Property Animation with the interpolator you want. If you just want to do this once, View Animation may also suffice.


text:
Q: How can I pass Interface to the child component in Typescript React application interface User {
  name: string,
  address: string,
  active: boolean
}

The problem is -
I can't import interface in child component.
Child component interface have to be the type parent component provided.
So how can I access component props to define interface.

A: The interface that need to be imported need to be explicitly exported from the file where it is declared.
Here is the working example for exporting an interface and importing it in a component:
Interface file  - IUser.ts
// File name: IUser.ts

export interface IUser {
  name: string,
  address: string,
  active: boolean
}

Component File  - Functional comopnent / React Hook
// File name: MyComponent.tsx

import React, {FunctionComponent} from 'react'
import {IUser} from "../interfaces/IUser"

const MyComponent : FunctionComponent<IUser> = (props) => (

Name: {props.name}

Address: {props.address}

Active: {props.active}

)

export default MyComponent

Component File  using Class
// File name: MyComponent.tsx

import React, {Component} from 'react'
import {IUser} from "../interfaces/IUser"

export default class MyComponent extends Component<IUser> {
    render() {
        return (

Name: {this.props.name}

Address: {this.props.address}

Active: {this.props.active}

        )
    }
}

A: first you should export your interface like so:
export interface User {
name: string,
address: string,
active: boolean
}

then you can import it wherever you want:
import { User } from 'relative/path/to/interface'


text:
Q: How to run couchbase n1ql-command from powershell I'm trying to extract all the documents from a bucket and pipe them out to a file. I'm running this commmand:
PS C:\Program Files\Couchbase\Server\bin> ./cbq --engine couchbase://localhost --user Administrator --password 'password' --script="SELECT * FROM `bucket.name`"

But Powershell expects something more and gives me newlines with >> at the start of each line after executing the command.
If I drop the --script=... I log into the cqb-shell, and running the command/script works fine, but  piping to file becomes difficult.
Do anyone have an idea of what's missing here? And how I can run the command from the terminal?
PS C:\Program Files\Couchbase\Server\bin> ./cbq -v
 SHELL VERSION  : 2.0 on  Couchbase Community Edition 6.0.0 build 1693

A: You can use --file , --output options
https://docs.couchbase.com/server/current/tools/cbq-shell.html
https://dzone.com/articles/mastering-the-couchbase-n1ql-shell-scripting

A: The answer came in the comments:
Put double back ticks around the bucket name, since the single back tick escaped the double quote
PS C:\Program Files\Couchbase\Server\bin> ./cbq --engine couchbase://localhost --user Administrator --password 'password' --script="SELECT * FROM ``bucket.name``"


text:
Q: Is there a type of object, to which I can cast both Buttons AND MenuItem objects in order to access their Tag properties? I want to cast both MenuItem objects and Button control objects to an object type of whose "Tag" property I can reference.
Is there such an object type?
E.g.
void itemClick(object sender, EventArgs e)
{
    Control c = (Control)sender;
    MethodInvoker method = new MethodInvoker(c.Tag.ToString(), "Execute");
    method.Invoke();
}

Except this fails - "Unable to cast object type 'System.Windows.Forms.MenuItem' to type 'System.Windows.Forms.Control'
What can replace Control in this example?

A: I am writing this without IDE.

object myControlOrMenu = sender as MenuItem ?? sender as Button;
if (myControlOrMenu == null)
// neither of button or menuitem

A: Use "as" operator.

object tag;
Button button;
MenuItem menuItem = sender as MenuItem;
if (menuItem  != null)
{
    tag = menuItem.Tag;
}
else if( (button = sender as Button) != null )
{
    tag = button.Tag;
}
else
{
    //not button nor MenuItem
}

A: the inheritance path is different for MenuItem and Button, there is no shared / inherited Tag property.
MenuItem inherits from Menu Which declares a Tag property, Button Inherits from Control which also implements a Tag propery. You should be able to cast both MenuItem and Button to Component, but this won't help you as the Tag property is declared in the derived classes I mentioned (menu and control).
In this specific case you would probably need to use reflection rather than inheritance. Or come up with plan B

A: Control is what you're looking for.


text:
Q: iTextSharp with special characters I have an aspx form in which user takes a survey and the survey is saved to the database. After saving to the database, the survey responses given by the user are displayed so the user can save the response as pdf.
This is the function to save as pdf
//Save as PDF
protected void SaveAsPDF_Click(object sender, EventArgs e)
{
    Random nRandom = new Random(DateTime.Now.Second);
    string strFileName = nRandom.Next().ToString() + ".pdf";
    string target = Server.MapPath(System.Configuration.ConfigurationManager.AppSettings["NewResponsePDF"].ToString() + strFileName);

    string filepath = target;
    string filename = Path.GetFileName(filepath);

    Response.Clear();
    Response.ContentType = "application/pdf";
    Response.AddHeader("content-disposition", "attachment;filename=" + filename);

    Response.Cache.SetCacheability(HttpCacheability.NoCache);
    StringWriter sw = new StringWriter();
    HtmlTextWriter hw = new HtmlTextWriter(sw);
    this.Page.Form.RenderControl(hw);
    StringReader sr = new StringReader(sw.ToString());
    Document pdfDoc = new Document(PageSize.A4, 10f, 10f, 100f, 0f);
    HTMLWorker htmlparser = new HTMLWorker(pdfDoc);
    PdfWriter.GetInstance(pdfDoc, Response.OutputStream);
    pdfDoc.Open();
    htmlparser.Parse(sr);
    pdfDoc.Close();
    Response.Write(pdfDoc);
    Response.End();
}

It works fine and everything is well. The form has some text boxes. The user can enter text into the textbox. Sometimes, the user enters mathematical symbols like <, >, =. To make sure that the textbox value is saved to the database, the following ValidateRequest="false" has been done in the aspx file. But, the SaveAsPDF throws up an error as it is unable to parse these symbols.
I am pretty sure it is mostly these special symbols causing the issue with the
htmlparser.Parse(sr) method
because if there are no special symbols in the text boxes, PDF is generated fine.
Could you help me out on what I can do?/ Any pointers.
Thank you.

A: You should first encode the input text by using HttpUtility.HtmlEncode before processing the text and performing the save.
http://msdn.microsoft.com/en-us/library/73z22y6h.aspx


text:
Q: MySQL Join is the same as Cross Join? I'm learning mysql.  Under all cases, is Join the same as Cross Join?  For example, this query
SELECT * FROM table t1
JOIN table t2

Will always be the same as
SELECT * FROM table t1
CROSS JOIN table t2

Even if I add WHERE, GROUP BY, HAVING, LIMIT, ORDER etc.... conditions afterwards, JOIN and CROSS JOIN will always yield the same results?
Thanks

A: INNER, OUTER, and CROSS are ignored by MySQL.  The ON and WHERE control which type of JOIN it is.
In your examples you have nothing tying the tables together, hence operates like a CROSS JOIN.
GROUP BY, etc have no impact.


text:
Q: x86-64 MSVC++/Intel C++ change size of int, long, etc I wish to have the following sizes when I compile (using Visual C++ 2015 and/or Intel C++ 16.0)

*

*char 32 bits unsigned (for UTF-32 characters)

*short 32 bits

*int 64 bits

*long 128 bits

*Pointers and size_t 64 bits (which they are currently)

Is this possible to change? My current solution uses the macros:
#define int int64_t
#define char char32_t // Is this unsigned?
#define short int32_t
#define long __int128

But it has problems, like "int main" doesn't work... And I can't defined "signed int" "unsigned int" etc. as macro names can't have spaces
EDIT: The reason I want to do this is to improve legibility (so I don't have to write int64_t...) and also to make any code I use, that uses int/char/short/long to automatically upgrade (when recompiling) to using 64/32/32/128 bits, without having to modify it directly.

A: You cannot do this. The only proper way to achieve this is by introducing your own types and using them instead.
Also, when using types like int you must not depend on the underlying size apart from what the standard says (i.e. in case of int the only guarantee is that it's at least 16 bits). What you want to achieve is a dependency you shouldn't have, and that would make you code completely unportable. Besides, I don't see why int64_t would be less legible than using int. Also, the redefining you want would come unexpected to other developers and thus is likely to cause bugs. Using your own types makes it explicit that the types are different.

A: It's not necessary to use macro when you define unsigned int, you can write code like the following:
typedef unsigned int UINT;
now you can also write code like this:
#define UINT balabala


text:
Q: Unable to load image when selected from the gallery on Android in phonegap I want to select image form android gallery and upload image to server. My code works properly for IOS apps. But not getting image from android phone.
Inside android app getting show image url like this

content://com.android.providers.media.documents/document/image%3A352

What should I do to get the right image extension from Android gallery?
I am using Hybird App with Phonegap.
document.addEventListener("deviceready", onDeviceReady, false);

        // device APIs are available
        //
        function onDeviceReady() {
            // Retrieve image file location from specified source
            navigator.camera.getPicture(
                uploadPhoto,
                function(message) { alert('get picture failed'); },
                {
                    quality         : 100,
                    destinationType : navigator.camera.DestinationType.FILE_URI,
                    sourceType      : navigator.camera.PictureSourceType.PHOTOLIBRARY
                }
            );
        }

        function uploadPhoto(imageURI) {
            //alert(imageURI); return false;

            //alert(imageURI);

            var options = new FileUploadOptions();
            options.fileKey="file";

            //options.fileName=imageURI.substr(imageURI.lastIndexOf('/')+1)+'.png';
            options.mimeType="image/jpeg";

            var params = {};
            params.value1 = "test";
            params.value2 = "param";

            options.fileName=imageURI.substr(imageURI.lastIndexOf('/')+1);
            options.params = params;
            options.chunkedMode = true; //this is important to send both data and files

            alert(options.fileName);
            var ft = new FileTransfer();
            ft.upload(imageURI, encodeURI("file_upload.php"), win, fail, options);
        }

        function win(r) {
                alert("Code = " + r.responseCode); //http response 200, means OK
                alert("Response = " + r.response); //php uploader response (failed)
                alert("Sent = " + r.bytesSent); //filesize
       }

        function fail(error) {
            alert("An error has occurred: Code = " + error.code);
            console.log("upload error source " + error.source);
            console.log("upload error target " + error.target);
        }

A: This is a cordova bug - https://issues.apache.org/jira/browse/CB-5398.
You can change your path like this.
function uploadPhoto(imageURI) {
            //alert(imageURI); return false;

            //alert(imageURI);
            if (imageURI.substring(0,21)=="content://com.android") {
                photo_split=imageURI.split("%3A");
                imageURI="content://media/external/images/media/"+photo_split[1];
              }

            var options = new FileUploadOptions();
            options.fileKey="file";
            //options.fileName=imageURI.substr(imageURI.lastIndexOf('/')+1)+'.png';
            options.mimeType="image/jpeg";

            var params = {};
            params.value1 = "test";
            params.value2 = "param";
            options.fileName=imageURI.substr(imageURI.lastIndexOf('/')+1);
            options.params = params;
            options.chunkedMode = true; //this is important to send both data and files

            //alert(options.fileName);
            var ft = new FileTransfer();
            ft.upload(imageURI, encodeURI("file_upload.php"), win, fail, options);
        }

And send image request to file_upload.php. Add some condition like this.
       $file=$_FILES['file']['name'];
        $new_file=explode('.', $file);
        $img_file=end($new_file);

        if($img_file=='png' || $img_file=='jpeg' || $img_file=='jpg')
        {
            $file_name=$new_file[0];
        }  else {
             $file_name=$_FILES['file']['name'];
             $_FILES['file']['name']=$_FILES['file']['name'].'.jpg';
        }

        move_uploaded_file($_FILES["file"]["tmp_name"], 'your_location'.$file_name);

A: You can specify encodingType: Camera.EncodingType.JPEG and render image in your success callback like this- $('#yourElement).attr('src', "data:image/jpeg;base64," + ImageData);
navigator.camera.getPicture(onSuccess, onFail, {
    quality: 100,
    destinationType: Camera.DestinationType.DATA_URL,
    sourceType: Camera.PictureSourceType.SAVEDPHOTOALBUM,
    allowEdit: true,
    encodingType: Camera.EncodingType.JPEG,
    targetWidth: 500,
    targetHeight: 500,
    popoverOptions: CameraPopoverOptions,
    saveToPhotoAlbum: false,
    correctOrientation: true
});

function onSuccess(imageData) {
    console.log("Image URI success");
    ImageData = imageData;
    $('#yourElement).attr('src', "data:image/jpeg;base64," + ImageData);
    }


text:
Q: MySQL uses incorrect index. Why? There is a typical Users table, which contains fields: id (primary), application_id, login, phone, etc. (application_id - selective field)
There are few indexes:
index_users_on_application_id,
unique_index_users_on_application_id_and_login
unique_index_users_on_application_id_and_phone

The query itself is very simple:
SELECT  `users`.*
FROM `users`
WHERE `users`.`application_id` = 1234
LIMIT 10 OFFSET 0;

The tricky part is that this query uses one of two unique indexes (unique_index_users_on_application_id_and_login for example), and then returns list of users sorted by login. But I need them sorted by id.
For that purpose, I've updated the query:
SELECT  `users`.*
FROM `users`
WHERE `users`.`application_id` = 1234
ORDER BY id
LIMIT 10 OFFSET 0;

Well, now explain shows that MySQL starts using PRIMARY key instead of any indexes. But how did that happen? If index_users_on_application_id should in fact contain two fields: [application_id, id] (InnoDB), so that index is perfect for the query, but MySQL decides to chose another one.
If I say IGNORE INDEX(PRIMARY), MySQL starts using unique_index_users_on_application_id_and_login, still ignoring the correct index. Same result when ORDER BY id+0.
I also tried to ORDER BY application_id, id to make sure index fits the best, MySQL still selects wrong index.
Any ideas, why is it happening and how to ensure MySQL to use proper index without explicitly say USE INDEX(index_users_on_application_id)?
Full list of indexes for Users table:
mysql> show indexes from users;
+-------+------------+-----------------------------------------------------+--------------+----------------------+-----------+-------------+----------+--------+------+------------+---------+---------------+
| Table | Non_unique | Key_name                                            | Seq_in_index | Column_name          | Collation | Cardinality | Sub_part | Packed | Null | Index_type | Comment | Index_comment |
+-------+------------+-----------------------------------------------------+--------------+----------------------+-----------+-------------+----------+--------+------+------------+---------+---------------+
| users |          0 | PRIMARY                                             |            1 | id                   | A         |       21893 |     NULL | NULL   |      | BTREE      |         |               |
| users |          0 | index_users_on_confirmation_token                   |            1 | confirmation_token   | A         |          28 |     NULL | NULL   | YES  | BTREE      |         |               |
| users |          0 | index_users_on_reset_password_token                 |            1 | reset_password_token | A         |          50 |     NULL | NULL   | YES  | BTREE      |         |               |
| users |          0 | index_users_on_application_id_and_external_user_id  |            1 | application_id       | A         |          32 |     NULL | NULL   | YES  | BTREE      |         |               |
| users |          0 | index_users_on_application_id_and_external_user_id  |            2 | external_user_id     | A         |         995 |     NULL | NULL   | YES  | BTREE      |         |               |
| users |          0 | index_users_on_application_id_and_login             |            1 | application_id       | A         |          30 |     NULL | NULL   | YES  | BTREE      |         |               |
| users |          0 | index_users_on_application_id_and_login             |            2 | login                | A         |       21893 |     NULL | NULL   | YES  | BTREE      |         |               |
| users |          1 | users_account_id_fk                                 |            1 | account_id           | A         |          44 |     NULL | NULL   |      | BTREE      |         |               |
| users |          1 | users_blob_id_fk                                    |            1 | blob_id              | A         |         118 |     NULL | NULL   | YES  | BTREE      |         |               |
| users |          1 | index_users_on_remember_token                       |            1 | remember_token       | A         |           8 |     NULL | NULL   | YES  | BTREE      |         |               |
| users |          1 | index_users_on_application_id                       |            1 | application_id       | A         |          32 |     NULL | NULL   | YES  | BTREE      |         |               |
| users |          1 | index_users_on_application_id_and_facebook_id       |            1 | application_id       | A         |          32 |     NULL | NULL   | YES  | BTREE      |         |               |
| users |          1 | index_users_on_application_id_and_facebook_id       |            2 | facebook_id          | A         |        3127 |     NULL | NULL   | YES  | BTREE      |         |               |
| users |          1 | index_users_on_application_id_and_twitter_digits_id |            1 | application_id       | A         |          32 |     NULL | NULL   | YES  | BTREE      |         |               |
| users |          1 | index_users_on_application_id_and_twitter_digits_id |            2 | twitter_digits_id    | A         |         138 |     NULL | NULL   | YES  | BTREE      |         |               |
| users |          1 | index_users_on_application_id_and_email             |            1 | application_id       | A         |          32 |     NULL | NULL   | YES  | BTREE      |         |               |
| users |          1 | index_users_on_application_id_and_email             |            2 | email                | A         |        2189 |     NULL | NULL   | YES  | BTREE      |         |               |
| users |          1 | index_users_on_application_id_and_full_name         |            1 | application_id       | A         |          32 |     NULL | NULL   | YES  | BTREE      |         |               |
| users |          1 | index_users_on_application_id_and_full_name         |            2 | full_name            | A         |        5473 |     NULL | NULL   | YES  | BTREE      |         |               |
+-------+------------+-----------------------------------------------------+--------------+----------------------+-----------+-------------+----------+--------+------+------------+---------+---------------+
19 rows in set (0.01 sec)

Example of EXPLAIN:
mysql> EXPLAIN SELECT  `users`.* FROM `users` WHERE `users`.`application_id` = 56374  ORDER BY id asc LIMIT 1 OFFSET 0;
+----+-------------+-------+------+----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+----------------------------------------------------+---------+-------+------+-----------------------------+
| id | select_type | table | type | possible_keys                                                                                | key                                                | key_len | ref   | rows | Extra                       |
+----+-------------+-------+------+----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+----------------------------------------------------+---------+-------+------+-----------------------------+
|  1 | SIMPLE      | users | ref  | index_users_on_application_id_and_external_user_id,index_users_on_application_id_and_login,index_users_on_application_id,index_users_on_application_id_and_facebook_id,index_users_on_application_id_and_twitter_digits_id,index_users_on_application_id_and_email,index_users_on_application_id_and_full_name | index_users_on_application_id_and_external_user_id | 5       | const |    1 | Using where; Using filesort |
+----+-------------+-------+------+----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+----------------------------------------------------+---------+-------+------+-----------------------------+
1 row in set (0.00 sec)

The problem itself is that using wrong index causes queries like that (with a limit of 100 instead of 1) to be performed MINUTES, while with a correct index it is a matter of split second.
Profiling:
SET PROFILING = 1; SELECT `users`.* FROM `users` WHERE `users`.`application_id` = 56374  ORDER BY id asc LIMIT 1 OFFSET 0; SHOW PROFILE FOR QUERY 1; SET PROFILING = 0;
Query OK, 0 rows affected (0.00 sec)

+----------+----------+-----------------+-------+-------+----------------------------------------------------------------------------------------------------------------------------------+----------------------+-------+---------+---------------------+---------------------+---------------------+------------------+-------------+------------+---------+----------------------+------------------------+---------------------+--------------------+---------------------+----------------------+-------------------+------------+----------------+-------------+---------------------------------------------------------------------------------------+-------------------+-------------------------+--------------------------------------------------+----------------+
-- fields list --
+----------+----------+-----------------+-------+-------+----------------------------------------------------------------------------------------------------------------------------------+----------------------+-------+---------+---------------------+---------------------+---------------------+------------------+-------------+------------+---------+----------------------+------------------------+---------------------+--------------------+---------------------+----------------------+-------------------+------------+----------------+-------------+---------------------------------------------------------------------------------------+-------------------+-------------------------+--------------------------------------------------+----------------+
| 27265241 |     NULL | Some Username | NULL  | 9777  | SomeHash | AnotherHash | NULL  | NULL    | 2017-04-12 15:53:32 | 2017-09-21 13:39:51 | 2017-09-24 19:19:06 |             1234 | NULL        | NULL       |    NULL | NULL                 | NULL                   | NULL                | NULL               | 2017-07-05 10:59:59 | NULL                 | NULL              |      12345 | NULL           | NULL        | something_else | NULL              |                       1 | another_hash |          54321 |
+----------+----------+-----------------+-------+-------+----------------------------------------------------------------------------------------------------------------------------------+----------------------+-------+---------+---------------------+---------------------+---------------------+------------------+-------------+------------+---------+----------------------+------------------------+---------------------+--------------------+---------------------+----------------------+-------------------+------------+----------------+-------------+---------------------------------------------------------------------------------------+-------------------+-------------------------+--------------------------------------------------+----------------+
1 row in set (1 min 14.43 sec)

+--------------------------------+-----------+
| Status                         | Duration  |
+--------------------------------+-----------+
| starting                       |  0.000068 |
| Waiting for query cache lock   |  0.000025 |
| init                           |  0.000025 |
| checking query cache for query |  0.000047 |
| checking permissions           |  0.000026 |
| Opening tables                 |  0.000031 |
| After opening tables           |  0.000025 |
| System lock                    |  0.000025 |
| Table lock                     |  0.000026 |
| Waiting for query cache lock   |  0.000037 |
| init                           |  0.000046 |
| optimizing                     |  0.000032 |
| statistics                     |  0.000225 |
| preparing                      |  0.000042 |
| executing                      |  0.000025 |
| Sorting result                 |  0.000057 |
| Sending data                   | 42.952100 |
| end                            |  0.000070 |
| query end                      |  0.000027 |
| closing tables                 |  0.000025 |
| Unlocking tables               |  0.000028 |
| freeing items                  |  0.000028 |
| updating status                |  0.000039 |
| cleaning up                    |  0.000025 |
+--------------------------------+-----------+
24 rows in set (0.00 sec)

Query OK, 0 rows affected (0.00 sec)

A: You should be able to use index-hints and optimizer hints to suggest correct index usage:
Index hints
Optimizer hints
You could hint directly the table:
tbl_name [[AS] alias] [index_hint_list]

index_hint_list:
    index_hint [index_hint] ...

index_hint:
    USE {INDEX|KEY}
      [FOR {JOIN|ORDER BY|GROUP BY}] ([index_list])
  | IGNORE {INDEX|KEY}
      [FOR {JOIN|ORDER BY|GROUP BY}] (index_list)
  | FORCE {INDEX|KEY}
      [FOR {JOIN|ORDER BY|GROUP BY}] (index_list)

index_list:
    index_name [, index_name] ...

In your case I think the best solution would be to name the attributes by name and not to use star * and to use IGNORE INDEX (unique_index_users_on_application_id_and_login, unique_index_users_on_application_id_and_phone ) FOR ORDER BY directly at the query:
An example based on your code:
SELECT  u.id,
        u.application_id,
        u.login,
        u.phone,
        # ... here to continue
FROM users as u
IGNORE INDEX (unique_index_users_on_application_id_and_login, unique_index_users_on_application_id_and_phone ) FOR ORDER BY
WHERE u.application_id = 1234
ORDER BY u.id
LIMIT 10 OFFSET 0;

First Edit
Due to a comment below I'm adding a trick with invalidating a primary key.
You could also go a way of invalidating the primary key by this trick:
SELECT u.id,
       u.application_id,
       u.login,
       u.phone,
       #...
FROM users as u
WHERE u.application_id = 1234
ORDER BY u.id+0

A: It's hard to be certain, but in very many cases, MySQL is good at selecting the correct index.
It may be necessary to update the statistics for the query analyzer -  occasionally the query analyzer doesn't have good information on the data, and this can lead to weird behaviour.
However...your index_users_on_application_id only has application_id, but not ID.
I'm guessing that application_id has a fairly low number of distinct values. ColumnID is unique, and has as many values as there are rows in the table. There is no index that includes both the where clause and the order by clause, so MySQL guesses that the most expensive part will be ordering by ID, rather than filtering by application_id.
So, I think MySQL is doing the right thing here. Behind the scenes, it's returning all the rows ordered by ID, and going through that list and giving you the first 10 with the specified application_ID.
The obvious thing to do is to create an index with application_id and ID, and see if MySQL picks that.

A: When you use ORDER BY column_name MySQL scan all data in column given in ORDER BY clause, here in your case id column will get scan. For this database use Table pointer. In InnoDB, it is the value of the PRIMARY KEY and in MyISAM, it is an offset in the .MYD file.
That's why when you use ORDER BY id your query start using only primary key as index.
To use you created index add id column as first column of index. Then it will use index effectively. So your index unique_index_users_on_application_id_and_login on users table should contains columns as follows in same sequence 1- id & 2- application_id.
For more details about MySQL performance of ORDER BY/ LIMIT Go here


text:
Q: malloc touching unallocated memory I'm wondering why my allocation is working. I created ptr which is a pointer and ptr2 which a pointer on the same location than ptr.
Here's my code:
int* ptr = malloc(sizeof(int));
int* ptr2 = ptr;
*ptr2 = 1;
ptr2 = ptr+1;
*ptr2 = 2;

At the end I've an array of two integer like that :
ptr[0] = 1
ptr[1] = 2

My question is : why I can affect the value 2 to ptr2 without error or warnings ? I only malloc()-ed for one integer place in my array, isn't it?

A: The problem here is, by saying
  ptr2 = ptr+1;

you're pointing to out of bound memory. Next upon dererencing, you invoke undefined behavior. Now, the outcome of UB cannot be justified, in any way.
There is nothing inherent in C that stops you from accessing out of bound (or invalid) memory, but the outcome of doing so is UB.
That said, just a suggestion, you should always check the returned value of malloc() before using that pointer to avoid UB by dereferencing NULL pointer, in case of malloc() failure.


text:
Q: Ubuntu 18.04 does not boot and hangs on power off, on new Vivobook: I've bought new Asus Vivobook without OS. I've prepared bootable pendrive with Ubuntu 18.04 and I've gotten problem with installation - could not find SSD.
I've changed in BIOS a SATA option to AHCI and added set pci=nomsi in GRUB and managed to install on SSD.
Unfortunately the OS bahaves strangely. In most cases it won't boot completely or hangs on poweroff.
When it doesn't boot all the way after GRUB it hangs on a purple screen.
I have logs: https://pastebin.com/CKVGQhpA


text:
Q: Erlang: get information from parsed html My project is still encoding. But unfortunately I encountered another problem.
Recently, I manage to get html code from website with erlang and I parse that information in mochiweb plugin.
Here what have got now:
    {<<"html">>,[],
 [{<<"head">>,[],[]},
  {<<"body">>,[],
   [{<<"table">>,[],
     [{<<"tr">>,[],
       [{<<"td">>,[{<<"id">>,<<"day">>}],[<<"Poniedzialek ">>]},
        {<<"td">>,[{<<"id">>,<<"temp">>}],[<<" -5 ">>]},
        {<<"td">>,[{<<"id">>,<<"wiatr">>}],[<<"13 km/h">>]}]},
      {<<"tr">>,[],
       [{<<"td">>,[{<<"id">>,<<"day">>}],[<<"Wtorek ">>]},
        {<<"td">>,[{<<"id">>,<<"temp">>}],[<<" -15 ">>]},
        {<<"td">>,[{<<"id">>,<<"wiatr">>}],[<<"13 km/h">>]}]},
      {<<"tr">>,[],
       [{<<"td">>,[{<<"id">>,<<"day">>}],[<<"Sroda ">>]},
        {<<"td">>,[{<<"id">>,<<"temp">>}],[<<" 10 ">>]},
        {<<"td">>,[{<<"id">>,<<"wiatr">>}],[<<"13 km/h">>]}]},
      {<<"tr">>,[],
       [{<<"td">>,[{<<"id">>,<<"day">>}],[<<"Czwartek ">>]},
        {<<"td">>,[{<<"id">>,<<"temp">>}],[<<" 12 ">>]},
        {<<"td">>,[{<<"id">>,<<"wiatr">>}],[<<"13 km/h">>]}]},
      {<<"tr">>,[],
       [{<<"td">>,[{<<"id">>,<<"day">>}],[<<"Piatek ">>]},
        {<<"td">>,[{<<"id">>,<<"temp">>}],[<<" 20 ">>]},
        {<<"td">>,[{<<"id">>,<<"wiat"...>>}],[<<"13 km/h">>]}]},
      {<<"tr">>,[],
       [{<<"td">>,[{<<"id">>,<<"day">>}],[<<"Poniedzialek"...>>]},
        {<<"td">>,[{<<"id">>,<<"temp">>}],[<<" -5 ">>]},
        {<<"td">>,[{<<"id">>,<<...>>}],[<<"13 k"...>>]}]}]}]}]}

And now I'd like to extract information about temperature, wind. How to make function in erlang to get exactly temperature in maybe list or add to json file, without any unnecessary things.

A: Now I've got:
[{<<"td">>,[{<<"id">>,<<"temp">>}],[<<" -5 ">>]},
 {<<"td">>,[{<<"id">>,<<"temp">>}],[<<" -15 ">>]},
 {<<"td">>,[{<<"id">>,<<"temp">>}],[<<" 10 ">>]},
 {<<"td">>,[{<<"id">>,<<"temp">>}],[<<" 12 ">>]},
 {<<"td">>,[{<<"id">>,<<"temp">>}],[<<" 20 ">>]},
 {<<"td">>,[{<<"id">>,<<"temp">>}],[<<" -5 ">>]}]

Ok I got that:
[<<" -5 ">>]

How extract only -5 ?


text:
Q: Just a loop, and 33 leaks Look something strange on my mac :
$> cat main.c

#include <stdio.h>
int main(int ac, char **av) {
    for (int i = 0; i < ac; i++)
        printf("%s\n", av[i]);
    return 0;
}

$> gcc main.c -std=c99
$> valgrind ./a.out hello my friends

And here is the result :
==725== Memcheck, a memory error detector
==725== Copyright (C) 2002-2011, and GNU GPL'd, by Julian Seward et al.
==725== Using Valgrind-3.7.0 and LibVEX; rerun with -h for copyright info
==725== Command: ./a.out hello my friends
==725==
--725-- ./a.out:
--725-- dSYM directory is missing; consider using --dsymutil=yes
./a.out
hello
my
friends
==725==
==725== HEAP SUMMARY:
==725==     in use at exit: 6,146 bytes in 33 blocks
==725==   total heap usage: 33 allocs, 0 frees, 6,146 bytes allocated
==725==
==725== LEAK SUMMARY:
==725==    definitely lost: 0 bytes in 0 blocks
==725==    indirectly lost: 0 bytes in 0 blocks
==725==      possibly lost: 0 bytes in 0 blocks
==725==    still reachable: 6,146 bytes in 33 blocks
==725==         suppressed: 0 bytes in 0 blocks
==725== Rerun with --leak-check=full to see details of leaked memory
==725==
==725== For counts of detected and suppressed errors, rerun with: -v
==725== ERROR SUMMARY: 0 errors from 0 contexts (suppressed: 1 from 1)

If someone knows why, and could explain me where does theses leaks come from, I'd be thankful !!
Have a good day :-)

A: These aren't leaks. Objects listed as still reachable shouldn't trouble you. If you'd have a non-zero value in the rows above then it should ring an alarm bell though!
Those 33 blocks listed as still reachable are most probably some blocks allocated inside  printf calls by your standard library. Nothing to be worried about.
Consider also taking a look at this answer to a similar question.

A: "still reachable" when a program has terminated is really nothing to worry about.
"still reachable" means that there are allocated memory which hasn't been released, but there are still pointers pointing towards this memory. Therefor valgrind doesn't flag it as a true memory "leak".
It's often a waste of time to spend time free:ing the allocated memory before a application ends, the allocated memory will be returned to the OS anyhow since the application is terminating.


text:
Q: org.xerial.snappy.SnappyError: [FAILED_TO_LOAD_NATIVE_LIBRARY] no native library is found for os.name=Mac and os.arch=aarch64 I'm building a cdc pipeline to read mysql binlog through maxwell and putting them into kafka my compression type is snappy in maxwell config.But at consumer end in my spring project I'm getting this error.
org.xerial.snappy.SnappyError: [FAILED_TO_LOAD_NATIVE_LIBRARY] no native library is found for os.name=Mac and os.arch=aarch64
at org.xerial.snappy.SnappyLoader.findNativeLibrary(SnappyLoader.java:361) ~[snappy-java-1.1.7.7.jar:1.1.7.7]
at org.xerial.snappy.SnappyLoader.loadNativeLibrary(SnappyLoader.java:195) ~[snappy-java-1.1.7.7.jar:1.1.7.7]
at org.xerial.snappy.SnappyLoader.loadSnappyApi(SnappyLoader.java:167) ~[snappy-java-1.1.7.7.jar:1.1.7.7]
at org.xerial.snappy.Snappy.init(Snappy.java:69) ~[snappy-java-1.1.7.7.jar:1.1.7.7]
at org.xerial.snappy.Snappy.<clinit>(Snappy.java:46) ~[snappy-java-1.1.7.7.jar:1.1.7.7]
at org.xerial.snappy.SnappyInputStream.hasNextChunk(SnappyInputStream.java:435) ~[snappy-java-1.1.7.7.jar:1.1.7.7]
at org.xerial.snappy.SnappyInputStream.read(SnappyInputStream.java:466) ~[snappy-java-1.1.7.7.jar:1.1.7.7]
at java.base/java.io.DataInputStream.readByte(DataInputStream.java:271) ~[na:na]
at org.apache.kafka.common.utils.ByteUtils.readUnsignedVarint(ByteUtils.java:170) ~[kafka-clients-2.7.2.jar:na]
at org.apache.kafka.common.utils.ByteUtils.readVarint(ByteUtils.java:205) ~[kafka-clients-2.7.2.jar:na]
at org.apache.kafka.common.record.DefaultRecord.readFrom(DefaultRecord.java:296) ~[kafka-clients-2.7.2.jar:na]
at org.apache.kafka.common.record.DefaultRecordBatch$2.doReadRecord(DefaultRecordBatch.java:278) ~[kafka-clients-2.7.2.jar:na]
at org.apache.kafka.common.record.DefaultRecordBatch$StreamRecordIterator.readNext(DefaultRecordBatch.java:617) ~[kafka-clients-2.7.2.jar:na]
at org.apache.kafka.common.record.DefaultRecordBatch$RecordIterator.next(DefaultRecordBatch.java:582) ~[kafka-clients-2.7.2.jar:na]
at org.apache.kafka.common.record.DefaultRecordBatch$RecordIterator.next(DefaultRecordBatch.java:551) ~[kafka-clients-2.7.2.jar:na]
at org.apache.kafka.clients.consumer.internals.Fetcher$CompletedFetch.nextFetchedRecord(Fetcher.java:1578) ~[kafka-clients-2.7.2.jar:na]
at org.apache.kafka.clients.consumer.internals.Fetcher$CompletedFetch.fetchRecords(Fetcher.java:1613) ~[kafka-clients-2.7.2.jar:na]
at org.apache.kafka.clients.consumer.internals.Fetcher$CompletedFetch.access$1700(Fetcher.java:1454) ~[kafka-clients-2.7.2.jar:na]
at org.apache.kafka.clients.consumer.internals.Fetcher.fetchRecords(Fetcher.java:687) ~[kafka-clients-2.7.2.jar:na]
at org.apache.kafka.clients.consumer.internals.Fetcher.fetchedRecords(Fetcher.java:638) ~[kafka-clients-2.7.2.jar:na]
at org.apache.kafka.clients.consumer.KafkaConsumer.pollForFetches(KafkaConsumer.java:1299) ~[kafka-clients-2.7.2.jar:na]
at org.apache.kafka.clients.consumer.KafkaConsumer.poll(KafkaConsumer.java:1233) ~[kafka-clients-2.7.2.jar:na]
at org.apache.kafka.clients.consumer.KafkaConsumer.poll(KafkaConsumer.java:1206) ~[kafka-clients-2.7.2.jar:na]

My java version "17.0.2" 2022-01-18 LTS
and using Apple M1 chip.

A: You'll need to update snappy version to 1.1.8.4 or later:
    <dependency>
      <groupId>org.xerial.snappy</groupId>
      <artifactId>snappy-java</artifactId>
      <version>1.1.8.4</version>
    </dependency>

Source:
https://issues.apache.org/jira/browse/BEAM-11863?page=com.atlassian.jira.plugin.system.issuetabpanels%3Acomment-tabpanel&focusedCommentId=17318180#comment-17318180


text:
Q: Can WT present web pages as part of the host page? Update 3
user52875 also has a very good answer, Can WT present web pages as part of the host page? which uses HTML, and is actually a lot easier than messing with JS. +1 to you good sir.
Update 2
Figured it out, working code bellow. You need to use an iframe in javascript to embed another page in your own. The IP address is another PC on a local network that runs a WT server with some content, I was able to connect and view the contents of the WT server. Also, for some reason the iframe is unable to connect to browsing sites such as google or yahoo. Though I am sure there is a separate question on that that somewhere.
WText* text = new WText(root);
string command = string("var ifr") + " = document.createElement('iframe');" +
                 //"ifr.src = 'http://javascript.info';" +         //Works
                 //"ifr.src = 'http://www.escapistmagazine.com';" +//Works
                 //"ifr.src = 'http://escapistmagazine.com';" +    //Works
                 //"ifr.src = 'http://google.com';" +              //Doesn't work
                 //"ifr.src = 'http://www.google.com';" +          //Doesn't work
                 "ifr.src = 'http://12.3.45.678:8080/';" +         //Works
                 "ifr.width = 1500;" +
                 "ifr.height = 700;" +
                 "document.body.appendChild(ifr);";
text->doJavaScript(command);

Update 1
It would seem that this requires the use of JS iframes with WT objects. Javascript is not my strong point, but I have done some embedding of applications using WT doJavaScript() command(Embedding Ventus in WT and Using ACE with WT). I will update the post further if I find the proper way to embed the page in WT. Thanks in advance for any help.
WText* text = new WText(root);
string command = ""; //TODO: Proper creation and use of JS iframe.
text->doJavaScript(command);

Original Post
So, I am trying to create a small WT app in which I have a collection of anchors, or a text box and a button to type in and switch pages. The basic setup is like this:
WContainerWidget* root = wApp->root();

WAnchor* Google = new WAnchor("http://www.google.com/", "Google", root);
root->addWidget(new Wt::WBreak());

WAnchor* Yahoo = new WAnchor("http://www.yahoo.com/", "Yahoo", root);
root->addWidget(new Wt::WBreak());

Wt::WLineEdit* GotoBar = new Wt::WLineEdit(root);
Wt::WPushButton* GotoButton = new Wt::WPushButton("Goto address", root);

//TODO: Some kind of widget that will present the content of the anchors
//      or the GotoBar

So, what I am trying to do is present the content of a different page without leaving the host page. Is this possible? I've been reading documentation and browsing the widget gallery, but so far have not found anything that relates to embedding remote content into your own page. My long term goal is to have an anchor connect to an IP address of another PC, on the same network, and present the content of a WT server running on that PC in my own host page without leaving it. Thanks in advance for any help!

A: There is a similar question and its answer here. Hope it helps.
http://www.mail-archive.com/witty-interest@lists.sourceforge.net/msg01578.html

A: Do this:
WText *myIframe = new WText(this);
// Very important: if your url comes from a user, sanitize it or you create a
// very nice XSS attack vector. AFAIK not all functions required are publicly
// available in Wt. XHTMLUnsafeText switches of Wt's built-in XSS filer, which
// filters out iframes.
myIframe->setText("<iframe src='http://12.34.56.78:8080/' width=100 height=100></iframe>", XHTMLUnsafeText);

Using this method, you can also remove the iframe, that is not possible with your JS-based solution you mention in your update.


text:
Q: iOS Location Services asks on app open Just trying to add location services to my app (in ObjC). I only want the permissions prompt to appear when I am about to use it, however the prompt appears when I first open the app.
My impression was that the prompt would only appear when startUpdatingLocation was called on the CLLocationManager object. However this is only called in my app on certain ViewControllers (definitely not my first view controller).
Interestingly this issue only appears in iOS8, it's fine in iOS7. Anyone had a similar issue? Or have any idea what else could be wrong?
Thanks.

A: iOS 8 changes how location services are handled, and it also means that if you're supporting older versions of the OS you potentially need to do some extra coding. For an wonderfully detailed look at the entire process, checkout NSHipster
Prior to iOS 8, yes calling startUpdatingLocation would prompt the user for permission. Though now requesting permission and starting the location updates are separate and you'll need to call requestWhenInUseAuthorization or requestAlwaysAuthorization.
Not only that, but in iOS8 you need to explicitly add two plist keys and then define their values: NSLocationWhenInUseUsageDescription and NSLocationAlwaysUsageDescription, which are strings that will show up in the alert that notifies users that your app is requesting location information.
But seriously, check out the link. It's phenomenal at explaining this all, far better than I could summarize here.

A: Without knowing where you had placed your code, the way I would approach this issue is

*

*Create a method that asks for location access i.e. - (void) findLocationAsk

*Now don't call this method right on app launch as you didn't want that behavior

*Call this method in your view controller

*You can call it in your viewDidLoad or as a button action or fire it as a timer.

This should take care of your prompt on app launch
UPDATE:
Your app will prompt for location access right on startup on iOS 8. This is because the "Required background modes" required key is detected in plist file. The only thing you can do is make that message more descriptive as to why you need access. Add this key and description pair to your plist file and add whatever explanation text you like in it
NSLocationWhenInUseUsageDescription
Please grant this app access to your location incase of failed login attempts are detected and you want to know who it was


text:
Q: Problem on combining bar and line plot in seaborn I am trying to combine a line plot and bar plot in seaborn. Code is as below:)
fig, ax1 = plt.subplots(figsize=(10,6))
sns.barplot(x=df_mergedpa['Day'], y=df_mergedpa['pro_mean'],hue=df_mergedpa['Strain'], ax=ax1)
ax2 = ax1.twinx()
sns.lineplot(x=df_mergedpa['Day'],y=df_mergedpa['ami_mean'],hue=df_mergedpa['Strain'],
marker='o',  ax=ax1)

The plot I am getting is as above:

Why the line plot is not rendering properly. It is extending in X-Axis. I am not able to figure out why?
Dataframe looks as below:


text:
Q: Objective-C in Mono I have a .NET application, which I want to port to OSX. Up to now I used a DirectShow DLL for WebCam handling. Can I use an Objective-C DLL for Mono? How? I'm a newbie on Mac. Is there an existing (WebCam handling) solution for this? Is there a better solution?

A: You want to use the QTKit framework to do this, in particular you can use the QTCaptureView as a reusable NSView that you can embed in an existing window or in an application to do the actual video capturing.
I have just added support for capturing to the MonoMac bindings a few minutes ago after I saw your question, so you will need to do a little bit of work.
Steps:

*

*Install Mono, MonoDevelop and the MonoMac addin as described here: http://mono-project.com/MonoMac

*Download the latest sources for MonoMac and MacCore from Github: http://github.com/mono/maccore and http://github.com/mono/monomac

*Update the MonoMac.dll to the latest version, by going into the monomac/src directory and typing "make update"
At this point you should be able to use the QTCaptureView in your MonoMac applications like any other NSView.   A tutorial showing the use of the API in Objective-C is here:
http://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/QTKitApplicationTutorial/BuildingaSimpleQTKitCaptureApplication/BuildingaSimpleQTKitCaptureApplication.html#//apple_ref/doc/uid/TP40008155-CH8-SW1
You can just use the equivalent versions in C#

A: I'm not sure what you mean by "an object-c dll for Mono".
Your absolute best approach is to learn the platform you're targeting and port only the logic and general architecture.
To access cameras, microphones, line-ins, etc. on Mac OS X, use QTKit (Quicktime Kit). It's mind-numbingly simple to set up a web cam view, record to files, grab frames, etc. It's built in and designed to make this sort of thing mostly drag-and-drop for developers.

A: MonoMac is just one alternative. There are Monobjc, CocoSharp, NObjective, MObjc / MCocoa and ObjC# (I cannot choose between them). Theese are all "bridges" between Mono and Cocoa, what mean you can use Cocoa API in Mono application. But I don't want to use the API directly. I just want a dinamically linked library, which provide me some function for WebCam handling (as I said, I did this up to this time on Windows). In other words: I need a wrapper in Mono for QTKit.
PS: If I rewrite the application in object-c that means several months, and double work in the future when the application will grow. I love object-c but I hate to work unnecessary.

A: I tried the accepted code in XCode, and when I tried to port to Monodevelop, several classes are missing, eg. QTCaputureSession, QTCaputreDeviceInput, CVimagebuffer.
(Sorry, I cannot edit my previous messages, this is another account.)


text:
Q: Merging two oracle database instances in one instance I have an environment where data from different versions of the same application (which runs on top of an Oracle database) need to be merged into a single database instance. From a database point of view, each version runs on top of a single schema and in addition to the standard objects (tables, procedures, sequences, constraints, etc), each version has a set of user definied tables that also needs to be present on the new instance.
Considering the implications of this type of merge (PK/FK collisions between standard tables, sequence/index rebuilding, etc.), what would be the best merge strategy for this case?


text:
Q: PHP - Converting Seconds to Minutes discrepancy I'm running into a discrepancy with either my conversion of an integer into defined Minutes.
<?php
$seconds = 269;
echo date("G:i:s", $seconds);
// result: 0:04:29
?>

I figured I'd double check on some sites to see if the conversion is correct:
Here's one I found:
http://www.thecalculatorsite.com/conversions/time.php
The result returned is: 4.4833333333333
Example 1 returns: 0:04:29
Example 2 returns: 4.4833333333333
I'm confused about this.
What am I missing here.  Am I using the date() function incorrectly?

A: Be careful with date(). it expects to be provided with a PHP timestamp, which is number of seconds since midnight, Jan 1/1970. It will "work" for small timestamp values, but will get increasingly wrong as you pass in "larger" timestamps, as you will be dealing with months/days/years in 1970, plus leapyears, etc...
As for the conversion, what's wrong with it? 4.48333... is 4 full minutes, and 0.483333 is simply 29/60.

A: You can use DateTime class for time calculation:
Code:
$start = new DateTime;
$end = clone $start;
$end->modify('+269 seconds');
$diff = $start->diff($end);
print_r($diff);

Output:
DateInterval Object
(
    [y] => 0
    [m] => 0
    [d] => 0
    [h] => 0
    [i] => 4
    [s] => 29
    [invert] => 0
    [days] => 0
)

As you can see in output, you have all the info you need. To access it, just use $diff->i for minutes, $diff->s for seconds etc.