text:
Q: Hyperparameter tune for Tensorflow I am searching for a hyperparameter tune package for code written directly in Tensorflow (not Keras or Tflearn). Could you make some suggestion?

A: I'd like to add one more library to @jdehesa's list, which I have applied in my research particularly with tensorflow. It's hyper-engine, Apache 2.0 licensed.
It also implements Gaussian Process Bayesian optimization and some other techniques, like learning curve prediction, which save a lot of time.

A: You can try out Ray Tune, a simple library for scaling hyperparameter search. I mainly use it for Tensorflow model training, but it's agnostic to the framework - works seamlessly with PyTorch, Keras, etc. Here's the docs page - ray.readthedocs.io/en/latest/tune.html
You can use it to run distributed versions of state-of-the-art algorithms such as HyperBand or Bayesian Optimization in about 10 lines of code.
As an example to run 4 parallel evaluations at a time:
import ray
import ray.tune as tune
from ray.tune.hyperband import HyperBandScheduler

def train_model(config, reporter):  # add the reporter parameter
    model = build_tf_model(config["alpha"], config["beta"])
    loss = some_loss_function(model)
    optimizer = tf.AdamOptimizer(loss)

    for i in range(20):
        optimizer.step()
        stats = get_statistics()
        reporter(timesteps_total=i,
                 mean_accuracy=stats["accuracy"])

ray.init(num_cpus=4)
tune.run(train_model,
    name="my_experiment",
    stop={"mean_accuracy": 100},
    config={
        "alpha": tune.grid_search([0.2, 0.4, 0.6]),
        "beta": tune.grid_search([1, 2])
    },
    scheduler=HyperBandScheduler(reward_attr="mean_accuracy"))

You also don't need to change your code if you want to run this script on a cluster.
Disclaimer: I work on this project - let me know if you have any feedback!

A: Usually you don't need to have your hyperparameter optimisation logic coupled with the optimised model (unless your hyperparemeter optimisation logic is specific to the kind of model that you are training, in which case you would need to tell us a bit more). There are several tools and packages available for the task. Here is a good paper on the topic, and here is a more practical blog post with examples.

*

*hyperopt implements random search and tree of parzen estimators optimization.

*Scikit-Optimize implements a few others, including Gaussian process Bayesian optimization.

*SigOpt is a convenient service (paid, although with a free tier and extra allowance for students and researchers) for hyperparameter optimization. It is based upon Yelp's MOE, which is open source (although the published version doesn't seem to update much) and can, in theory, be used on its own, although it would take some additional effort.

*Spearmint is a commonly referred package too, also open source but not free for commercial purposes (although you can fall back to a less restrictive older version). It looks good, but not very active, and the available version is not compatible with Python 3 (even though pull requests have been submitted to fix that).

*BayesOpt seems to be the golden standard in Bayesian optimization, but it's mainly C++, and the Python interface doesn't look very documented.

Out of these, I have only really (that is, with a real problem) used hyperopt with TensorFlow, and it didn't took too much effort. The API is a bit weird at some points and the documentation is not terribly thorough, but it does work and seems to be under active development, with more optimization algorithms and adaptations (e.g. specifically for neural networks) possibly coming. However, as suggested in the previously linked blog post, Scikit-Optimize is probably as good, and SigOpt looks quite easy to use if it fits you.

A: I'm not sure if this is also the parameters that you want but you mentioned TensorFlow hyperparameters so I guess I can suggest some.
Try to clone this repository for having the needed scripts;

git clone https://github.com/googlecodelabs/tensorflow-for-poets-2

and in the Master folder, invoke your command prompt and run this line;

python -m scripts.retrain -h

to get the list of optional arguments.
Source: https://codelabs.developers.google.com/codelabs/tensorflow-for-poets/#6

A: I found sci-kit optimize very simple to use for bayesian optimization of hyperameters, and it works with any tensorflow API (estimator, custom estimator, core, keras, etc.)
https://stackoverflow.com/a/53582472/2218905

A: You could use variational inference (bayesian) as a point cloud over the optimization space; hyperparameter tuning would be much better. Tensorflow probability would be an approach.


text:
Q: Split key: value; pairs and exclude whitespace in matches Let's say we've a string like this: '  key1  :  value1  ;  key2  :  value2 value3  ' and we want to convert it into a javasript-object. We can match aything that is not a delimiter (:;) and capture these matches. Great, got this job done with a simple regular expression:
/([^:]+):?([^;]+);?/g

Problem with my current RegExp is, that it also include whitespace in the results. So the string above will result in something like this:
{
  "  key1  ": "  value1  ",
  "  key2  ": "  value2 value3  "
}

Not really what we want... So I've changed the RegExp to this:
/\s*([^:]+)\s*:?\s*([^;]+);?\s*/g

Arr, damn! The character-set [^:]+ matches anything that is not a colon (so also whitespace). What will result in something like this:
{
  "key1  ": "value1  ",
  "key2  ": "value2 value3  "
}

Any idea how we can capture only the keys / values, without including whitespace in the match. So that our result looks like this:
{
  "key1": "value1",
  "key2": "value2 value3"
}

By the way, this is how the full parsing-function looks like:
var parseAttributes = function (attribute) {
  var REGEX_SPLIT_PAIRS = /;?([^:]+):?([^;]+);?/g;
  var attributes = {};
  var match;

  while (match = REGEX_SPLIT_PAIRS.exec(pairs)) {
    attributes[match[1]] = match[2];
  }

  return attributes;
};

Edit
Another way is doing it with splitting the attribute-string down into the pair-chunks. However, I think about a pure RegExp-solution, without trim:
var parseAttributes = function (attribute) {
  var attributes = {};

  attribute.split(';').forEach(function (pair) {
    var pairs = pair.split(':');
    if (pairs && pairs[0] && pairs[1]) {
      attributes[pairs[0].trim()] = pairs[1].trim();
    }
  });

  return attributes;
};

A: You could try the below regex to capture Key,Value pair separately
\s*(\S+)\s*:\s*([^;\s]*(?:\s*\w+))

DEMO

A: Can you guarantee that every entry will match the model "  key : value ;", that every entry will have a ":" and a ";" delimiter? If so, this may work:
/\s*([^:]+?)\s*:\s*([^;]+?)\s*;/g

A: /\s*([^:]+)\s*:?\s*([^;]+);?\s*/g matches whitespace because the first match is greedy; to stop this just add a ? to the match.
I think that /\s*([^:]+?)\s*:?\s*([^;]+?)\s*;?\s*/g will do what you want.

A: I don't know if it will work but,
did you tried?  /[a-z0-9]+/g

redpajama_set_name: RedPajamaStackExchange


text:
Q: Google Chrome error
 I have installed Google Chrome by .deb file from google.com/chrome/
Installation was ok but when I opening through terminal it says the code below although it opens it self. And it's unopenable from launcher.
Help me please
drinkon@drinkon:~$ google-chrome
ATTENTION: default value of option force_s3tc_enable overridden by environment.
[6662:6662:0918/163724:ERROR:sandbox_linux.cc(308)] InitializeSandbox() called with multiple threads in process gpu-process
[6622:6622:0918/163724:ERROR:desktop_window_tree_host_x11.cc(1478)] Not implemented reached in void views::DesktopWindowTreeHostX11::MapWindow(ui::WindowShowState)

EDIT:
Not it gives me this:
google-chrome
ATTENTION: default value of option force_s3tc_enable overridden by environment.
[2647:2647:0922/182234:ERROR:sandbox_linux.cc(308)] InitializeSandbox() called with multiple threads in process gpu-process
[2607:2607:0922/182238:ERROR:desktop_window_tree_host_x11.cc(1478)] Not implemented reached in void views::DesktopWindowTreeHostX11::MapWindow(ui::WindowShowState)
[2607:2607:0922/182315:ERROR:CONSOLE(26)] "Uncaught Error: Assertion failed", source: chrome://resources/js/util.js (26)
[2607:2818:0922/182317:ERROR:get_updates_processor.cc(240)] PostClientToServerMessage() failed during GetUpdates
[2607:2644:0922/183114:ERROR:connection_factory_impl.cc(335)] Failed to connect to MCS endpoint with error -21
[2607:2644:0922/183143:ERROR:connection_factory_impl.cc(335)] Failed to connect to MCS endpoint with error -106
[2607:2644:0922/183324:ERROR:connection_factory_impl.cc(335)] Failed to connect to MCS endpoint with error -21
[2607:2644:0922/183348:ERROR:connection_factory_impl.cc(335)] Failed to connect to MCS endpoint with error -106
[2607:2644:0922/183438:ERROR:connection_factory_impl.cc(335)] Failed to connect to MCS endpoint with error -106
[2607:2644:0922/183617:ERROR:connection_factory_impl.cc(335)] Failed to connect to MCS endpoint with error -106
[2607:2644:0922/183945:ERROR:connection_factory_impl.cc(335)] Failed to connect to MCS endpoint with error -106
[2607:2644:0922/184631:ERROR:connection_factory_impl.cc(335)] Failed to connect to MCS endpoint with error -106
[2607:2644:0922/185631:ERROR:connection_factory_impl.cc(335)] Failed to connect to MCS endpoint with error -106
[2607:2818:0922/185842:ERROR:get_updates_processor.cc(240)] PostClientToServerMessage() failed during GetUpdates
[2607:2818:0922/185843:ERROR:get_updates_processor.cc(240)] PostClientToServerMessage() failed during GetUpdates
[2607:2818:0922/185845:ERROR:get_updates_processor.cc(240)] PostClientToServerMessage() failed during GetUpdates
[2607:2818:0922/185848:ERROR:get_updates_processor.cc(240)] PostClientToServerMessage() failed during GetUpdates
[2607:2818:0922/185855:ERROR:get_updates_processor.cc(240)] PostClientToServerMessage() failed during GetUpdates
[2607:2818:0922/185906:ERROR:get_updates_processor.cc(240)] PostClientToServerMessage() failed during GetUpdates
[2607:2818:0922/185908:ERROR:get_updates_processor.cc(240)] PostClientToServerMessage() failed during GetUpdates
[WARNING:flash/platform/pepper/pep_module.cpp(63)] SANDBOXED

A: This is a bug related with GPU rendering options, but not all bugs are problematics.
If you don't want to see those messages, open your browser adding extra option in command line.
google-chrome --disable-gpu

or
google-chrome > /dev/null 2>&1

This bug is reported since chrome/chromium 33 in 2013.

A: I was getting similar problems when I installed Chrome. It may be related to the way in which the computer connects to the DNS Server because I'd get this error when I was connecting to the work network but not when I was connecting to my home wifi.
I ended up uninstalling Google Chrome and installed Chromium Browser instead. Not only is the installation easier, but it's less resource intensive and works exactly like Chrome for all intents and purposes (all your Chrome bookmarks sync seamlessly into Chromium and the interface is pretty much identical).
Good luck!

A: Try using chromium. It's into he Ubuntu App Store. It's the open source version of chrome. Just search chrome in the search bar or App Store.


text:
Q: iOS 10, bluetooth connection from today extension / widget I´m having an App with a Today Extension/Widget. This Widget has a CBCentralManager to scan for peripherals and connect to them. The scanner works fine but connecting to the device sometimes works and sometimes get´s stuck at connecting. The led at my bluetooth device lights up briefly so I see that there is some kind of communication.
The very same code works perfectly fine in the app itself just not from the widget.
When I run the widget on a iOS 9 device it also works fine!
Are there any known issues with connecting to a bluetooth device from a today extension on iOS 10?
Thanks
Stephan


text:
Q: SUMIFS with mutliple OR/AND criterias (using a cell reference)       A             B              C            D               E            F          G        E
1  Products     Suppliers        Value     Criteria 1:     Product_C      Result:      600
2  Product_A    Supplier_01      500       Criteria 2:     Supplier_01
3  Product_B    Supplier_01      600       Criteria 3:     Supplier_03
4  Product_B    Supplier_02      300
5  Product_C    Supplier_01      200
6  Product_C    Supplier_01      400
7  Product_C    Supplier_03      800
8
9

In the table you find a list of different Products (Column A) and Suppliers (Column B).
In Cell G1 I want to get the sum of the values in Column C if the following conditions are met:
Product = Product_C AND
Supplier = Supplier_01 OR Supplier_03
Those conditions are typed in as Criteria 1-3 in Cells E1:E3.
In order to achieve this I tried to go with the solution from these questions (Q1,Q2) which gives me the correct result:
G1 =SUM(SUMIFS($C:$C,$A:$A,$E$1,$B:$B,{"Supplier_01","Supplier_02"}))

However, my issue with this solution is that I need to enter the OR-criterias manually as {"Supplier_01","Supplier_02"}.  How do I have to change my formula so I can refer to the values in Cells E2:E3 so if the user changes those values the result is automatically adjusted?

A: One possibility:
=SUMPRODUCT((A2:A7=E1)*((B2:B7=E2)+(B2:B7=E3))*C2:C7)

It will be easy to extend criteria in the same fashion for both column A and B.

A: I was going to say that you need to transpose E2:E3. I think this is true in general, but in this particular case with only a single criterion applying to column A, you don't need to:
=SUM(SUMIFS($C:$C,$A:$A,$E$1,$B:$B,$E$2:$E$3))

works if entered as an array formula.
If you have multiple criteria for  A and B, you do need to transpose one set of criteria:
=SUM(SUMIFS($C:$C,$A:$A,$E$1:$E$2,$B:$B,TRANSPOSE($E$3:$E$4)))

A: try this
=SUM(SUMIFS($C:$C,$A:$A,$E$1,$B:$B,E2:E3))

or
=SUM(IF(($A$2:$A$7=E1)*(($B$2:$B$7=E2)+($B$2:$B$7=E3)),$C$2:$C$7,0))


text:
Q: filestream not finishing writing to to file What the program does is goes out to a webpage, reads the source line by line, strips out the html tags/code, and then writes the actual text/information to a text file. Because I want the text file to only contain the data/information I want and nothing else, I have it looking for a specific string that tells it it's found the right section so it can start writing to the text file, and then it looks for another string to know when it's found the end of the section. It correctly starts and stops at the right lines in the file (I put in a counter to make sure, and it was correctly stopping/starting in the right spots), however, it doesn't finish writing all of the information to text file. It doesn't even stop at the end of a specific line -- it often stops writing in the middle of a line. As an example, if I want it to read 4 lines, the output might look like:
Text for line 1..
Text for line 2..
Text for li
and just stop, even though it should read/write 4 lines.
Below is my code:
private void button1_Click(object sender, EventArgs e)
{

    string tempString = "";
    string startString = "start string";
    string endString = "end string";
    bool startFlag = false;
    bool endFlag = true;
    string filename = @"C:\file.txt";

    System.IO.StreamWriter file = new System.IO.StreamWriter(filename);

    WebRequest request = WebRequest.Create("http://www.website.com/webpage.html");
    request.Credentials = CredentialCache.DefaultCredentials;
    HttpWebResponse response = (HttpWebResponse)request.GetResponse();
    Console.WriteLine(response.StatusDescription);
    Stream dataStream = response.GetResponseStream();
    StreamReader reader = new StreamReader(dataStream);

    while (endFlag)
    {
        tempString = reader.ReadLine();

        if (tempString.Contains(startString))
        {
            startFlag = true;
        }

        if (tempString.Contains("text"))
        {
            ...
        }

        if (tempString.Contains("other text"))
        {
            if (startFlag)
                file.WriteLine(tempString.Trim());
        }

        if (tempString.Contains("different text"))
        {
                if (startFlag && tempString.Length > 0)
                    file.WriteLine(tempString.Trim());
        }

        if (tempString.Contains(endString))
        {
            endFlag = false;
        }
    }

    MessageBox.Show("Done!", "Finished Writing", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);

    reader.Close();
    dataStream.Close();
    response.Close();

    Process.Start(filename);

    this.Close();
}

I've tried just about everything I can think of, I've tried using flush, I've tried having it continue reading/writing past the string that signals the end of the section, but nothing seems to work. I know I'm not the greatest coder by any means, but I'm really stumped. Can anyone share some insight? Any help greatly appreciated!

A: You have to Flush() your file ... Or use
using( System.IO.StreamWriter file = new System.IO.StreamWriter(filename)){
   ....
}
Process.Start(filename);

A: Your StreamWriter file is not closed or flushed before you call Start on the file name.
Either Close or Dispose file object. Or even better wrap it in using.

A: private void button1_Click(object sender, EventArgs e)
{

    string tempString = "";
    string startString = "start string";
    string endString = "end string";
    bool startFlag = false;
    bool endFlag = true;
    string filename = @"C:\file.txt";

    using (System.IO.StreamWriter file = new System.IO.StreamWriter(filename))
    {
        WebRequest request = WebRequest.Create("http://www.website.com/webpage.html");
        request.Credentials = CredentialCache.DefaultCredentials;
        using (HttpWebResponse response = (HttpWebResponse) request.GetResponse())
        {
            Console.WriteLine(response.StatusDescription);
            using (Stream dataStream = response.GetResponseStream())
            {
                using (StreamReader reader = new StreamReader(dataStream))
                {
                    while (endFlag)
                    {
                        tempString = reader.ReadLine();

                        if (tempString.Contains(startString))
                        {
                            startFlag = true;
                        }

                        if (tempString.Contains("text"))
                        {
                            // ...
                        }

                        if (tempString.Contains("other text"))
                        {
                            if (startFlag)
                                file.WriteLine(tempString.Trim());
                        }

                        if (tempString.Contains("different text"))
                        {
                            if (startFlag && tempString.Length > 0)
                                file.WriteLine(tempString.Trim());
                        }

                        if (tempString.Contains(endString))
                        {
                            endFlag = false;
                        }
                    }

                    MessageBox.Show("Done!", "Finished Writing", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);

                    reader.Close();
                }
                dataStream.Close();
            }
            response.Close();
        }
    }

    Process.Start(filename);

    this.Close();
}


text:
Q: How to modify a Vim buffer with a python script? The official Vim python interface documentation states, that modifying buffers with python is very simple, basically:
:py import vim
:py vim.current.buffer[0] = "Hello world"

However, python throws an exception, when I try to do that:
Traceback (most recent call last):
  File "<string>", line 1, in <module>
TypeError: bad argument type for built-in operation

Read-only access (e.g. :py print vim.current.buffer[0] works just fine. Am I missing something here? Why can't I modify vim buffers with python scripts?
[Note: I'm using recent Vim 7.3]

A: Works for me, "Hello World" is inserted in buffer. Is your vim compiled with +python
I'm using version 7.3.162
EDIT
looking in the hg log for if_python.c I see a lot issues related to python, e.g. this one:
changeset:   2641:b803b2776880
tag:         v7-3-062
user:        Bram Moolenaar <bram@vim.org>
date:        Tue Nov 16 19:26:02 2010 +0100
files:       src/auto/configure src/configure.in src/if_python.c src/if_python3.c src/version.c
description:
updated for version 7.3.062
Problem:    Python doesn't work properly when installed in another directory
        than expected.
Solution:   Figure out home directory in configure and use Py_SetPythonHome()
        at runtime. (Roland Puntaier)

Which version are you on?

A: This may be an encoding issue. I've run into a very similar (but not identical) use case, e.g. inside a vim python function:
buf = vim.current.buffer
names = [x.name for x in triggers] #encoded as a default python unicode, e.g. u'foo'
names = [x.encode('utf-8') for x in names] # Force to utf-8
buf[:] = names #Now this works.

Without forcing it into utf-8, I get the same exception, which I think is related to how vim handles python's default (for me) us-ascii strings. After converting to utf-8 it works fine. I hope this helps.


text:
Q: Updating controller data doesnt update the view - Angular JS - Ionic I have this controller :
.controller("mainctrl",function($scope,$state){
        var self = this;

        var usuario = window.localStorage.getItem('usuario');
        this.msjs=[];

        var res = window.localStorage.getItem(usuario+'_msjs');
        if(res===null)
        {
            this.msjs=[];
        }
        else{
            this.msjs=JSON.parse(res);
        }

        $scope.$on('newMessageReceived', function(e, msg) {
            //alert('message received:'+msg);
            self.msjs.push(msg);
            alert('mensaje recibido');
            alert(JSON.stringify(self.msjs));

            window.localStorage.setItem(usuario+'_msjs',JSON.stringify(self.msjs));
            $state.reload();

        });
  }

And the view:
<ion-view ng-controller="mainctrl as m" >
             <ion-nav-buttons side="right">
                 <button class="button" ng-click="m.logout()">Logout</button>
             </ion-nav-buttons>
             <ion-content id="msjcontent">

Mensajes

                     {{msj}}

             </ion-content>
</ion-view>

When the $scope receives the event it pushes a new element in the  'msjs' array.
The view doesnt update the data. I had to put $state.reload() to refresh the $state (ui-router from Angular-Ionic) and watch the changes. This refresh is giving me problems such as multiple copies of $scopes (1 for each $state.reload() ). i've already tried with $scope.apply() and it didnt work. I think the problem may be  Ionic/angular ui-router stuff.
I want to know a better way to bind the msjs array to the view without refresh the $state.
Thanks.

A: I was writing $scope.apply() and the correct method is $scope.$apply().

A: .state(url: '/url', controller: Ctl,  templateUrl: 'template.html', cache: false)
cache: false ==> solved my problem ^^


text:
Q: tangent and normal bundle Find the tangent and normal bundle of $Y$ where the mapping $f:[-1,1]\times[1,2]\to Y$ is defined as
$$f(x,y)=\left(x\sqrt{\frac{y}{1+x^2}},\sqrt{\frac{y}{1+x^2}},xy\right).$$
Then show that $Y$ is orientable.
So as far as I know, the tangent bundle is determined by $f$ and a linear combination of $f_x$ and $f_y$.
So I calculated both partial derivatives and so the tangent bundle would be $(f(x,y),Lin\{f_x(x,y),f_y(x,y)\})$ where $(x,y)\in[-1,1]\times[1,2]$. Is this correct?
If yes, then the normal bundle would be $(f(x,y),Lin\{f_x(x,y)\times f_y(x,y)\})$ so we take the cross product of the partials.
I also am not sure how to prove that we can orient $Y$ and how to choose the orientation. Any suggestions?

A: Your proof for the tangent and normal bundle are correct. For the orientation you want to used the induced orientation from $[-1,1]\times [1,2]$. Then you need to check whether $f$ is injective. If it is you are done, if not you need to check whether distinct points in $[-1,1]\times [1,2]$ that map to the same point have the same orientation. Essentially you want to distinguish whether the image of $f$ is just a deformed rectangle, some flat ribbon or a version of the Möbius strip.
Edit: I claim that $f$ is injective on the given domain. Suppose $f(x_1,y_1)=f(x_2,y_2)$, then $$x_1\sqrt{\frac{y_1}{1+x_1^2}}=x_2\sqrt{\frac{y_2}{1+x_2^2}}$$ and $$\sqrt{\frac{y_1}{1+x_1^2}}=\sqrt{\frac{y_2}{1+x_2^2}}$$ These can only both be satisfied if either $\sqrt{\frac{y_1}{1+x_1^2}}=0$ which can't happen for $y \in[1,2]$ or if $x_1=x_2$. If $x_1=x_2$, the third equation $$x_1y_1=x_2y_2$$ implies $y_1=y_2$ or $x_1=0$ and $f(0,y)$ is injective as well.


text:
Q: Debugging touchesEnded NOT being called when swiping in 1 direction only Totally stumped in debugging a simple swipe movement for my application. When I swipe in a left direction, I correctly get a touchesEnded message-method call.
BUT, if I drag in the other direction, touchesEnded does NOT get called.
Anyone have a clue as to why this might be?
I'm using a TapDetectingView as my view for my viewController class. And user intraction and multiple touch are both enabled for this view in IB.

A: I had some issues too, using GestureRecognizers and touchesEnded on a single view.
My problem was, that I was either able to detect swipes OR touches when using GestureRecognizers only.
What I ended up doing, was using SwipeGestureRecognizers to detect swipes and the touchesEnded Method for Taps.
Using TapGestureRecognizers and SwipeGestureRecognizers on the same view didn't work.

A: If you're trying to capture the touchesEnded on a swipe gesture try checking for touchesCancelled.  I handle my swipe ends via the touchesCancelled and then call touchesEnded from within that method.  For some reason touchesEnded is only called via single taps and long presses but not swipes.  The nice thing is that you get a timestamp and coordinates to use for figuring out acceleration.


text:
Q: Datagrid not displaying initial values of data source I'm using a WPF Datagrid and set the ItemSource to an ObservableCollection.  If the data in the collection changes the DataGrid shows the latest values.  If the collection values don't change after I set the ItemsSource, and assuming the collection has values other than 0, the DataGrid only displays 0 until the data in the collection changes.  Basically it isn't displaying the initial values in the collection.
I've implemented INotifyPropertyChanged
I've tried DataGrid.Items.Refresh();
Any ideas would be appreciated.
My Error, the values were not being propagated to the collection until the source of the data changed.

A: My Error, the values were not being propagated to the collection


text:
Q: Best way to sync two MS-ACCESS 2010 ACCDB files Not using programing Here's my situation:
two computer in two separate city use one MS-ACCESS .accdb file which computer#1 is for data entry, and Computer #2 is for using data and reports and ... .
i need to find the best way to sync the .accdb file between these two computers without losing any data and of course without any duplication. please note that there are more than 20 tables in this .accdb and all have a field named "ID" with "AutoNumber" Type.
What do you suggest? Export data from computer#1 in xml format and import to computer#2 or any other ways?
I'm looking forward for your helpful answers.
Thank you for taking time.

A: Ensure you are using a split  database, email the data from city 1 to city 2, attach the tables, if necessary, it will not be necessary if names are not changed and you have linked before.
How to manually split a Access database in Microsoft Access
Import or link to data in another Access database


text:
Q: Why is my C++ program crashing as soon as I input a letter or number? I start off the program with debugging with a successful build. Then it loads up a screen that says enter a character. I enter a letter. As soon as I press enter the program crashes. Why is this happening? I am running Visual Studio 2015 edition.

A: When you run a program in visual studio (with debugging), the program will execute and the console will automatically kill itself after it's done. The reason it doesn't immediately kill execution is because it is waiting for your input. It is hard to be certain without seeing your code itself, but you are likely not waiting on user input after that initial input. Instead, your program probably just prints something to the console with some intermediary calculations and/or format adjustments. You should add breakpoints if you want to run with debugging, but otherwise I would suggest that you run without debugging if you want to manually close the console.


text:
Q: How can __len__ check type of output despite being overridden? The __len__/__repr__ methods make sure that the output is always int/str even when I override them.
My question is:
How can I inherit a functionality around a method of a subclass?
(just like I can override __len__ but it still checks that the output is integer?)
For example, even if overridden, __len_ still does something like this:
def __len__(self):
   out = ...
   assert type(out) == int
   return out

A: The __len__ and __str__ methods don't do this, as demonstrated below:
>>> class A:
...     def __len__(self):
...         return 'foo'
...     def __str__(self):
...         return 22
...
>>> a = A()
>>> a.__len__()
'foo'
>>> a.__str__()
22

It is the len and str functions which check it:
>>> len(a)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'str' object cannot be interpreted as an integer
>>> str(a)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: __str__ returned non-string (type int)

So the answer is simple: those functions are built-in in Python, and they are written to check the type returned by the __len__ and __str__ methods before passing those return values on.

A: You can't do this, and __len__() doesn't, the trick here is you don't call __len__() directly, you call len() which then calls __len__(), as pointed out in
kaya3's answer.
You can, however, repeat this pattern to do a similar thing in your code. Provide a method the user should override, and then another one that calls that method and validates it as necessary for end-users of the type to call.
E.g:
class SomeClass(ABC):
    def do_something(self):
        """Call to do something."""
        result = do_something_unsafe()
        if validate(result):
            return result
        else:
            raise ...

    @abstractmethod
    def do_something_unsafe(self):
        """Override me in subclasses."""
        return ...

Of course, if it makes sense in your API, you could also follow the given example use a top-level function, which is less likely to be overridden by mistake.


text:
Q: How big of a HDD can a Mid 2010 Mac Pro handle? I heard somewhere that the maximum HDD size that my Mid 2010 Mac Pro can handle is 4TB.  Is this correct?  If not, how big can I go?

A: It's not that they can't address a larger drive, it's that the screw holes don't fit the 'sleds' that the drives are mounted on.
OWC sell replacements - http://eshop.macsales.com/item/OWC/MPRODBKTLG6/ though I have no idea if they ship outside the US, or indeed if that would be worth it.
Standard sled - 4 mount points.

6TB compatible sled - 6 mount points

Pics from OWC [no affiliation]

A: The OS X HFS+ Operating System will max out around 8 EB (Exabytes)
To put that into perspective:
8EB = 8,000 Petabytes
1 Petabyte = 1,000 Terrabytes
1 TB = 1,000 GB
In other words...
8 EB = 8 Million TB or 2 million of your 4 TB Hard Drives.  I hope you have room under your desk.
However, a 4 TB drive will easily be installed or you could opt for one of the new 8 TB Helium Drives.


text:
Q: Route prefixes in NestJS I have a bunch of modules that logically belong together, and should be namespaces under /api. I've been trying every which way to make it work with the RouterModule as well as with nest-router, and for some reason I cannot seem to make it work. As soon as I put my modules in either nest-router's RouterModule.forRoutes(routes), or in the built-in RouterModule's RouterModule.register([]) call, the modules don't even get initialized anymore:
Before:
[Nest] 40601  - 17/11/2022, 15:29:26     LOG [InstanceLoader] ViewModule dependencies initialized +1ms
[Nest] 40601  - 17/11/2022, 15:29:26     LOG [InstanceLoader] CacheableModule dependencies initialized +0ms
[Nest] 40601  - 17/11/2022, 15:29:26     LOG [InstanceLoader] JobApplicationModule dependencies initialized +1ms
[Nest] 40601  - 17/11/2022, 15:29:26     LOG [InstanceLoader] CandidateProfileModule dependencies initialized +0ms
[Nest] 40601  - 17/11/2022, 15:29:26     LOG [InstanceLoader] BrandModule dependencies initialized +0ms
[Nest] 40601  - 17/11/2022, 15:29:26     LOG [InstanceLoader] OtpModule dependencies initialized +1ms
{"level":40,"time":1668695365622,"pid":40601,"hostname":"SLBR62611.local","msg":"Preflight conditions have not passed, disabling APM."}

after:
[Nest] 40618  - 17/11/2022, 15:29:52     LOG [InstanceLoader] ViewModule dependencies initialized +0ms
[Nest] 40618  - 17/11/2022, 15:29:52     LOG [InstanceLoader] CacheableModule dependencies initialized +0ms
{"level":40,"time":1668695391435,"pid":40618,"hostname":"SLBR62611.local","msg":"Preflight conditions have not passed, disabling APM."}

Even if I strip down my routes file to just this, the modules & their controllers and routes don't get loaded:
export const routes: Routes = [
  {
    path: '/otp',
    module: OtpModule,
  },
  {
    path: '/job-applications/:applicationId',
    module: BrandModule,
  },
];


text:
Q: Breeze is not storing the right value (that is set in code) when saving during entityChanged event I'm have a Breeze, Typescript, MVC 5.2, Knockout, Entity Framework webapp. I try to update a value of an User entity when the user clicks on a row in a grid (kogrid). The value is (should be) saved in the entityChanged eventhandler, but in Fiddler I see that the property value has not changed and the entityAspect.entityState is set to Modified (!) The originalValuesMap has the old TenantId and is the only value in the map.
I subscribe to the entity changed event like this:
this.EntityManager.entityChanged.subscribe((data: breeze.EntityChangedEventArgs) => {
    if (data.entityAction == breeze.EntityAction.PropertyChange) {
                return this.EntityManager.saveChanges(<breeze.Entity[]> new Array(data.entity))
                    .fail((error) => alert("Failed. " + error));}

        });

The data arrives correctly a the eventhandler. A savechanges call is made, but the changed value (tenantId) has not changed.
The eventhandler for the rowclick is as follows:
ViewModel).OnRowClick = (tenantId: KnockoutObservable<System.IGuid>, viewModel: Imp.Scripts._TenantListViewModel) => {
        entityManager.fetchEntityByKey("User", viewModel.Settings().CurrentUser().UserId(), false)
        .then(entityKeyResult => {
            (<Imp.Classes.UserBreeze>entityKeyResult.entity).CurrentTenantId(tenantId());
            //entityManager.saveChanges(<breeze.Entity[]> new Array(entityKeyResult.entity));
         })
        .fail((error)=> alert("Error setting current tenant. " + error));});

When I disable the entityChanged subscription and enable the comment out line entityManager.saveChanges.... the entity is saved correctly. If I uncomment the line, but keep the subscription, it does not work.
How can I save the changed entity automatically after it changes?
EDIT:
Workaround is to disable the entityChanged eventhandler temporarily before changing the value CurrentTenantId on the current user, save the entity manually and re-subscribe to the entityChanged event.
But this solution smells.

A: Few suggestions:

*

*Consider throttling the saves if propertychanged events are fired frequently.  Knockout has a rate limiting extender for this purpose.

*You may also want to consider using breeze save queuing plugin so you don't need to worry about overlapping save calls as much.

*To troubleshoot the save issue, try adding the following code immediately before calling saveChanges:

if (data.entityAction === breeze.EntityAction.PropertyChange) {
    var pcArgs = <breeze.PropertyChangedEventArgs>data.args;
    console.log('Property Changed.  PropertyName: ' + pcArgs.propertyName + '; Old Value: ' + (pcArgs.oldValue ? pcArgs.oldValue.toString() : 'null') + '; New Value: ' + (pcArgs.newValue ? pcArgs.newValue.toString() : 'null') + ';');
}


text:
Q: Notepad++: Positional Insert (automatic padding) Sometimes, it makes more sense to see text appear side by side and to be able to arbitrarily insert characters to the right of what's been written (without having to pad the ends of each lines with space characters until you're at the column position where you want to insert text).

It'd be convenient to have a toggle-hotkey binding (Ctrl + Left-Click) that automatically pads spaces to the column position you've clicked and insert that padding for each subsequent lines (until you turn it off).
Is this a feature of notepad++ or some notepad++ plugin? Is this a feature of any other editor (if so, what is it called there)?

A: *

*Alt + Left-click mouse + Select the block you want

*Ctrl + C

*Alt + Left-click mouse + Select the first column where you want to put the block

*Ctrl + V


text:
Q: Firestore document full of key/values or multiple documents - which is faster/better for speed? If I'm trying to store key/value pairs of emails:phones, would it be better to have one document full of the emails:phones fields, or multiple documents, where the document.id would be the email and each document has one phone listed?
Example 1:
 collectionA -> documentA -> "email1": (number) 1234567890,
                             "email2": (number) 1234567899,
                             ...

Example 2:
 collectionA -> documentA -> "email1": (number) 1234567890,
                documentB -> "email1": (number) 1234567899
                ...

what if I have a dataset of 100? 1000? multiple thousands?
I think Example 2 would be better because Example 1 requires loading the whole document before accessing the desired key/value, right?
Edit: this is based on me knowing the email but not knowing the phone number.

A: It's only possible to determine which one is "better" if you examine specific use cases.  Neither one is 100% is fully advantaged over the other.
Problems with #1:

*

*Large volumes of entries will eventually fill up the max limit of a document (1MB), at which point writes will fail.

*If you're only looking for one entry, it requires reading all of the entries, as it's not possible to read a partial document (on mobile clients only, server SDKs can do projections, however).

*It's not possible to query by number without knowing the email.

Problems with #2:

*

*Reading the entire set of N costs N document reads.  For very large sets, this can get more expensive than needed, and would likely be slower than reading one document with everything.

You will have to pick which problems are less bad for your expected use cases.


text:
Q: Bash script, case statement and sub-menus I wish to run a script with a case statement leading to choices between other lists of choices (sort of sub-menus) between scripts :
#!/bin/bash

echo "Your choice ?"
echo "1) Foo"
echo "2) Bar"
echo "3) Stuff"
read case;

case $case in

#and this is where I would like to allow
#(here a simplified example I do not manage to code)

1) What script ?    # may I use another case statement ?
    a) Foo1;;
    b) Foo2;;
2) What script ?    # d°
    a) Bar1;;
    b) Bar2;;
    c) Bar3;;

esac

Foo1, Foo2, Bar1, Bar2 and Bar3 being in fact bash scripts, I would like to call, eg, sh Foo1 from within the script.
How must I proceed :
May I include a case statement within a case statement (better than if statement, if the choices are numerous) ?
And how do I call a script from within another script ?
Thanks in advance for your help
ThG

A: Yes, you can nest case statements. You should also consider using a select statement instead of all those echo and read statements.
options=("Option 1" "Option 2" "Option3" "Quit")
optionsprompt='Please enter your choice: '

sub1=("Option 1 sub 1" "Option 1 sub 2")
sub1prompt='Please enter your choice: '

PS3=$optionsprompt
select opt in "${options[@]}"
do
    case $opt in
        "Option 1")
            echo "you chose choice 1"
            PS3=$sub1prompt
            select sub1opt in "${sub1[@]}"
            do
                case $sub1opt in
                    "Option 1 sub 1")
                        echo "you chose choice 2"
                        ;;
                    "Option 1 sub 2")
                        echo "you chose choice 2"
                        ;;
                 esac
            done
            ;;
        "Option 2")
            echo "you chose choice 2"
            ;;
        "Option 2")
            echo "you chose choice 3"
            ;;
        "Quit")
            break
            ;;
        *) echo invalid option;;
    esac
done

The first level menu would look like this:
1) Option 1
2) Option 2
3) Option3
4) Quit
Please enter your choice:

However, that can get very hairy very quickly. It would be better to break it up into functions where the inner select/case statements are in separate functions or are abstracted so you can pass arguments to control them.
To call another script, you might want to set a variable that holds the directory. It would look something like this:
basedir=/some/path

case ...
...
    $basedir/Foo    # call the script

A: Dennis' answer should do what you want. Just to illustrate how to do it with functions, so as to make the script more readable:
function which_foo {
    local foo_options=("foo1" "foo2" "cancel")
    local PS3="Select foo: "

    select foo in "${foo_options[@]}"
    do
        case $REPLY in
            1) ./foo1.sh
               break ;;

            2) ./foo2.sh
               break ;;

            3) break ;;
        esac
    done
}

ACTIONS=("foo" "bar" "quit")
PS3="Select action: "

select action in "${ACTIONS[@]}"
do
    case $action in
         "foo") which_foo
                break ;;

         "bar") which_bar # Not present in this example
                break ;;

        "quit") break ;;
    esac
done

As an aside, note:

*

*the use of $REPLY in the case inside which_foo, which is automatically set to the number selected by the user, instead of the text of the option.

*the use of break in each case options. Without them, select puts you in a loop, so the user would be asked to enter a choice again.

*that select never changes the value of PS3 for you, so you have to do it yourself when switching between the different levels of your menu.


text:
Q: Accessing Lambda Variables I'm trying to work with a lambda expression right now, and I have a variable initialized outside of the lambda expression. Inside of the expression, I'm trying to set the value of that variable so that I can use it outside of the expression, but I can't can't because the "Variable used in lambda expression should be final or effectively final". Any ideas? The only way I see is to somehow initialize the variable INSIDE the scope of the lambda but then I don't know how to access it outside of that scope at that point.
Member name; //My Variable
event.reply("Ok! Give me the name a user. Like this: @TI-84+");
waiter.waitForEvent(MessageReceivedEvent.class, e -> e.getAuthor().equals(event.getAuthor()), e -> {
    event.reply("Searching the archives on information for user: " + e.getAuthor() + "...");
    name = e.getMessage().getMentionedMembers().get(0); //Problem because you can't set an implicitly final variable
});


text:
Q: Thymeleaf: Do not render during unit test? As I haven't gotten an answer for my other question here, I am looking for another approach. Is there a way to no not execute or include a fragment during unit testing?
I want to display the version and build number in the footer of my templates, thus I have the following line:

Version

This works well when running the application, but during unit test I get the exception:

No bean named 'buildProperties' available

In the other question I am looking for a way to get this bean during unit test, as an alternative I am now looking for a way to exclude this template during unit tests. Something like this:

Version

I am using the following annotations on my test class:
@RunWith(SpringRunner.class)
@WebMvcTest(SimpleController.class)

A: If it's a standard unit-test, use Mockito to mock the bean:
@RunWith(MockitoJUnitRunner.class)
public class SomeTest{

  @Mock
  private BuildProperties buildProperties;

  ...

Or, if it's a Spring MVC test:
@RunWith(SpringRunner.class)
@WebMvcTest(value = MyController.class)
public class MyControllerTest{

  @MockBean
  private BuildProperties buildProperties;

The version will be null, because all of the methods of the mocked bean returns null.
if you want to emulate a real version you can add something like this to your test or to the setUp() method
given(buildProperties.getVersion()).willReturn("whatever");

--------------- edit
Unfortunately all of the above solutions work only if the buildProperties bean was added to the model directly.
But in your case you use the bean directly as a SpEL bean reference. Unfortunately I don't know any way to check if a bean exists in the context via SpEL.
Also, it's not a good practice to add extra code into your code for checking if it's running in test mode.
So I think the best solution if you create a nested test configuration class and define a default BuildProperties bean there.
@TestConfiguration
public static class TestConfig {
  @Bean
  BuildProperties buildProperties() {
    return new BuildProperties(new Properties());
  }
}

Or you can use @Import(TestConfig.class) if you need this extra configuration in multiple test classes.

A: I got a hint from a colleague that works for this question.
Just add an application.properties to src/test/resources with a custom property:
isUnitTest=true

Then I can simply check for this in my thymeleaf template:

Version

Though if someone finds a way to achieve this automatically with a thymeleaf setting or property I didn't find so far, I will accept it as an answer.


text:
Q: 2D perlin noise in C I followed this tutorial.
When I implement it in my code (Raytracing), and apply it on a sphere, I get a uni-color sphere, with one stripe of darker pixel on it. When I change the random float generator, I got the basic linear noise, which isn't my goal. Can you explain what I missed?
Here is my code:
#include    <stdlib.h>
#include    <math.h>

float       noise(int x, int y)
{
  int       n;

  n = x + y * 57;
  n = pow((n << 13), n);
  return (1.0 - ( (n * (n * n * 15731 + 789221) + 1376312589) & 0x7fffffff) / 1073741824.0);
}

float       interpolate(float a, float b, float x)
{
  float     pi_mod;
  float     f_unk;

  pi_mod = x * 3.1415927;
  f_unk = (1 - cos(pi_mod)) * 0.5;
  return (a * (1 - f_unk) + b * x);
}

float       smooth_noise(int x, int y)
{
  float     corners;
  float     center;
  float     sides;

  corners = (noise(x - 1, y - 1) + noise(x + 1, y - 1) +
         noise(x - 1, x + 1) + noise(x + 1, y + 1)) / 16;
  sides = (noise(x - 1, y) + noise(x + 1, y) + noise(x, y - 1) +
       noise(x, y + 1)) / 8;
  center = noise(x, y) / 4;
  return (corners + sides + center);
}

float       noise_handler(float x, float y)
{
  int       int_val[2];
  float     frac_val[2];
  float     value[4];
  float     res[2];

  int_val[0] = (int)x;
  int_val[1] = (int)y;
  frac_val[0] = x - int_val[0];
  frac_val[1] = y - int_val[1];
  value[0] = smooth_noise(int_val[0], int_val[1]);
  value[1] = smooth_noise(int_val[0] + 1, int_val[1]);
  value[2] = smooth_noise(int_val[0], int_val[1] + 1);
  value[3] = smooth_noise(int_val[0] + 1, int_val[1] + 1);
  res[0] = interpolate(value[0], value[1], frac_val[0]);
  res[1] = interpolate(value[2], value[3], frac_val[0]);
  return (interpolate(res[0], res[1], frac_val[1]));
}

float       perlin_two(float x, float y)
{
  float     total;
  float     per;
  float     amp;
  int       hz;
  int       i;
  int       octave;

  total = 0.0;
  per = 0.5;
  octave = 10;
  i = 0;
  while (i < octave)
    {
      hz = pow(2, i);
      amp = pow(per, (float)i);
      total += noise_handler(x * (float)hz, y * (float)hz) * amp;
      i += 1;
    }
  return (total);
}

EDIT: I spot an error in the Noise function (I consider the XOR operand like a power function ... Now I get a barcode, as if the y parameter was ignored in the operations ...

A: Had to implement this in C recently and this post helped get me started. One fix for the noise function as previously stated.
float noise(int x, int y) {
    int n;

    n = x + y * 57;
    n = (n << 13) ^ n;
    return (1.0 - ( (n * ((n * n * 15731) + 789221) +  1376312589) & 0x7fffffff) / 1073741824.0);
}

Most importantly, is that Fractal Brownian Motion is really important when implementing Perlin Noise for use in a height map. Instead of following the pseudo code by Hugo Elias, I used this Google Code Snippet.
float perlin_two(float x, float y, float gain, int octaves, int hgrid) {
    int i;
    float total = 0.0f;
    float frequency = 1.0f/(float)hgrid;
    float amplitude = gain;
    float lacunarity = 2.0;

    for (i = 0; i < octaves; ++i)
    {
        total += noise_handler((float)x * frequency, (float)y * frequency) * amplitude;
        frequency *= lacunarity;
        amplitude *= gain;
    }

    return (total);
}

Before I did this, I'd had the same issue with uniform 'stripping' or just complete random looking height maps.

A: You got to debug & rework probably all your variable types; do the math in pen & paper or in a debugger and check the range of the values. e.g. here
noise(int x, int y) {
      int n = x + y * 57;
      n = pow((n << 13), n);  ...
}

n will either underflow or overflow for almost all non-zero values. Good random values can't be produced with any random method, which is what these formulas look like.
Check also this topic for some reference code.


text:
Q: Import works, but why is require not working? I am using webpack to build a simple project, in main.js.  If I use import to import app.js, the result works well. However, if I use require the vue template won't show on the page.
I thought Babel compiles the import to require; if so, why is require not working here?
The result of using require:
<!DOCTYPE html>

    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>

123

index.html
<!DOCTYPE html>

    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>

123

main.js
const Vue = require("vue");
const router = require('vue-router')
// const app = require('./app.vue')
import app from './app.vue'

new Vue({
el: "#app",
data: {},
render: el => el(app),
// router
})

webpack.config.js
const htmlPlugin = require('html-webpack-plugin')

module.exports = {
  entry: path.join(__dirname, "./src/main.js"),

  output: {
    path: path.join(__dirname, "./dist"),
    filename: "bundle.js"
  },

  module: {
    rules: [
      { test: /\.js$/, use: "babel-loader", exclude: /node_modules/ },
      { test: /\.vue$/, use: "vue-loader" }
    ]
  },
  plugins: [
    new htmlPlugin({
      minify: {
        removeAttributeQuotes: true
      },
      hash: true,
      template: "./src/index.html"
    })
  ],
  resolve: {
    // extensions: [ '.vue'],
    alias: {
      'vue$': 'vue/dist/vue.common.js'
    }
  },
};

app.js
<template>

test

</template>

A: require and import are different in how they access the imported object.
import app from './app.vue'

This line actually means this, and this should work just the same as the import:
const app = require('./app.vue').default

For completeness' sake, this line:
const app = require('./app.vue')

Would be equivalent to:
import * as app from './app.vue'


text:
Q: trouble implementing method from inherited class -ios I have looked through the other topics on this matter and I have not been able to determine my error.
I am very new to IOS programming.  I am trying to create a program that looks at the selected state of 2 buttons and determines whether the buttons selected state are the same.
I am currently trying to use a model to determine the buttons selected state and then pass the state to a label.  I have an error which says:

No visible @interface for 'MatchTest' declares the selector 'doesItMatch'

I'd appreciate any help that may be offered.
Thanks!
this is the MatchTest.h file
//  MatchTest.h
#import <Foundation/Foundation.h>

@interface MatchTest : NSObject
@end

this is the MatchTest.m file
//  MatchTest.m
#import "MatchTest.h"

@implementation MatchTest

-(NSString*)doesItMatch:(UIButton *)sender
{
    NSString* tempString;

    if(sender.isSelected)
    {
        tempString = @"selected";
    }
    else
    {
        tempString = @"not selected";
    }

    return tempString;
}
@end

this is the MatchViewController.h file
//  MatchViewController.h
#import <UIKit/UIKit.h>
#import "MatchTest.h"
@interface MatchViewController : UIViewController
@end

this is the MatchViewController.m file
//  MatchViewController.m
#import "MatchViewController.h"
@interface MatchViewController ()

@property (weak, nonatomic) IBOutlet UILabel *matchLabel;
@property (strong, nonatomic) MatchTest *match;

@end

@implementation MatchViewController

-(MatchTest *)match
{
    if(!_match) _match = [[MatchTest alloc] init];
    return _match;
}

- (IBAction)button:(UIButton *)sender
{
    sender.selected = !sender.isSelected;
    self.matchLabel.text = [self.match doesItMatch:sender];
}
@end

A: declare doesItMatch method in MatchTest.h file
like
in MatchTest.h
-(NSString*)doesItMatch:(UIButton *)sender;

compiler is not able to file doesItMatch method's declaration in .h file that's why that error is there.

A: You have not defined your method -(NSString*)doesItMatch:(UIButton *)sender in  MatchTest.h file.
You are importing MatchTest.h file in MatchViewController.h file so you need to define your methods or variables or property to make available this method.
Therefore according to your error log viewController wasn't able to find the interface where this method is declared.


text:
Q: Esper - handle out of order events I want to monitor if an event does NOT arrive within 10 minutes of arrival of event with the same id.
This is the EPL I am currently using:

SELECT * FROM pattern[ every s=Order_Status(status="placed") -> (timer:interval(600 sec) and not e=Order_Status(status="delivered", id=s.id))]

Usually placed event arrives before delivered, but sometime because of some lag in our systems, delivered event happens to come before placed for some id.
Cases

*

*time: 8:00 event: Order_Status{id=167, status="placed"}
time: 8:07 event: Order_Status{id=167, status="delivered"}

< No alert > (delivered within 10 minutes)

*time: 8:00 event: Order_Status{id=189, status="placed"}
time: 8:17 event: Order_Status{id=189, status="delivered"}

< Alert> (delivered after 10 minutes)

*time: 8:00 event: Order_Status{id=2637, status="delivered"}
time: 8:08 event: Order_Status{id=2637, status="placed"}

< Alert > (but shouldn't alert, the problem is delivered event for this id has arrived before placed)

As stated, I would get a false alert as the EPL pattern starts the window after the placed event and waits for  delivered event which has already arrived.
How do I handle this scenario of out of order events ?
Note:
(Basically I want to check for every id if the time difference between placed and delivered is above a certain threshold.
I also have the timestamp fields inside each event)

A: You have a "not" in your pattern that is used to detect the absence of events. Your requirement doesn't search for absence so the "not" isn't right.
There is a requirement questions as well. You don't state what happens when there are many A events and just one B event. Are there many matches or just the match for the last A event or the first A event or something else?
Sample pattern:
pattern [A -> (timer:interval(10 minutes) and B)]

Or this is a join that would seem to match what you want:
select * from B unidirectional, A#window(10 minutes)#lastevent

The "A#window(10 minutes)#lastevent" keeps the last event for up to 10 minutes.


text:
Q: Rewrite url via htaccess on apache server I have a url which is
www.domain.com/index.php?route=ticketsystem/generatetickets
I want people who type in the url www.domain.com/contact to be redirected to the page index.php?route=ticketsystem/generatetickets  however have the url bar still show /contact is that possible via htaccess and if so how? I tried the below
RewriteEngine On
RewriteBase /
RewriteRule contact /index.php?route=ticketsystem/generatetickets [L,QSA]

A: For your shown attempts, please try following .htaccess rules file. Make sure your index.php and .htaccess files are present in same directory/folder. Also better to use & rather than using / for query string.
Make sure to clear your browser cache before testing your URLs.
RewriteEngine ON
RewriteRule ^contact/?$ index.php?route=ticketsystem&generatetickets [QSA,NC,L]


text:
Q: Uncaught TypeError: Object [object Object] has no method 'highcharts' while loading highstock chart Facing problem while loading high stock chart, getting Uncaught TypeError: Object [object Object] has no method 'highcharts' error
$(divId).highcharts('StockChart', {

        rangeSelector: {
                enabled: true,
            buttonTheme:
                      {
                        width:50,
                        height:20
                      },
            inputEnabled : false
            },
        exporting: {
                enabled: false
            },
        navigator: {
                enabled: false
            },
        scrollbar: {
                enabled: false
            },

        chart : {
            events: {
                  click: function(event) {
                }
            },
          pinchType : 'none',
           zoomType : 'none'
       },
      title : {
        text : 'AAPL Stock Price'
      },

      series : [{
        name : 'AAPL Stock Price',
        data : data,
        type : 'area',
        threshold : null,

        enableMouseTracking: false,
        fillColor : {
          linearGradient : {
            x1: 0,
            y1: 0,
            x2: 0,
            y2: 1
          },
          stops : [[0, Highcharts.getOptions().colors[0]], [1, 'rgba(0,0,0,0)']]
        }
      }]
    });
  });

I have imported the libraries
first jquery then highstock and then exporting
Thanks in advance

A: Use your code after DOM is loaded, like in this example: http://jsfiddle.net/bu9V8/
$(function () { // call code below, after document is loaded
  $("#container").highcharts('StockChart', {
    series: [{
      data: [5, 10]
    }]
  });
});

A: Try to do it this way:
<script src="http://code.jquery.com/jquery-1.9.0.js"></script>
<script src="http://code.highcharts.com/highcharts.js"></script>
<script src="http://code.highcharts.com/modules/exporting.js"></script>

jQuery-1.9.0.js library.


text:
Q: AngularJS: count number of redirect in iframe? How can i count number of times the iframe has redirect with AngularJS?
I do so far with this code, but no luck.
I found if using JQuery can done like this.
Any help would be greatly appreciated!

A: Finally i get the answer, this the code:
.run(function($ionicPlatform, $window) {
  $ionicPlatform.ready(function() {
    var i = 0;
    $window.iframeLoaded = function () {
        console.log('value of i: '+i);
        if(i === 1) {
            // something todo
        }
        i++;
    };
  });
})

Html:
<iframe  ng-src="{{frameUrl}}" onLoad="iframeLoaded()">
    Something was wrong!.
</iframe>


text:
Q: What is the fastest way to modify a large string in Ruby? I need to modify a string in ruby. Specifically I'm trying to remove 'holes' from a WKT string.  Holes are defined as any single set of parenthesis after the first one with numbers within.  For example in this string...
POLYGON ((1 2, 3 4), (5 6, 7 8))
I would need to remove , (5 6, 7 8) because this parenthesis data is a hole, and the comma and the space don't belong except to separate sets of parentheses.
I am avoiding ruby methods like match or scan to try to optimize for speed and achieve O(n) speed.
Here's what I have so far.
def remove_holes_from(wkt)
    output_string = ""
    last_3_chars  = [ nil, nil, nil ]
    number_chars  = [ '0', '1', '2', '3', '4', '5', '6', '7', '8', '9' ]

    should_delete_chars = false

    wkt.each_char do |char|
      last_3_chars.shift
      last_3_chars.push(char)
      if should_delete_chars == false
        if number_chars.include?(last_3_chars[0]) && last_3_chars[1] == ")" && last_3_chars[2] == ","
          should_delete_chars = true
          next
        else
          output_string += char
        end
      end

      if should_delete_chars == true
        if number_chars.include?(last_3_chars[0]) && last_3_chars[1] == ")" && last_3_chars[2] == ")"
          should_delete_chars = false
          output_string += char
        else
          next
        end
      end
    end
    output_string
  end

The problem I am facing is that for a large polygon, like the United States (over 500,000 characters and over 40,000 points) it takes me 66 seconds to complete this.  You can find the string here:  https://gist.github.com/cheeseandpepper/9da5ca6ade921da2b4ab
Can anyone think of optimizations to this example I can use? Or maybe a separate approach? Thanks.

A: Whelp... regex wins!
wkt.gsub(/, \(-?\d.*?\)/, "")
took me 0.003742 seconds
As for the regex
, Literal comma
 Literal space
\( Literal open parenthesis
-? Optional negative sign
\d Any digit (because the previous is optional, we need to make sure we have a digit vs another open parenthesis)
.* Any number of any characters (will be digits, a comma and maybe a negative sign)
?\) Up to and including a literal close parenthesis


text:
Q: Where the scaling property $\int_{-\infty}^\infty f(ax)dx=\frac1a \int_{-\infty}^\infty f(x)dx$ comes from in the theory of distributions? Where the scaling property $\int_{-\infty}^\infty f(ax)dx=\frac1a \int_{-\infty}^\infty f(x)dx$ comes from in the theory of distributions?
Basically, if the distributions are defined as linear maps $f:\psi \in {\mathcal {D}}(\mathbb {R} )\to\int_{-\infty}^\infty f(x)\psi(x)dx\in\mathbb{R}$, where the scaling property comes from? Or it is a separate postulate?

A: So first, rigorously speaking, integrals are not defined for distributions. A distribution $\boldsymbol f$ (over $\Bbb R$) is indeed a linear form that to any $\varphi\in\mathcal D(\Bbb R)$ associates a value $\langle \boldsymbol f,\varphi\rangle\in\Bbb R$ (that is sometimes also denoted $\boldsymbol f[\varphi]$).

*

*Now, to make these linear forms behave as a generalization of functions, one associates to any function $f$ a distribution $\boldsymbol f$ defined by
$$
\langle \boldsymbol f,\varphi\rangle := \int_{\Bbb R} f(x)\,\varphi(x)\,\mathrm d x.
$$
Here I put a bold font to distinguish the function and the distribution, but in general one uses the same notation, and considers functions as a particular case of distributions (a bit as rational numbers are a particular case of real numbers, but they are formally usually initially build differently).

*But there are others distributions such as $\delta_0$ that are not functions, and for example its distributional derivative acts as $\langle\delta_0',\varphi\rangle = -\varphi'(0)$ which is not an integral. However, because of the fact that brackets denote the integral in the case of functions, we can think of them as being the analogue of the integral for other distributions.
Now that objects are more clear, you see that in principle, if $\boldsymbol f$ is a distribution, there is no meaning yet to $\boldsymbol f(ax)$ (and even no meaning either to $\boldsymbol f(x)$). Let me define $\tau_a$ the operation $\tau_a f(x) = f(ax)$. If we want to use the analogue of a change of variable formula for distributions, we should indeed define what it means first. To be consistent with the change of variable formula in integrals, it is defined by
$$\label{1}\tag{1}
\langle \tau_a\boldsymbol f,\varphi\rangle := \frac{1}{|a|}\langle \boldsymbol f,\tau_{1/a}\varphi\rangle,
$$
so that indeed, when $f$ is a function, this is consistent with the formula
$$
\int_{\Bbb R} f(ax)\,\varphi(x)\,\mathrm d x = \frac{1}{|a|}\int_{\Bbb R} f(x)\,\varphi(x/a)\,\mathrm d x.
$$
In the particular case when $\boldsymbol f$ is a compactly supported distribution, then one can take $\varphi = 1$ and define the analogue of the integral of $f$ by
$$
\int_{\Bbb R} \boldsymbol f := \langle \boldsymbol f,1\rangle,
$$
and your formula follows taking $\varphi = 1$ and $a>0$ in \eqref{1}, giving
$$
\int_{\Bbb R} \tau_a\boldsymbol f = \frac{1}{a} \int_{\Bbb R} \boldsymbol f
$$
since $\tau_{1/a}1 = 1$.


text:
Q: shorten querystring for searching and many filters i am building a search function which use many filters. i decide to use the get method instead of post (different reasons). Problem is, when using many filters the querystring gets very long, especially when i use filter with same name so i get
myurl.com?filter1[]=val1&filter1[]=val2&filter2=val

To get better control and to prevent 0 values i tried serializeArray:
var array = {};
jQuery.each(jQuery('form').serializeArray(), function(index,val) {
if (val.value != 0 )
    array[value.name] = val.value;
});

But this way it overrides the first filter1 with the last value of filter1, so multiple values doesn´t work. And then i have the "problem" to create the querystring. I am not a javascript prof. so i need a little help here.
What can i do, so i get a querystring which looks like:
myurl.com?filter1=val1|val2&filter2=val and so on

The HTML are "normal" input fields
<input type="checkbox" name="filter1[]" />
<input type="text" name="filter2" />

Thank you in advance
ruven

A: How about this (working demo):
<form action="search.html">
    <input type="text" value="val1" name="filter1" />
    <input type="text" value="val2" name="filter1" />
    <input type="text" value="val" name="filter2" />
    <input type="submit" value="search" name="cmdSearch" />
</form>

<script>
    // don't do anything until document is ready
    $(function() {

        // register to form submit event
        $('form').submit(function(e){

            // stop the form from doing its default action (submit-GET)
            e.preventDefault();

            // initialise url
            var url = '';

            // keep track of previously enumerated field
            var prev = '';

            // iterate all fields in the form except the submit button(s)
            $('input:not([type="submit"])', $(this)).each(function(){

                // get the name of this field, with null coalesce
                var name = $(this).attr('name') || '';

                // get the value of this field
                var val = $(this).attr('value');

                // does this field have the same name as the previous?
                if (name.toLowerCase() == prev.toLowerCase()) {

                    // same name therefore we have already appended the name
                    // append value separator
                    url += '|';
                }
                else {

                    // different name, track new name
                    prev = name;

                    // append parameter separator, parameter name, equals char
                    url += '&' + name + '=';
                }

                // append value of this field
                url += val;
            });

            // removing leading ampersand
            if (url.length && [0] == '&') {
                url = url.substring(1);
            }

            // insert leading question mark
            url = '?' + url;

            // insert url from "action" attribute of the form
            url = $(this).attr('action') + url;

            // display url (delete this line)
            alert(url);

            // redirect to the new url (simulates the GET)
            window.location.href = url;
        });
    });
</script>


text:
Q: How to reliably strip invisible characters that break code? I am trying to build a bookmarklet and got slammed with this issue which I was just able to figure out: a \u8203 character, which Chrome unhelpfully tells me in my block of code (upon pasting into the JS console) is an `"Invalid character ILLEGAL".
Luckily Safari was the one that told me it was a \u8203.
I am editing the code in the Sublime Text 2 editor and somehow copying in and out of it (I also tried TextEdit) fails to remove it.
Is there some sort of website somewhere that will strip all characters other than ASCII?
When I try to save as ISO 8859 but it will save it back as UTF-8 "because of unsupported characters".
... Yeah. that's the point. Get rid of my unsupported evil characters.
What am I supposed to do? Edit my file in a hex editor?
FYI I actually solved it by re-typing the code (which originated from this site by the way).

A: you can use regex to filter everything out of 0-127. For example in javascript:
text.replace(/[^\x00-\x7F]/g, "")

x00 = 0, x7f = 127

A: Well, the easiest way I can think of is to use sed
sed -i 's/[^[:print:]]//g' your_script.js
//            ^^^^^ this can also be 'ascii'

or using tr
tr -cd '\11\12\15\40-\176' < old_script.js > new_script.js

A:
Is there some sort of website somewhere that will strip all characters
  other than ASCII?

You could use this website
You can recreate the website using this code:
<!DOCTYPE html>
<html>

    <head>
        <meta http-equiv="content-type" content="text/html; charset=UTF-8">
        <title>- jsFiddle demo</title>
        <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
        <link rel="stylesheet" type="text/css" href="/css/normalize.css">
        <link rel="stylesheet" type="text/css" href="/css/result-light.css">
        <style type="text/css">
            textarea {
                width: 800px;
                height: 480px;
                outline: none;
                font-family: Monaco, Consolas, monospace;
                border: 0;
                padding: 15px;
                color: hsl(0, 0%, 27%);
                background-color: #F6F6F6;
            }
        </style>
        <script type="text/javascript">
            //<![CDATA[
            $(function () {
                $("button").click(function () {
                    $("textarea").val(
                             $("textarea").val().replace(/[^\u0000-\u007E]/g, "")
                    );
                    $("textarea").focus()[0].select();
                });
            }); //]]>
        </script>
    </head>

    <body>
        <textarea></textarea>
        <button>Remove</button>
    </body>

</html>

A: Nontechnical solution: paste your text into a new email message in Gmail and click Tx (clear formatting, in the formatting menu). Worked for me.


text:
Q: I'm not sure if my foreign key is working I've made a system where employees can send feedbacks.
Feedback form:

Now I have two tables in my database, tbl_feedback and employee:
tbl_feedback:

employee:

The employee_id in my tbl_feedback is a foreign key that references id in employee table.
My question is, is it really necessary to put Employee ID on my form for it to work? Because I noticed that when I remove Employee ID on the form, I get an error. Does that also mean I didn't set the employee_id column to a foreign key? properly?
Here's my insert feedback php code:

<?php
require_once ('database.php');

if (isset($_POST['send'])) {

$employee_id = $_POST['employee_id'];
$full_name = $_POST['full_name'];
$email = $_POST['email'];
$website = ($_POST['website']);
$message = ($_POST['message']);

{
$database->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$insert_query = "INSERT INTO tbl_feedback (employee_id, full_name, email, website, message)
VALUES (?, ?, ?, ?, ?)";

$insert = $database->prepare($insert_query);
$insert->execute(array($employee_id, $full_name, $email, $website, $message));

echo "<script>alert('Successfully sent!'); window.location='feedback.php'</script>";
}
}
?>

Here's how I created tbl_feedback:

CREATE TABLE tbl_feedback (
  id int NOT NULL AUTO_INCREMENT,
  employee_id int NOT NULL,
  full_name varchar(100) NOT NULL,
  email varchar(100) NOT NULL,
  website varchar(100) NOT NULL,
  message varchar(100) NOT NULL,
  PRIMARY KEY (id),
  FOREIGN KEY (employee_id) REFERENCES employee(id)
 );

A: If you remove the employee information from your feedback form, without getting the information from another source, you will defineately have a problem.
The foreign key constraint you added to your tables just makes sure, that there is not feedback entry in your table, that has no corresponding employee to map it with.
This means, that it does not magically maps the two tables with each other and makes sure that each feedback has a linked employee, but rather throws an error for each feedback entry that can not be linked to an employee, based on the given id. The errors you encountered are therefore actually proof, that your foreign key constraint works correctly.
So eventhough you have a foreign key constraint, you still have to manage the mapping in your code.

A: If there is a Foreign Key in Table then table needs the key to be passed when inserting the data. It doesn't matter if you are passing via Form or getting your employee id from the database via PHP code.


text:
Q: Visual Paradigm add two foreign key in a single table reference to single primary key? Here we have many to many relationship between tour and places .
So Visual paradigm automatically add the bridge table but i want to keep Place Column two time as a foreign key in Tour_place table,
Place_start (fk)
Place_destination (fk)  both referencing to the same column place for Place table.
I can easily create a table in  oracle sql with both of them as foreign key but i also need to show both as a foreign key in ERD.

A: Just add a another relationship association line
, now both Place_start and Place_destination reference the Pk places from Places table.


text:
Q: pass EditText to a string          EditText hi = (EditText) findViewById(R.id.editText1);
         String hi2 = hi.toString();

         editor.putString("user_email", hi2);
     editor.commit();

The code above in my on click works and compiles fine but the value i get when i go into my settings is
androd.widget.EditText@414e4e70

Does anyone know the correct syntax for me to pass a value from a user input box into a my pref.
if i use
editor.putString("user_email","helloworld@google.com");

then it works because its a full string.

A:          EditText hi = (EditText) findViewById(R.id.editText1);
         String hi2 = hi.getEditableText().toString();

         editor.putString("user_email", hi2);   //put into the email settings the value from the user input
         editor.commit();

I missed the getEditableText()
Late night coding :(


text:
Q: when does the Minkowski inequality for infinity norm become equality I have two vectors $x, y \in \mathbb{R}^d$, it is well known as Minkowski inequality that:
$|x+y|_\infty \leq |x|_\infty + |y|_\infty$,
where $|x|_\infty= \underset{i=1..d}{\max} |x_i|$ with $x = \left[x_1 \dots x_d\right]^T$.
Could anyone kindly tell me when this inequality becomes equality?
I see at least that the equality happens if $x = \lambda y$ with $\lambda \geq 0$, but i have not found any other case (i.e. $x = Ay$ with $A \in \mathbb{R}^{d \times d}$?) after some hours looking for on the internet.
Thank you for your time!


text:
Q: What is wrong with my setup of flutter geolocator: ^6.1.7? BTW-  Things work as anticipated on IOS.
The trouble I'm having is running on Android (Nexus 5 API 30)
I have carefully followed the instructions for setup paying special attention to the
gradle.properties and "android/app/build.gradle"  The AndroidManifest.xml  was also updated to include the
uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION
uses-permission android:name="android.permission.ACCESS_BACKGROUND_LOCATION

when the app starts, there is prompting asking to allow location services.

I can even check that the location services on the app are indeed enabled-
Here is the code that calls geolocation...
import 'package:flutter/material.dart';
import 'package:geolocator/geolocator.dart';

class LoadingScreen extends StatefulWidget {
  @override
  _LoadingScreenState createState() => _LoadingScreenState();
}

class _LoadingScreenState extends State<LoadingScreen> {

  void initState() {
    super.initState();
    getLocation();
  }
  void getLocation() async {
    Position position = await Geolocator.getCurrentPosition(desiredAccuracy: LocationAccuracy.low);
    print(position);
  }
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Center(
        child: RaisedButton(
          onPressed: () {
            getLocation();
          },
          child: Text('Get Location'),
        ),
      ),
    );
  }
}

When I run the code there is a very long list of exceptions the first few are:
E/flutter (21698): [ERROR:flutter/lib/ui/ui_dart_state.cc(177)] Unhandled Exception: The location service on the device is disabled.
E/flutter (21698): #0      MethodChannelGeolocator._handlePlatformException (package:geolocator_platform_interface/src/implementations/method_channel_geolocator.dart:192:9)
E/flutter (21698): #1      MethodChannelGeolocator.getCurrentPosition (package:geolocator_platform_interface/src/implementations/method_channel_geolocator.dart:121:7)
E/flutter (21698): <asynchronous suspension>
E/flutter (21698): #2      Geolocator.getCurrentPosition (package:geolocator/geolocator.dart:258:35)

A: try{
 await getLocation();
} catch(e,s){
 //handle errors
}

and some of the Android emulators has this exact problem (bug), try a different emulator, or device

A: initialize variable
Position _currentPosition;

code
_getCurrentLocation() async{
 await Geolocator.getCurrentPosition(desiredAccuracy: LocationAccuracy.best)
        .then((Position position) {
      setState(() {
        _currentPosition = position;
        print(_currentPosition);

      });

    }).catchError((e) {
      print(e);
    });
  }

Run flutter clean uninstall the app from phone/emulator and restart the phone/emulator
then run the app again after accepting permission it will ask for enable location dialog automatically,if the problem occurs try with location package

A: Adding forceAndroidLocationManager:true made it work for me.
position = await Geolocator.getCurrentPosition(
              desiredAccuracy: LocationAccuracy.medium,
              forceAndroidLocationManager: true)
          .timeout(Duration(seconds: 10));


text:
Q: Deleting an item from the shopping cart I'm trying to delete a object from expandable list view. This code is in my adapter class.
                deleteIB.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {

                        ShoppingCartEntry catalog = ShoppingCartHelper.getByProduct(cat);
                        Product selectedProduct = catalog.getProduct();
                        selectedProduct  = null;
                        _cartList.remove(groupPosition);
                        ProductAdapter.this.notifyDataSetChanged();
                    }
                });

When I does this it will remove the item from the listview, but once open the cart activity again, I can find the added item in the cart. why is it behaving like that? Do I need to implement anything in my activity class.
ShoppingCartHelper
public static final String PRODUCT_INDEX = "PRODUCT_INDEX";
    private static Map<Product, ShoppingCartEntry> cartMap = new HashMap<Product, ShoppingCartEntry>();

    public static void setQuantity(Product product, int quantity) {
        // Get the current cart entry
        ShoppingCartEntry curEntry = cartMap.get(product);

        // If the quantity is zero or less, remove the products
        if (quantity <= 0) {
            if (curEntry != null)
                removeProduct(product);
            return;
        }

        // If a current cart entry doesn't exist, create one
        if (curEntry == null) {
            curEntry = new ShoppingCartEntry(product, quantity);
            cartMap.put(product, curEntry);
            return;
        }

        // Update the quantity
        curEntry.setQuantity(quantity);
    }

    public static int getProductQuantity(Product product) {
        // Get the current cart entry
        ShoppingCartEntry curEntry = cartMap.get(product);

        if (curEntry != null)
            return curEntry.getQuantity();

        return 0;
    }

    public static void removeProduct(Product product) {
        cartMap.remove(product);
    }

    public static List<Product> getCartList() {
        List<Product> cartList = new Vector<Product>(cartMap.keySet().size());
        for (Product p : cartMap.keySet()) {
            cartList.add(p);
        }

        return cartList;
    }

    public static ShoppingCartEntry getByProduct(Product product) {
        return cartMap.get(product);
    }
}

ShoppingCartEntry
private Product mProduct;
    private int mQuantity;

    public ShoppingCartEntry(Product product, int quantity) {
        mProduct = product;
        mQuantity = quantity;
    }

    public Product getProduct() {
        return mProduct;
    }

    public int getQuantity() {
        return mQuantity;
    }

    public void setQuantity(int quantity) {
        mQuantity = quantity;
    }

}

A: catalog.getProduct() returns the product you want (or the first, whatever your imlpementation is) and assigns a copy of that value to your variable selectedProduct. By giving it a null value, you nullify the copy of the product.
You should call catalog.removeProduct or something similar. Consider using the ProductAdapter to remove the product. The catalog will be updated automatically.

A: the reason why the item is being added back to the cart is because you never called the method that will remove your product from the shopping cart. the only method you called was to remove the item from the listview. I see that you have ShoppingCartHelper.removeProduct(selectedProduct) method. You should call that too.
deleteIB.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {

                    ShoppingCartEntry catalog = ShoppingCartHelper.getByProduct(cat);
                    Product selectedProduct = catalog.getProduct();
                    ShoppingCartHelper.removeProduct(selectedProduct);
                    selectedProduct  = null;
                    _cartList.remove(groupPosition);
                    ProductAdapter.this.notifyDataSetChanged();
                }
            });


text:
Q: How do I open a (Mercurial) patch file in a human-readable format (preferably with kdiff3)? The Mercurial command
hg diff > mypatchfile

compiles a "patch" file representing the differences between the working directory and the last commit. Opening this file as plain text results in a presentation of the changes that is quite difficult to read. I want to open this file in a diff tool for a clearer presentation of the differences.
I know that the diff tool kompare can do exactly this, using the command
kompare mypatchfile

But while its presentation is certainly more readable than the plain text format, I find it lacking.
I much prefer kdiff3. Can this tool open patch files? The command
kdiff3 mypatchfile

doesn't work. Instead, the patch file is just opened in plain-text format in the left panel, while the right panel is empty. But it seems that kdiff3 should be able to open patch files, because I can just write
hg extdiff -p kdiff3

and get exactly the presentation I want. However, I don't see how I can get similar results with a previously exported patch file. Any suggestions?
(I would also appreciate recommendations for other diff tools that can open and display patch files in a readable format.)

A: *

*You can't do it easy (but can try to do it with some tricks for some patches)

*hg extdiff -p kdiff3 does NOT visualize custom patch, but (read carefully Extdiff extension wiki) only show in dual-window mode difference between two revisions (see difference in terms) - Working Dir and parent in simplest case (and sources for diffing are full files from relevant revisions)

A: I think you are just tying to visualize diff output, right ? There's a tool xxdiff that might be useful with few caveats. extdiff is an external diff, that is instead of using Mercurial diff, another program is used to do the diff of two revisions. You can even use linux diff command as an extdiff for Mercurial.


text:
Q: Solving the recurrence relation with repeated roots (2 in $a_g$ and same root in $a_p$) $$a_{n+2} - 6a_{n+1} + 9a_n = 3^n$$
Solving for this recurrence can be done by the following:
1) solve for the recurrence relation $a_g$ such that: $a_{n+2} - 6a_{n+1} + 9a_n = 0$
then,
2) $a_h$ such that: $a_{n+2} - 6a_{n+1} + 9a_n = 3^n$
then,
3) $a_n = a_g + a_p$
Solving for the $a_g$ I have the solution: $C_1(3)^n + C_2n(3)^n$, where the extra $n$ is due to the repeated root.
Now, solving for $a_p$ I use the trial solution $a_n = A(3^n)\cdot(n^2)$, where $n^2$ is due to the third root.
This is the part I'm having trouble with now: when i substitute for $a_{n+2}$ is it $A\cdot3^{n+2}\cdot(n+2)^2$ and then similarly I would substitute for $6a_{n+1}$ which should be $6A\cdot3^{n+1}\cdot(n+1)^2$ and $9a_n$ should be $9A\cdot 3^n \cdot n^2$
Then, I need to solve:
$$(A\cdot3^{n+2}\cdot(n+2)^2) - (6A\cdot 3^{n+1} \cdot (n+1)^2) + (9A\cdot 3^n \cdot n^2) = 3^n$$
Would this be the correct approach to solve for $a_p$?

A: Writing, as you did,
$$(A\cdot3^{n+2}\cdot(n+2)^2) - (6A\cdot 3^{n+1} \cdot (n+1)^2) + (9A\cdot 3^n \cdot n^2) = 3^n$$ Expanding the lhs, you should end with $$2 A\, 3^{n+2}=3^n\implies 18 A=1\implies A=\frac 1 {18}$$ But, as said in comments, there is a faster way to solve the problem.


text:
Q: AngularJS: Config $routeProvider after $http request I need to config $routeProvider after ajax request, but i can not using $http in config, means following code causes error:
module.config(['$routeProvider','$http',function ($routeProvider,$http) {}

and $routeProvider can not accessed in controller!
I need this approach for considering who can see what page as index page.

A: You can pass $routeProvider from config object to your controller. For example
in your route config file you write:
 .when('/', {
                    templateUrl: 'template.html',
                    controller: 'MyController',
                    controllerAs: 'main',
                    resolve: {
                        myRouteConfig: function(){
                            return $routeProvider;
                        }
                    }
                })

and in controller you can inject it like a dependency
function MyController(myRouteConfig) {
   myRouteConfig.when ......
}

working example in fiddle


text:
Q: Custom rectangle goes wrong on lower android version than 5.0 I have created a custom xml like this:
<shape xmlns:android="http://schemas.android.com/apk/res/android">

    <stroke
        android:color="@color/colorAccent"
        android:width="2dp"/>

    <corners
        android:bottomLeftRadius="30dp"
        android:bottomRightRadius="30dp"
        android:topLeftRadius="30dp"
        android:topRightRadius="30dp" />
<size
    android:height="400dp"
    android:width="1000dp" />

This is an empty rectangle with rounded corners. It looks well in 5.0+ android versions but when I tested it on 4.1 the rectangle filled in with black color.
Have you any idea what cause this?

A: Just to copy my previous comment: There's a bug on older OS versions. You need to add a solid tag in your shape as well. I'm not sure if android:color/transparent will work on these older devices though...


text:
Q: Fixing macro for siunitx backwards compatibility I am encountering errors with my below code (contained in a loaded .sty file; packages appropriately loaded beforehand), which is part of my attempt to ensure siunitx3 compatibility for older code, while maintaining backwards compatibility for Version 2.
\expandafter\edef\csname SIUnitXUnitSepParamNameV2\endcsname{number-unit-product}
\expandafter\edef\csname SIUnitXUnitSepParamNameV3\endcsname{quantity-product}

\edef\SIUnitXUnitSepParamName{\csname SIUnitXUnitSepParamNameV3\endcsname}
%
\@ifpackagelater{siunitx}{2021/05/17} {  % main release of 3.0.0
    % already set, as default, above
}{
    \edef\SIUnitXUnitSepParamName{\csname SIUnitXUnitSepParamNameV2\endcsname}
}

I later attempt to use this, as follows:
\expandafter\expandafter\expandafter\DeclareSIUnit[\expandafter\SIUnitXUnitSepParamName = \;]\basepair{bp}

\expandafter\expandafter\expandafter\DeclareSIUnit[\expandafter\SIUnitXUnitSepParamName = \;]\kilobasepair{\kilo\basepair}

I realize that I have errors with my macro substitutions, but my attempts to solve it have been unsuccessful thus far. (I get various errors, amounting to saying that my SIUnitXUnitSepParamName definition is invalid, due to not properly expanding.)
Might someone be able to kindly point out my error(s), and ideally provide both a corrected version, and perhaps an improved version, using LaTeX 3 syntax? Feedback or improvements for these particular \SI definitions would also be most welcome.

A: The correct \expandaftery would be:
  \expandafter\DeclareSIUnit\expandafter[\SIUnitXUnitSepParamName = \;]\basepair{bp}
% 1           2             3           45

(remember, each \expandafter skips one token and expands the next, so above 1 skips 2 and expands 3, and 3 skips 4 and expands 5).
But instead if you're on version 2 you can define the key quantity-product to be an alias to the key number-unit-product:
\@ifpackagelater{siunitx}{2021/05/17}
  { }
  {
    \keys_define:nn { siunitx }
      { quantity-product .meta:n = { number-unit-product = {#1} } }
  }

then you can use quantity-product unconditionally.
Working example:
\documentclass{article}

\usepackage{siunitx}
\ExplSyntaxOn
\makeatletter
\@ifpackagelater{siunitx}{2021/05/17}
  { }
  {
    \keys_define:nn { siunitx }
      { quantity-product .meta:n = { number-unit-product = {#1} } }
  }
\ExplSyntaxOff

\DeclareSIUnit[quantity-product = x]\basepair{bp}
\DeclareSIUnit[quantity-product = x]\kilobasepair{\kilo\basepair}

\begin{document}

\ifdefined\qty
  \qty{10}{\basepair}
\else
  \SI{10}{\basepair}
\fi

\end{document}


text:
Q: Math.floor возвращяет NAn Есть код:
var lvl_user = '21,711';
lvl_user = Math.floor(lvl_user);
alert(lvl_user);

Возвращает NaN, что не так.
A: а не так то, что lvl_user - это строка
Вам нужно либо эту строку к числу.
Конкретно в вашем случае этот код даст нужный эффект:
var lvl_user = '21,711';
lvl_user = parseInt(lvl_user);
alert(lvl_user);

либо, если необходимо по какой-либо причине именно Math.floor использовать, строку привести к числу можно так:
lvl_user = parseFloat(lvl_user.replace(',','.'))

A: Разделителем целого числа, должна быть не запятая, а точка
var lvl_user = "21.711";
lvl_user = Math.floor(lvl_user);
alert(lvl_user);

...и цифровые значения можно задавать без кавычек


text:
Q: Variable assigned to instance of jQuery plugin returns 'undefined' I was looking for a way to create a countdown timer plugin for a project I'm working on, and did so using the template found here:
http://stefangabos.ro/jquery/jquery-plugin-boilerplate-oop/.
My plugin works as it should, and I assign it to a variable like:
var timer1 = new $.timer({
    option1: true,
    callback1: function(){
        //do something
    }
});

but when I later on go to check the value of that variable, it returns undefined rather than an object, as I would expect. I can use this same variable, however, to access the public methods of my timer:
timer1.set(10);

and it will set the timer.
But trying to return the object within the variable 'timer1' returns undefined instead.
Here is the basis of the code (unfortunately my employer restricts me from posting it as it is - I have had to cut out the actual method code):
;
(function($) {

    $.timer = $.timer || {};
    $.timer = function(options) {
        var defaults = {
            option1: false,
            option2: false,
            callback1: function() {
            }
        };
        var plugin = this;
        plugin.settings = {};

        //local variables

        var sampleVar = 0;

        //constructor

        var init = function() {
            plugin.settings = $.extend({}, defaults, options);
            return plugin;
        };

        //private methods

        var fire = function() {
            //do something here
            plugin.settings.callback1.call(plugin);
        };

        var updateTimer = function() {
            //do something here
        };

        var reset = function() {
            //do something here
        };

        //public methods

        plugin.set = function(time) {
            //do something here
        };

        plugin.start = function() {
            //do something here
        };

        init();
    };
})(jQuery);


text:
Q: Insert new row unless ONE of the values matches another row? I'm trying to insert new rows into a MySQL table, but only if one of the values that I'm inserting isn't in a row that's already in the table.
For example, if I'm doing:
insert into `mytable` (`id`, `name`) values (10, `Fred`)

I want to be able to check to see if any other row in the table already has name = 'Fred'. How can this be done?
Thanks!
EDIT
What I tried (can't post the exact statement, but here's a representation):
INSERT IGNORE INTO mytable (`domain`, `id`)
VALUES ('i.imgur.com', '12gfa')
WHERE '12gfa' not in (
    select id from mytable
)

which throws the error:
#1064 - You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'WHERE '12gfa' not in ( select id from mytable)' at line 3

A: First of all, your id field should be an autoincrement, unless it's a foreign key (but I can't assume it from the code you inserted in your question).
In this way you can be sure to have a unique value for id for each row.
If it's not the case, you should create a primary key for the table that includes ALL the fields you don't want to duplicate and use the INSERT IGNORE command.
Here's a good read about what you're trying to achieve.

A: You could use something like this
INSERT INTO someTable (someField, someOtherField)
VALUES ("someData", "someOtherData")
ON DUPLICATE KEY UPDATE someOtherField=VALUES("betterData");

This will insert a new row, unless a row already exists with a duplicate key, it will update it.

A: DELIMITER |
CREATE PROCEDURE tbl_update (IN id INT, IN nm VARCHAR(15))
BEGIN
DECLARE exst INT;
SELECT count(name) INTO exst FROM mytable WHERE name = nm;
IF exst = 0 THEN
     INSERT INTO mytable VALUES(id, name);
END IF;
END
|
DELIMITER ;

or just make an attribute name as UNIQUE


text:
Q: How to use terminal to access iCloud Drive when Finder is not running I would like to access iCloud drive from Terminal in order to create an emergency backup. Unfortunately, my installation of Mac OS Yosemite is not operational, so I am using recovery mode to create my backup. In this mode, the Finder is not available and iCloud Drive is not running.
I am aware that normally, the iCloud drive directories are located at
~/Library/Mobile\ Documents/com~apple~CloudDocs. Unfortunately this directory does not appear when using Terminal in recovery mode (there appears to be no Mobile Documents in Library). This makes sense, because I am not logged in as any of the users (and I believe the recovery utility runs on its own partition).
My questions are thus:

*

*Is there any way I can connect to and access iCloud drive directories from Terminal in Mac OS recovery mode (i.e. after booting up while holding down cmd + r) when iCloud Drive sync is not running (as Finder isn't running)?

*How can I copy all files in a given folder (including all subfolders) into an iCloud drive directory using a Terminal command?

Should it not be possible to log into iCloud drive using Terminal, Dropbox would be an alternative. I am not sure, however, whether I can install the Dropbox command line tool in recovery mode.

A: I think you're going the wrong way.

*

*Why are you trying to recover these files?

*Reinstall the OS from CMD + R and log in again.

*Now you can back up all your documents.

*The reinstall will not delete your files until you don't format the disk/s.

BTW. you could log in to iCloud via www.icloud.com and get your files from there.
Another solution could be:

*

*Download the latest Combo Update for your installed OS (for ex. https://support.apple.com/kb/DL1832?locale=de_DE)

*and turn the damaged OS into Target Disk Mode by holding the "T" key on startup.

*Now connect your damaged OS via Firewire or Thunderbolt (or even with a FW to TB converter/adapter)

*and run from your working Yosemite installation the Combo Update installer.

*Choose as destination the damaged OS from Target Disk Mode.

*In many cases, the Combo Update can fix some issues without having to reinstall the whole OS. But that's only a temporary solution.

*The issue should be resolved.

Btw. I don't understand why you're trying to recover the files from the disk when the files are already on iCloud. What's your intention? Perhaps we could help you better if we know what the intention is.
Best regards

A: This post is very old, but in case anyone stumbles on here looking for the answer (as I did) here's where you can find the iCloud Drive while in recovery mode:
/Volumes/Macintosh HD - Data/Users/[your username]/Library/Mobile Documents/com~apple~CloudDocs