text:
Q: Retrying celery failed tasks that are part of a chain I have a celery chain that runs some tasks. Each of the tasks can fail and be retried. Please see below for a quick example:
from celery import task

@task(ignore_result=True)
def add(x, y, fail=True):
    try:
        if fail:
            raise Exception('Ugly exception.')
        print '%d + %d = %d' % (x, y, x+y)
    except Exception as e:
        raise add.retry(args=(x, y, False), exc=e, countdown=10)

@task(ignore_result=True)
def mul(x, y):
    print '%d * %d = %d' % (x, y, x*y)

and the chain:
from celery.canvas import chain
chain(add.si(1, 2), mul.si(3, 4)).apply_async()

Running the two tasks (and assuming that nothing fails), your would get/see printed:
1 + 2 = 3
3 * 4 = 12

However, when the add task fails the first time and succeeds in subsequent retry calls, the rest of the tasks in the chain do not run, i.e. the add task fails, all other tasks in the chain are not run and after a few seconds, the add task runs again and succeeds and the rest of the tasks in the chain (in this case mul.si(3, 4)) does not run.
Does celery provide a way to continue failed chains from the task that failed, onwards? If not, what would be the best approach to accomplishing this and making sure that a chain's tasks run in the order specified and only after the previous task has executed successfully even if the task is retried a few times?
Note 1: The issue can be solved by doing
add.delay(1, 2).get()
mul.delay(3, 4).get()

but I am interested in understanding why chains do not work with failed tasks.

A: You've found a bug :)
Fixed in https://github.com/celery/celery/commit/b2b9d922fdaed5571cf685249bdc46f28acacde3
will be part of 3.0.4.

A: I'm also interested in understanding why chains do not work with failed tasks.
I dig some celery code and what I've found so far is:
The implementation happends at app.builtins.py
@shared_task
def add_chain_task(app):
    from celery.canvas import chord, group, maybe_subtask
    _app = app

    class Chain(app.Task):
        app = _app
        name = 'celery.chain'
        accept_magic_kwargs = False

        def prepare_steps(self, args, tasks):
            steps = deque(tasks)
            next_step = prev_task = prev_res = None
            tasks, results = [], []
            i = 0
            while steps:
                # First task get partial args from chain.
                task = maybe_subtask(steps.popleft())
                task = task.clone() if i else task.clone(args)
                i += 1
                tid = task.options.get('task_id')
                if tid is None:
                    tid = task.options['task_id'] = uuid()
                res = task.type.AsyncResult(tid)

                # automatically upgrade group(..) | s to chord(group, s)
                if isinstance(task, group):
                    try:
                        next_step = steps.popleft()
                    except IndexError:
                        next_step = None
                if next_step is not None:
                    task = chord(task, body=next_step, task_id=tid)
                if prev_task:
                    # link previous task to this task.
                    prev_task.link(task)
                    # set the results parent attribute.
                    res.parent = prev_res

                results.append(res)
                tasks.append(task)
                prev_task, prev_res = task, res

            return tasks, results

        def apply_async(self, args=(), kwargs={}, group_id=None, chord=None,
                task_id=None, **options):
            if self.app.conf.CELERY_ALWAYS_EAGER:
                return self.apply(args, kwargs, **options)
            options.pop('publisher', None)
            tasks, results = self.prepare_steps(args, kwargs['tasks'])
            result = results[-1]
            if group_id:
                tasks[-1].set(group_id=group_id)
            if chord:
                tasks[-1].set(chord=chord)
            if task_id:
                tasks[-1].set(task_id=task_id)
                result = tasks[-1].type.AsyncResult(task_id)
            tasks[0].apply_async()
            return result

        def apply(self, args=(), kwargs={}, **options):
            tasks = [maybe_subtask(task).clone() for task in kwargs['tasks']]
            res = prev = None
            for task in tasks:
                res = task.apply((prev.get(), ) if prev else ())
                res.parent, prev = prev, res
            return res
    return Chain

You can see that at the end prepare_steps prev_task is linked to the next task.
When the prev_task failed the next task is not called.
I'm testing with adding the link_error from prev task to the next:
if prev_task:
    # link and link_error previous task to this task.
    prev_task.link(task)
    prev_task.link_error(task)
    # set the results parent attribute.
    res.parent = prev_res

But then, the next task must take care of both cases (maybe, except when it's configured to be immutable, e.g. not accept more arguments).
I think chain can support that by allowing some syntax likes this:
c = chain(t1, (t2, t1e), (t3, t2e))
which means:
t1 link to t2 and link_error to t1e
t2 link to t3 and link_error to t2e


text:
Q: bash robustness: what is a correct and portable way to trap for the purpose of an "on exit" cleanup routine? When I create temporary files that I want removed when a script exits, I typically set a trap on EXIT. something like this:
function cleanup ()
{
   if [[ -d "$mytmp" ]]; then rm -rf --one-file-system -- "$mytmp" || :; fi
}

trap cleanup EXIT
...

I recently stumbled upon another script which sets things up slightly differently. It sets up a trap on EXIT, but also on actual signals, i.e.:
function cleanup () { : ... same as above ...; }
trap cleanup EXIT HUP INT QUIT TERM

I'm questioning whether the additional signals in the list are superfluous, or a strict improvement. Are there versions of bash that don't run the EXIT trap on certain signals?
In my experience, CTRL-C (SIGINT) a script will typically also invoke the EXIT trap, even without explicitly trapping on INT. Maybe I've always been lucky and it's just that a child gets killed by SIGINT first, and then the parent script exited with an error (because of set -e or another reason).
What's the best cleanup idiom, in terms of correctness and maybe portability?
Update:
This is tangential to my question, but one portability improvement, pointed out in the comments, is to define functions using the short form: cleanup () { :; } rather than function cleanup () { :; }. Thanks!

A: I've tested this quite recently on an old bash version (3.2, the one on MacOS from 2007...) and even there it's superfluous.
One could, however, argue that it's there for readability, to signal the reader: "there's no special behavior for any of the signals, just clean up and exit.", because if you have two trap statements referring to the same signal, the one which executed last will override.

redpajama_set_name: RedPajamaStackExchange


text:
Q: KeyPath with operators and NSArray I have a class Person defined as
@interface Person : NSObject {
    NSString *name;
    int age;
    NSArray *workedHours;
}

@property (nonatomic,retain) NSArray *workedHours;

-(int)age;
-(void)setAge:(int)val;
-(NSString*)name;
-(void)setName:(NSString*)val;
@end

I'd like to bind the workedHours sum to a label...
-(void) awakeFromNib{
    [label bind:@"value" toObject:person withKeyPath:@"@sum.workedHours" options:nil];
}

And i obtain this error:
this class is not key value coding-compliant for the key @sum.
label is an IBOutlet and person a property of my NSWindowController.
If i try to change the keyPath with "@name" it works correctly.
What is wrong ? Can i maybe use @sum, @count, @avg etc only with NSArrayController ?

A: The problem here is that the workedHours array is not a collection of objects that is KVC compliant.
If, for example, you used a daily work record of the form:
@interface DailyWork : NSObject {
   NSDate *day;
   int hours;
}
@property(retain) NSDate *day;
@property int hoursWorked;
@end

Then, this should work, since the collection operator expects to perform an operation on a field of the objects that are being collected.    So, if you stuck DailyWork* values in your NSArray, for example: @"workedHours.@hours" would give you the total of all hours worked in each of the objects in workedHours (the array of DailyWork*).


text:
Q: R showing error - "Building a Basic Calculator" add <- function(x, y) {
  return(x + y)
}
subtract <- function(x, y) {
  return(x - y)
}
multiply <- function(x, y) {
  return(x * y)
}
divide <- function(x, y) {
  return(x / y)
}

factors <- function(x) {
  if (choice == 5 | choice == 6) {
    choice <- readline(prompt = "Enter the number: ")
  }

  else {
    num1 = as.integer(readline(prompt = "Enter first number: "))
    num2 = as.integer(readline(prompt = "Enter second number: "))
  }
}

# take input from the user
print("Select operation.")
print("1.Add")
print("2.Subtract")
print("3.Multiply")
print("4.Divide")
print("5. Factors")
print("6. Prime")

choice = as.integer(readline(prompt="Enter choice[1/2/3/4/5/6]: "))
num1 = as.integer(readline(prompt="Enter first number: "))
num2 = as.integer(readline(prompt="Enter second number: "))
operator <- switch(choice,"+","-","*","/")
result <- switch(choice, add(num1, num2), subtract(num1, num2), multiply(num1, num2), divide(num1, num2), factor(i)
print(paste(num1, operator, num2, "=", result))

ERROR IN R CONSOLE -

> choice = as.integer(readline(prompt="Enter choice[1/2/3/45/6]: "))
Enter choice[1/2/3/45/6]: num1 = as.integer(readline(prompt="Enter first number: "))
Warning message:
NAs introduced by coercion
> num2 = as.integer(readline(prompt="Enter second number: "))
Enter second number: operator <- switch(choice,"+","-","*","/")
Warning message:
NAs introduced by coercion
> result <- switch(choice, add(num1, num2), subtract(num1, num2), multiply(num1, num2), divide(num1, num2))
> print(paste(num1, operator, num2, "=", result))
Error in paste(num1, operator, num2, "=", result) :
  object 'num1' not found

This is the error thats generated by R.It appears that R is not able to run through the integers as per my commands. I cannot understand whats wrong with it. I have made few changed but even then the errors appear to be the same. When i run the code until the inputs taken from the user it runs quite fine but the inputs are not recognizing num1 and num2 it says -
"Warning message:
NAs introduced by coercion"
I do not understand since I'm a beginner. Please help me out.
Thank you


text:
Q: How to download webpage with all related content using phantomjs I want to download an entire webpage along with content (including the css, javascripts, images, external resources) that may be required to render the webpage in any browser using PhantomJS. I do not want to execute scripts but simply parse the css and javascripts for more links to contents and download them too.
I tried using tools like wget (does exactly what I need but is very slow because it uses a single tcp connection to the webserver) and httrack (downloads entire websites, in my case I want to download only contents which are required to render the page by recursively parsing links in files). I am currently trying to use phantomjs for the purpose but could not find the right way to use it.
Any help/pointer is highly appreciated.

A: Try to use this code:
var page = require('webpage').create();

var url = "your url goes here";
var fs = require('fs');
var path = 'index.html';//you might want to change format whether .json .txt etc.

page.open(url, function (status) {
    if(status !== 'success')
        console.log('Connection failed, page was not loaded!');
    else
        var content = page.content;
        fs.write(path, content ,'w')
        phantom.exit();
});

This must give you entire content of the webpage. If you need further assistance, please let me know!


text:
Q: Are Timer and Task creating new threads? In my app, when a Button is clicked a Command is triggered that downloads  the image (asynchronously.. I hope) and the strings, name and character, specified below. The function to download these items is called from a DispatcherTimer as such:
timer.Tick += myMethodToDownloadCastInfo;

Within this method I have:
 timer.Stop();
 List<CastWithPic> castWithPicList = new List<CastWithPic>();
 // Add name and id for each CastWithPic in the list
 // ..

 _viewModel.SelectedItem.castInfoWithPics = castWithPicList;

// Download all the required pics
var tasks = new List<Task>();
foreach (CastWithPic cast in castWithPicList)
{
   tasks.Add(downloadBitmap(cast.profilePath, cast.id));
}

await Task.WhenAll(tasks);

Within the downloadBitmap function I set the object SelectedItem's castInfoWithPics to hold the image value.
It is at this point that I am receiving the error:
The calling thread cannot access this object because a different thread owns it.

SelectedItem is declared in my ViewModel.
SelectedItem Class
public List<CastWithPic> castInfoWithPics { get; set; }

CastWithPic Class
public string name
    {
        get { return (string)this.GetValue(nameProperty); }
        set
        {
            this.SetValue(nameProperty, value);
        }
    }

    public static readonly DependencyProperty nameProperty = DependencyProperty.Register(
                                                            "name", typeof(string),
                                                            typeof(CastWithPic));

    public string character
    {
        get { return (string)this.GetValue(characterProperty); }
        set
        {
            this.SetValue(characterProperty, value);
        }
    }

    public static readonly DependencyProperty characterProperty = DependencyProperty.Register(
                                                            "character", typeof(string),
                                                            typeof(CastWithPic));

    public Bitmap image
    {
        get { return (Bitmap)this.GetValue(imageProperty); }
        set
        {
            this.SetValue(imageProperty, value);
        }
    }

    public static readonly DependencyProperty imageProperty = DependencyProperty.Register(
                                                            "image", typeof(Bitmap),
                                                            typeof(CastWithPic));

downloadBitmap
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uri);
RequestState myRequestState = new RequestState();
myRequestState.request = request;

// Start the asynchronous request.
IAsyncResult result = request.BeginGetResponse(new AsyncCallback(RespCallback), Tuple.Create(myRequestState, actorID));

// this line implements the timeout, if there is a timeout, the callback fires and the request becomes aborted
ThreadPool.RegisterWaitForSingleObject(result.AsyncWaitHandle, new WaitOrTimerCallback(TimeoutCallback), request, DefaultTimeout, true);

// The response came in the allowed time. The work processing will happen in the
// callback function.
allDone.WaitOne();

My question is:
Why don't I get an error when I assign, _viewModel.SelectedItem.castInfoWithPics = castWithPicList; in the timer method but I get an error in the Task method.
Isn't the timer also starting a new thread?
In this case is the proper way to resolve the issue to use the solution suggested here?
The calling thread cannot access this object because a different thread owns it

A: I think _viewModel.SelectedItem.castInfoWithPics = castWithPicList needs to be set in the UI thread. Your donloadBitmap funciton uses a callback to process the response and that runs on a ThreadPool thread.
You can use Dispatcher.Invoke to force work to occur on a UI thread. Try putting this in your callback and putting the appropriate code in the commented section:
Application.Current.Dispatcher.BeginInvoke(
  DispatcherPriority.Background,
  new Action(() => /* set selected item */));

For a better solution you can use async-await which restores the current SynchronizatonContext and yo do not need to use Dispatcher.Invoke. HttpClient provides an async friendly API you can use.
Here is a simple example setting a TextBox value.
 private async Task DownloadUrlAsync(string url)
 {
    using (HttpClient httpClient = new HttpClient())
    {
        textBox1.Text = await httpClient.GetStringAsync(url);
    }
 }

A: You have to freeze your object and the problem is solved.
Here is a sample:
videoIcon = new BitmapImage();
videoIcon.BeginInit();
videoIcon.UriSource = new Uri(@"C:\Data\Image1.jpg");
videoIcon.DecodePixelWidth = 14;
videoIcon.EndInit();
videoIcon.Freeze();

Without the Freeze() I received the same error message you received. With Freeze() the problem is solved.
More info is here:
https://msdn.microsoft.com/en-us/library/ms750509(v=vs.110).aspx
"A frozen Freezable can also be shared across threads, while an unfrozen Freezable cannot."


text:
Q: Image source not being read/found (rails) I have a very simple view page, and for some reason, it is not grabbing my images.  At first I thought there was something wrong with my routes to my images and that they were off, until I put down the entire route (shown below). I still am getting the same error as I was before, however if I take that same image route and paste it into a tab on chrome, I'm able to view the image.
%img{:alt => "Testing Image", :type => "image/jpg", :src => 'images/testImage.jpg'

For some unknown reason, the console gives me a 404 (Not Found)
My legit route that chrome won't allow me to open is, but for proof that i'm not crazy: File:///Users/tomJohnson/Desktop/myAppProjectName/app/assets/images/testImage.jpg
Does anybody have any idea what on earth i'm doing wrong? I'm literally going crazy with this.

A: Instead using a "normal" anchor tag, and having to handle the source path, you can use the image_tag helper:
= image_tag 'images/testImage', alt: 'Testing'

You can also use the alt attribute as a method option and not to worry about the resource extension/format.


text:
Q: Why do the 2 planets in a two-planet system orbit around the center of mass? When reading the Feynman Lectures (chapter 7, volume 1), Feynman was explaining the formation of tides on the Earth and said the following:

The moon does not just go around the earth, the earth and the moon both go around a central position, each falling toward this common position

I got confused by that statement. Does that mean that the 1st Kepler's Law actually means that a planet orbits around the center of mass and that this center of mass is the one located at one of the focus of the elliptical orbit? Or is the focus at the center of the massive body?
Moreover, if the Earth is orbiting around the sun, does that mean that it would be doing kind of small orbits in the large orbit? What I mean is that, if it is also orbiting around that center of mass from the Earth-Moon system, then its orbit around the sun would not be a perfectly elliptical path, it would be like going overall in an elliptical path but doing small circles through that path, right?
I would appreciate if someone can clear my doubts.

A: "Using Newtonian gravity only (i.e. ignoring any relativistic corrections) it can be shown that two bodies will orbit about their common centre of mass, and their orbits will be ellipses with the centre of mass at one focus.
Three or more bodies will also orbit about their common centre of mass, but in the general case their orbits are no longer ellipses and may be chaotic - determining the orbits for three or more bodies is known as the three body problem.
However, if one body is much more massive than the others (as is the case with the Sun and the planets) then to a first approximation that body can be taken to be stationary and the other bodies will orbit in ellipses with the most massive body at a focus. Kepler's laws apply to this first approximation situation.
Over long periods of time the gravitational interactions between the less massive bodies (which are ignored in the first order approximation) must be taken into account and the orbits may become chaotic. It is not known for certain that the orbits of the planets in the solar system will still be stable hundreds of millions of years in the future - see this Wikipedia article.
The mutual orbits of the Earth and the Moon about the Sun are discussed and illustrated at the end of this Wikipedia article.


text:
Q: QuickTheories: Way to create generator from a list Using the java library QuickTheories, is there a builtin way to create a generator from a list of values?
Something like:
public Gen<A> fromList(List<A> xs) {
    ....
}

Rolling your own is not too bad, but seems like reinventing the wheel:
List<TimeZone> timeZones = Arrays.stream(TimeZone.getAvailableIDs()).map(id -> TimeZone.getTimeZone(id));
return integers().allPositive().map(i -> timeZones.get(i % timeZones.size());

A: pick seems exactly what you need.
From the javadoc:
public <T> Gen<T> pick(java.util.List<T> ts)
Generates a value by randomly picking one from the supplied. When shrinking, values earlier in the list will be considered "smaller".


text:
Q: Custom message where key is not present in a hash By definition ruby hashes return nil when a key is not present. But I need to use a custom message in the place of nil. So I'm using something like this:
val = h['key'].nil? ? "No element present" : h['key']

But this has a serious drawback. If there's a assigned nil against the key this will return "No element present" in that case also.
Is there a way to achieve this flawlessly?
Thanks

A: irb(main):001:0> h = Hash.new('No element present')
=> {}
irb(main):002:0> h[1]
=> "No element present"
irb(main):003:0> h[1] = nil
=> nil
irb(main):004:0> h[1]
=> nil
irb(main):005:0> h[2]
=> "No element present"

A: you can use the has_key? method instead
val = h.has_key?('key') ? h['key'] : "No element present"

A: val = h.has_key?("key") ? h['key'] : "No element present"

A: Initialize your hash this way:
> hash = Hash.new{|hash,key| hash[key] = "No element against #{key}"}
 => {}
> hash['a']
 => "No element against a"
> hash['a'] = 123
 => 123
> hash['a']
 => 123
> hash['b'] = nil
 => nil
> hash['b']
 => nil

Hope this helps :)


text:
Q: How to implement MVVM architecture when using TextView to display Seekbar value after it is changed by user interaction? Right now I have a seekbar which has a onseekbarchangelistener attached to it which changes the value of a TextView(targetTemperature) every time the seekbar moves.
        @Override
        public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
         Log.d(TAG, "onProgressChanged: progress: " + progress);
            if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.O) {
                float addTo18 = ((float)progress) / 2;
                Log.d(TAG, "onProgressChanged: addTo18 " + addTo18);
                if(MainActivity.selectedThermostat.getValue().getIsCelsius())
                    targetTemperature.setText(Float.toString((float) (18.0 + addTo18))); //u2109 for farenheit
                else
                    targetTemperature.setText(Float.toString((float) (64.0 + addTo18))); //u2109 for farenheit
            } else {
                if(MainActivity.selectedThermostat.getValue().getIsCelsius()) {
                    float addTo18 = (float) ((float) progress - 18.0) / 2;
                    Log.d(TAG, "onProgressChanged: addTo18 " + addTo18);
                    targetTemperature.setText(String.valueOf(18.0 + addTo18)); //u2109 for farenheit
                } else {
                    float addTo18 = (float) ((float) progress - 64.0) / 2;
                    Log.d(TAG, "onProgressChanged: addTo18 " + addTo18);
                    targetTemperature.setText(String.valueOf(64.0 + addTo18)); //u2109 for farenheit
                }
            }
        }

After reading through some articles on MVVM, I saw that changes to views(TextViews, ImageViews, etc.) in an activity come from observing changes to the mutable live data objects in the view model.
In that case, would it be better practice to create a mutable live data object in the viewmodel  and make changes to that instead of making changes to the TextView(targetTemperature) directly.
Essentially
User interaction -> seekbar change -> textView change
or
User interaction -> seekbar change -> change mutable live data in view model -> textview change

A: You can do as follow:
your ViewModel class like this:
public class SeekViewModel extends ViewModel {

    public ObservableField<String> text = new ObservableField<>();

    public void onSeekBarChanged(SeekBar seekBar, int progress, boolean fromUser) {
        text.set("Your progress: " + progress);
    }
}

your xml layout file:
<LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:gravity="center"
        android:orientation="vertical"
        tools:context=".MainActivity">

        <TextView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="@{viewModel.text}"
            />

        <androidx.appcompat.widget.AppCompatSeekBar
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:onProgressChanged="@{viewModel.onSeekBarChanged}"
            android:max="10"
            android:progress="1"
            />
</LinearLayout>

In your Activity class do like this:
mActivityBinding = DataBindingUtil.setContentView(this, R.layout.activity_main);

        viewModel = new ViewModelProvider(this).get(SeekViewModel.class);
        mActivityBinding.setViewModel(viewModel);

A: If it's only UI change, then modifying the textView directly is fine.
However usually when user inputs something you will want to use it somewhere else other than the UI itself, so the safe way is the second one.
Except, I wouldn't expose MutableLiveData from the ViewModel, instead have a method something like onTemperatureChanges(value: Int) and the ViewModel does the calculation, has a private MutableLiveData and exposes a LiveData via a getter.
So it would look something like this:
View
viewModel.getTemperature().observe(lifecycleObserver, new Observer<String>() {
  @Override
  void onChanged(String text) {
    targetTemperature.setText(text)
  }
);

@Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
  Log.d(TAG, "onProgressChanged: progress: " + progress);
  viewModel.onTemperatureChanges(progress)
}

viewModel:
private MutableLiveData<String> temperature;

LiveData<String> getTemperature() {
  return temperature;
}

void onTemperatureChanges(int progress) {
  // not really sure why you depend on os version or if this calculation is correct, so I just add one section of it
  if (true == isCelsius.getValue()) { // isCelsius another livedata, which you update based on the UI
    temperature.setValue(String.valueOf(((float) progress - 18.0) / 2 + 18.0));
  } else {
    temperature.setValue(String.valueOf(((float) progress - 64.0) / 2 + 64.0));
  }
}

The basic idea is that the View (Activity or Fragment etc) should just delegate it's user inputs to the ViewModel and the ViewModel should do the calculations, data modifications etc, then expose a state via livedata (or flow) to the View which then updates based on that.
Sorry for my Java, i'm a bit out of touch with it lately.


text:
Q: How can I find just the PDF files under folders "Pricelist" and "Price List"? I have a task to find out all the PDF files under several price list folders using JRuby on Windows 7. The folder structure is as follows:
WorkSpace/Data/2015/city1/A/...
WorkSpace/Data/2015/city1/B/...
WorkSpace/Data/2015/city1/Pricelist/...
WorkSpace/Data/2015/city1/...
WorkSpace/Data/2015/city1/Price List/.....
WorkSpace/Data/2015/city2/A/...
WorkSpace/Data/2015/city2/C/...
WorkSpace/Data/2015/city2/Pricelist/...
WorkSpace/Data/2015/city2/D/...
WorkSpace/Data/2015/city2/Price List/.....

WorkSpace/Data/2016/city1/folder1/...
WorkSpace/Data/2016/city1/folder2/...
WorkSpace/Data/2016/city1/Pricelist/...
WorkSpace/Data/2016/city1/folder3/...
WorkSpace/Data/2016/city1/folder4/Price List/...
WorkSpace/Data/2016/city2/folder1/...
WorkSpace/Data/2016/city2/folder2/...
WorkSpace/Data/2016/city2/Pricelist/...
WorkSpace/Data/2016/city2/folder3/...
WorkSpace/Data/2016/city2/folder4/Price List/...

... represents all kinds of files under their corresponding folder.
I only want to find the PDF files under folder Pricelist and Price List. How can I do this?
I read Searching a folder and all of its subfolders for files of a certain type. This is an answer which I think is helpful, but how can I modify the expression /.*\.pdf$/ to achieve my goal?

A: Use a Recursive Glob
All you need to find your files is Dir#glob and Enumerable#grep. For example:
Dir.glob('WorkSpace/Data/**/*.pdf').grep /Price List|Pricelist/

This will collect all the PDF files using a recursive glob pattern that descends into all subdirectories starting at Workspace/Data (adjust the path to this starting directory as needed), and then returns only the results that match the directories you're grepping for. In this case, we're using a regular expression pattern with alternation to find either of the two directories you're looking for, without regard to how deeply nested the desired directories might be.
There may be more efficient ways to do this, or you may need to tweak the regex if it's too permissive for you, but this certainly solves the problem without needing to know much more than the root of the directory tree you want to search.

A: You'll probably want to look at the Find module. The code would be something like this:
results = []
directory_list = []

Find.find('Workspace/Data') do |path|
    if FileTest.directory?(path)
        fn = File.basename(path)
        if fn == 'Pricelist' || fn == 'Price List'
            directory_list << path
            Find.prune
        end
    end
end

directory_list.each do |starting_path|
    Find.find(starting_path) do |path|
        if File.extname(path) == '.pdf'
            results << path
        end
    end
end

The first loop scans and finds all the directories that match the directory name condition, skipping scanning below them because that will happen in the second loop. The second loop takes each of the directories found by the first loop and scans them for files ending in the '.pdf' extension, adding each one to the results list.
You can hoist the second loop's body up into the first loop in place of directory_list << path, but the resulting code would be harder to read and wouldn't gain any performance improvement.


text:
Q: Quantifiers for formal definition of a limit I have a problem. I have to prove that
$(\forall\,\epsilon > 0)(\exists\,\delta > 0)[0 < |x − a| < \delta \implies |f(x) − L| < \epsilon$ (formal definition of a limit)
$(\exists\,\delta > 0) (\forall\,\epsilon > 0)[0 < |x − a| < \delta \implies |f(x) − L| < \epsilon$
are the same. Basically the only difference is the order of the quantifiers.
My first instinct was to use DeMorgans Law and negate the quantifier but that is not quite the same proposition. I am not sure how to prove this equivalence. Can anybody help?

A: $\forall  \epsilon \;\;\exists \delta$ means for any given $\epsilon$ we have $\delta$ which depends on $\epsilon$.
$\exists \delta\;\;\forall  \epsilon $ means there is a $\delta$ for all $\epsilon$. In this case $\delta$ is independent of $\epsilon$
So your statements are NOT same.

A: Another consequence of $(\exists\delta>0)(\forall\epsilon>0)(|x-a|<\delta\implies |f(x)-L|<\epsilon)$.  Since $|f(x)-L|<\epsilon$ for all $\epsilon>0$, we must have $f(x)=L$ whenever $|x-a|<\delta$.


text:
Q: A way to reboot iOS device or restart Springboard using private API? I am looking for some private API or piece of code which will allow me to reboot iOS device or restart Springboard.
I looked at SBReboot, but it looks like it's protected by some entitlement.
Also, I tried reboot(int) and reboot2(int), but it looks like both of them work only for "root" user and will do nothing for a "mobile" user.
I am looking for a solution which works on non jailbroken device. However, private API's are ok (an application won't go to AppStore)
Update 1
In response to Josiah answer below. Finding an expoit for gaining root privileges isn't the only option. As example, any vulnerability which will allow to crash kernel or Springboard is fine with me (even if it can't be used to get a root privileges).

A: There is no private or public API that can be executed as mobile from inside of an app. It's annoying, but that's truth.
The only way this is possible is to have a jailbroken device, which you said isn't possible.
Finally, there aren't even any unsafe ways to do this. You can't overload the memory or anything that will cause a reboot. Apple just kills your app.
After finally, there is one thing you could do... Find an exploit that you can execute through this app, to get yourself root privileges until after a reboot. Possible, but your not getting that info from here.
Good luck though. (Oh, and if anyone does have a way to do this, let me know, this could be used as an exploit)
Edit
I found a way to restart the springboard without a jailbreak, however it does not really do what you want. But it could give people some ideas.

*

*Firstly, you will just need to disable your devices passcode. If not, this glitch will not work. Go to Settings>;General>;Passcode Lock and turn it off.

*Lock your device.

*Enter lockscreen and turn your device in landscape mode (horizontally).

*Swipe up that camera slider thing (I'm not sure how you call it, LOL) while remaining in landscape mode

*As soon as the whole lockscreen is out and cannot be seen, press the home button and tap the photo library square on the now bottom right of the screen simultaneously. Note: do not need to wait for the camera to load and be active.

*You should see the home screen for a very short time before you see an Apple logo/loading circle, your device is now respringing. (note: in iOS 6 Apple replaced the usual loading circle when respringing into the Apple logo, don't worry your device is NOT rebooting)


text:
Q: Extract table data from website using Python I am trying to get information related to any website the user is trying to access. To stop any malicious website access, I need details like blacklist status, IP address, Location of server etc. I got this from URLVOID website. < https://www.urlvoid.com/scan/>
I am getting following results in a table format and trying to fetch the same in spyder.
See the Table
I am using regex approach to get particulars from the table.
######

import httplib2
import re
def urlvoid(urlInput):
    h2 = httplib2.Http(".cache")
    resp, content2 = h2.request(("https://www.urlvoid.com/scan/" + urlInput), "GET")
    content2String = (str(content2))
    rpderr = re.compile('\
', re.IGNORECASE)
    rpdFinderr = re.findall(rpderr,content2String)
    if "error" in str(rpdFinderr):
        ipvoidErr = True
    else:
        ipvoidErr = False
    if ipvoidErr == False:

        rpd2 = re.compile('(?<=Server Location	)[a-zA-Z0-9.]+(?=
)')
        rpdFind2 = re.findall(rpd2,content2String)
        rpdSorted2=sorted(rpdFind2)

    return rpdSorted2

urlvoid("google.com")
######

However, it is not much efficient and this regex does not work with all the websites. Is there any simpler way to get all this information?

A: I do not suggest you to scrape data with regex because it can be done by bs4, and if you build up a regex to complete that you need long time and complex condition.
import requests
from bs4 import BeautifulSoup,NavigableString
import re

def urlvoid(urlInput):
    url = "https://www.urlvoid.com/scan/" + urlInput
    res = requests.get(url)
    text = res.text
    soup = BeautifulSoup(text,"lxml").find("table",class_="table table-custom table-striped")
    all_tr = soup.find_all("tr")
    value = { tr.find_all("td")[0].text :
                tr.find_all("td")[1].text.replace("\xa0","")
                for tr in all_tr}
    print(value)

urlvoid("google.com")


text:
Q: Why are two integer pointers of the same value point to the same thing (via ==) ? int *x = 3;
int *y = 3;

if (x == y) "this statement evaluates to true" (pointer equality statement)
if (*x == *y) "this statement evaluates to true"

Is the reason that the pointer equality statement becomes true, just purely because COMPILER saw two "static" numbers "3" and said, hey point this to the same place? Or is there some magic for integers in general.
It obviously seems redundant that deferencing an integer pointer is the same (in this case) as not dereferencing.
I've seen some examples of this problem pertaining to strings (Addresses of two pointers are same), but wanted to clarify it more.

A: You've simply hardcoded a fixed memory address for both pointers, 3. Stands to reason that this simple address is the same, and that whatever data is actually AT that address will also be the same.
It's like you've got two sticky notes on your fridge. Both says "keys are on table by door". And by jove, when you go look by the door, there's your keys. Two different pointers, both pointing at the same thing.

A: Both of the declaration
int *x = 3;
int *y = 3;

are constraint violation. You can declare
int *x = (int *)3;
int *y = (int *)3;

these both are referring to the address 3 of memory.
if (*x == *y) "this statement evaluates to true"

No. It invokes undefined behavior. You may get anything. Either this evaluates to true or false

A: int *x = 3;

This is invalid (a constraint violation), and a conforming compiler is required to issue a diagnostic, and may reject it altogether. You cannot use an integer value to initialize a pointer (except for the special case of 0, which is a null pointer constant).
If a compiler happens to accept it it will probably treat it as equivalent to:
int *x = (int*)3;

which causes the pointer x to point to address 3 in memory. This is almost certainly nonsensical.
Given that x and y are initialized with the same expression (and assuming your code isn't rejected), it's not at all surprising that x == y is true.
Dereferencing x has undefined behavior; (int*)3 is very probably not a valid address, because it's outside your program's legal addressing space and/or because it's misaligned. But if *x happens to "work" and yield a value, it's also not surprising that *x == *y is true. It's possible that the compiler recognized that x == y and therefore concluded that *x == *y. You might determine that by examining the generated code. But it really doesn't matter; once your program's behavior is undefined, quite literally anything can happen (or rather, the language standard permits literally anything to happen; the laws of physics might have something else to say about it).
You should have gotten a warning for both declarations. If you did, you should heed it. If you didn't, you should find out how to increase the warning levels for your compiler.


text:
Q: How to generate binary data using Cholesky decomposition in R? m <- matrix(nrow=5, ncol=5)
m <- ifelse(row(m)==col(m), 1, 0.4)
ch <- chol(m)    # Choleski decomposition
u <- matrix(rnorm(2000*5), ncol=5)
uc <- u %*% ch
cr <- pnorm(uc)
cr <- qbinom(cr,1,0.5)
cor(uc)
cor(cr)

The cor(uc) is 0.4. However, I also expected the cor(cr) to be 0.4, but it is around 0.2.
Why the correlation is shrunken?

A: I'm going to go ahead and copy most of my answer from StackOverflow here:
You may want to look into the literature on copulas. I believe that what you are doing here is basically constructing a Gaussian copula (Wikipedia): maybe this is already obvious to you, maybe not ... For example, http://www.casact.org/library/02pcas/venter.pdf states

The linear correlation coefficient based on the covariance of two
  variates is not preserved by copulas. That is, two pairs of correlated
  variates with the same copula can have different correlations.
  However, the Kendall correlation, usually denoted by τ, is a constant
  of the copula. That is, any correlated variates with the same copula
  will have the τ of that copula.

As suggested by @Glen_b's comment, you don't necessarily need Cholesky to do this -- there are lots of ways to generate correlated multivariate normal Gaussian data (MASS::mvrnorm is probably the most widely used R function: it uses an eigenvector rotation).

A: By converting an interval scaled set of numbers with a given correlation (mostly concentrated around 0) over to a 1/0 scale you, on average, drove the pairs further apart on the squared distance scale. In thinking about this for its implications to coders it is probably that the unnecessary conversion of interval data to binomial data is going to decrease the power of your investigations into the data relationships. An investigation into count data outcomes conducted with Poisson regression is likely to reveal more than if the outcomes were coded into 1/0 depending on whether the counts were above or below any particular cutpoint. There's probably a proof that could be exhibited but demonstration of probability theorems is not what SO is about. If you want a more mathematical explanation, there is always the stats.stackexchange.com interface.


text:
Q: What is the correct type annotation for a function that returns a Sequence of the same type as one of its inputs? For the Python code
from typing import TypeVar, Sequence, Iterator

S = TypeVar("S", bound=Sequence)

def chunk(data: S) -> S:
    return data[:]

mypy 0.971 reports the error

simple_8.py:6:12: error: Incompatible return value type (got "Sequence[Any]", expected "S")  [return-value]

Where is the type annotation error in this example and what is the correct, precise way to annotate this function?

A: If you look at the Typeshed definition of Sequence:
class Sequence(Collection[_T_co], Reversible[_T_co], Generic[_T_co]):
    @overload
    @abstractmethod
    def __getitem__(self, index: int) -> _T_co: ...
    @overload
    @abstractmethod
    def __getitem__(self, index: slice) -> Sequence[_T_co]: ...

you can see that seq[:] is guaranteed to return some Sequence with the same generic type _T_Co as the source, but that it's not necessarily the same type of sequence. Although the built-in sequence types generally have this behaviour, e.g. for list:
    @overload
    def __getitem__(self, __s: slice) -> list[_T]: ...
                                       # ^ concrete list not abstract Sequence

it's not a requirement of the interface.
As you don't supply the generic type to the Sequence in your TypeVar, it's the default Any, hence the error:
error: Incompatible return value type (got "Sequence[Any]", expected "S") [return-value]

The slice data[:] gives a Sequence[Any], which might be the same as S but is not required to be. So if you want to support any Sequence, the most precise you can be is:
from typing import Sequence, TypeVar

T = TypeVar("T")

def chunk(data: Sequence[T]) -> Sequence[T]:
    return data[:]

Playground

Alternatively, if you define a Protocol with the stricter typing that seq[:] must return the same type:
from typing import Protocol, TypeVar

T = TypeVar("T")

class StrictSlice(Protocol):
    def __getitem__(self: T, index: slice) -> T: ...

you can then use this as the bound type in S and get the type-preserving behaviour:
S = TypeVar("S", bound=StrictSlice)

def chunk(data: S) -> S:
    return data[:]

l: list[int] = chunk([1, 2, 3])
s: str = chunk("Hello, world!")

If you tried this with the Sequence[T], you'd get e.g. expression has type "Sequence[int]", variable has type "List[int]".
Playground


text:
Q: Extract data from the database to a map I'm trying to query data to a map :
@Repository
public interface IUserRepository extends PagingAndSortingRepository<UserEntity, String> {

    @Query("SELECT DISTINCT (u.userId, u) FROM UserEntity u WHERE userId in (:userIds)")
    Map<String, UserEntity> findAllByUserIdIn(@Param("userIds") Collection<String> userIds);

But I get this error:
Caused by: java.lang.IllegalArgumentException: org.hibernate.hql.internal.ast.QuerySyntaxException: unexpected AST node: {vector} [SELECT DISTINCT (u.userId, u) FROM com.telefire.device.server.users.model.UserEntity u WHERE userId in (:userIds)]
...
Caused by: org.hibernate.hql.internal.ast.QuerySyntaxException: unexpected AST node: {vector} [SELECT DISTINCT (u.userId, u) FROM com.telefire.device.server.users.model.UserEntity u WHERE userId in (:userIds)]

JPA doesn't allow this?
Thanks!

A: The exception means the Query syntax is not right.
Please check: http://docs.spring.io/spring-data/jpa/docs/current/reference/html/#jpa.query-methods.query-creation
second option add nativeQuery = true
    @Query("SELECT DISTINCT (u.userId, u) FROM UserEntity u WHERE userId in (:userIds)",nativeQuery = true)

third option add value =:
    @Query(value = "SELECT DISTINCT (u.userId, u) FROM UserEntity u WHERE userId in (:userIds)",nativeQuery = true)


text:
Q: Get Gurobi IIS using Pyomo and gurobipy Could someone walk me through the steps to get the IIS from a Pyomo model using gurobipy?
opt = SolverFactory('gurobi',solver_io='python')
As a reference, this is what I use in JuMP
function getIIS(m::JuMP.Model)
  grb_model = m.internalModel.inner
  num_constrs = Gurobi.num_constrs(grb_model)
  Gurobi.computeIIS(grb_model)
  iis_constrs = Gurobi.get_intattrarray(grb_model, "IISConstr",  1, num_constrs)
  m.linconstr[find(iis_constrs)]
end

So, basically I need access to the internal gurobi model to run the computeIIS function, and then I need a way to map the array of rows to the actual Pyomo constraints.
thanks!

A: You can pass this as an option to Gurobi when you call
the solve function by using options_string. Then, Gurobi's Model.write() function will write the file. In this case, you would write a .ilp file, but other file formats exist for different purposes. An example:
solver_parameters = "ResultFile=model.ilp" # write an ILP file to print the IIS

Then, you would add options_string when you call the solve function:
results = solver.solve(instance, options_string=solver_parameters)

You can also string multiple options together with the following syntax. Note the leading empty space within the quotes for the LogToConsole and ResultFile options:
 solver_parameters = "TimeLimit=60" # set time limit (seconds)
            solver_parameters += " LogToConsole=0" # 0 =  turn off console output
            solver_parameters += " ResultFile=model.ilp" # write a MIP start file to warm start

The documentation found here applies to solving a model with Gurobi, and the examples at the bottom work with any Gurobi file format:
http://www.gurobi.com/documentation/8.0/refman/solving_a_model2.html
Finally, this link explains the different file formats that Gurobi can write: http://www.gurobi.com/documentation/8.0/refman/model_file_formats.html#sec:FileFormats

A: See this Pyomo example using suffixes. I believe it's doing what you want.
https://github.com/Pyomo/pyomo/blob/master/examples/pyomo/suffixes/gurobi_ampl_iis.py


text:
Q: Terraform AWS Lambda function with terraform I am new to Terraform, I am having difficulty in configuring vpc_config in Lambda function.
main.tf
resource "aws_lambda_function" "lambda" {
  function_name = var.function_name
  s3_bucket = var.s3_bucket_name
  s3_key = var.s3_key
    vpc_config {
      security_group_ids = ["${var.lambda_security_group_id}"]
      subnet_ids         = ["${split(",", var.lambda_subnet_id)}"]
    }
  #source_code_hash = data.archive_file.zip.output_base64sha256
  role    = aws_iam_role.iam_for_lambda.arn
  handler = "welcome.lambda_handler"
  runtime = "python3.9"
  timeout = var.timeout
  memory_size = var.lambda_mem_size
}

variables.tf
variable "lambda_security_group_id" {
  type = list(string)
}

variable "lambda_subnet_id" {
  type = list(string)
}

terraform.tfvars
lambda_security_group_id = ["sg-0aabcef7795c7e092", "sg-0f218ddc9fb47341d"]
lambda_subnet_id = ["subnet-0d786711ca50ab0f7", "subnet-06341798f99bc9849"]

Please guide me from here.

A: I think you need something like this, since the variables are already a list of strings. It could be a good idea to rename your variables to the plural form since they are lists: lambda_security_group_ids and lambda_subnet_ids.
  vpc_config {
      security_group_ids = var.lambda_security_group_id
      subnet_ids         = var.lambda_subnet_id
  }

More info can be found here.


text:
Q: Python Regular Expression group repetition within a repetition I have a string and have to extract. The problem is I can't describe repetition within a repetition. So here is the code:
f = "Makimak-cg_mk_Mokarmi"
pattern = "([A-Za-z][A-Za-z0-9]+)((?:[-_]([a-z]{2}))+)"
mO = re.match(pattern, f)
print mO.groups()

And the result will be:
('Makimak', '-cg_mk', 'mk')

But I would like to get tuple like this:
('Makimak', '-cg_mk', 'cg', 'mk')

So there is a group "-cg_mk" which include a repetition of the two character pattern. But there is no thing like that:
[a-z]{2}+

The groups of the result give back only the last part of the repetition expressed here:
([a-z]{2})

My thought was that there should be a "+" too like this:
([a-z]{2})+

It gives the same result. The match object is generated, simply I can't get the groups that I want.

A: You may need to do this in two steps:
>>> f = "Makimak-cg_mk_Mokarmi"
>>> pattern = "([A-Za-z][A-Za-z0-9]+)((?:[-_][a-z]{2})+)"
>>> mO = re.match(pattern, f)
>>> print mO.groups() + tuple(re.split('[-_]', mO.group(2))[1:])
('Makimak', '-cg_mk', 'cg', 'mk')

This just captures the groups ('Makimak', '-cg_mk'), and then combines this with the result of splitting the second group on occurrences of - or _.
If you always knew the exact number of two character patterns you could accomplish this with a lookahead, but it doesn't seem like that is known up front or you wouldn't need the repetition.


text:
Q: Can't sort bar chart by transformed mysql timestamp in Google Data Studio I've linked Google data studio with a MySQL database using the standard connector. Everything works except sorting correctly by date.
Database columns configured like this:

*

*price decimal(15,2) not null 24.59

*last_changed timestamp not null 2019-03-25 19:24:52
GDS datasource fields configured (as per this answer) like this:

*

*last_changed Date(YYYYMMDD) 2019-03-25

*sold_at GDS function TODATE(last_changed, 'DEFAULT_DASH', '%Y%m%d')
GDS bar chart configured like this:

*

*time dimension sold_at as date

*dimension sold_at as date

*value metric price as sum

*sorting sold_at as date ascending

*time range auto from date picker with default set to current month
I am experiencing the following issue: When sorting is set to sold_at the bar chart is empty with the default date range. Only when i go back at least one month it displays values in the chart but also cuts off the last day so that its less than it should be. Only when sorting is set to price it displays everything correctly, even in the current month. Also when switching from sorting set to price to sold_at while the default time range is selected it shows the sold_at field under Invalid in the sorting modal.
I tried modifying the database column to datetime instead of timestamp but it didnt change anything. I also tried setting a different default time range but that doesnt change anything also. It keeps showing no data for 1 month back.
Any idea or someone who already stumbled across this scenario?

A: For people that come across the same issue:
This issue was caused by the MYSQL timestamp/datetime column having optional Hrs:Min:Sec. This caused the GDS mysql query to not be able to group them by day and thus resulting in more than 100000 rows, which is more than the hardcoded limit set by the connector.
Solution: Added another timestamp/datetime column and filled it with
UPDATE table SET newcolumn = DATE_FORMAT(oldcolumn, '%Y/%m/%d');
It now works like a charm.


text:
Q: Ruby local variable is undefined I have the following Ruby code:
local_var = "Hello"

def hello
  puts local_var
end

hello

I get the following error:
local_variables.rb:4:in 'hello': undefined local variable or method 'local_var'
for main:Object (NameError) from local_variables.rb:7:in '<main>'

I always thought that local variables are not accessible from outside of the block, function, closure, etc.
But now I defined local variable in the file and try to get an access from the function  INSIDE the same file.
What's wrong with my understanding?

A: In Ruby local variables only accessible in the scope that they are defined. Whenever you enter/leave a Class, a Module or a Method definiton your scope changes in Ruby.
For instance :
v1 = 1

class MyClass # SCOPE GATE: entering class
  v2 = 2
  local_variables # => ["v2"]

  def my_method # SCOPE GATE: entering def
    v3 = 3
    local_variables  # => ["v3"]
  end # SCOPE GATE: leaving def

  local_variables # => ["v2"]
end # SCOPE GATE: leaving class

These entering and leaving points are called Scope Gates. Since you enter through Scope Gate via method definition you cannot access your local_var inside hello method.

You can use Scope Flattening concept the pass your variable through these gates.
For instance instead of using def for defining your method you can use Module#define_method.
local_var = "Hello"

define_method :hello do
  puts local_var
end

In the same way you can define your classes via Class#New so that your scope does not change when you pass through class definition.
local_var = 'test'

MyClass = Class.new do
  puts local_var #valid
end

instead of
class MyClass
  puts local_var #invalid
end

In the same way you should use Module#New if you want to pass your local variables through Module gates.
Example is taken from Metaprogramming Ruby

A: Ensure that the function takes arguments and add the object as one of the arguments when you call it
local_var = "Hello"

def hello(some_local_var)
  puts local_var
end

hello(local_var)

A: local_var is a local variable. Local variables are local to the scope they are defined in. (That's why they are called "local variables", after all!) So, obviously, since local_var is defined in the script scope, you cannot access it in the method scope.


text:
Q: IOS: Notification only showing cross button not showing Category using GCM I am trying to show notification with UIMutableUserNotificationCategory in IOS but it only show default cross button not showing other buttons then i add in Category. It should be showing like this bellow. Is it possible or its not possible with GCM. This is how i add category in application didfinishlaunching
// Category
let releaseRoomCategory = UIMutableUserNotificationCategory()
releaseRoomCategory.identifier = categoryID

    releaseRoomCategory.setActions([yesAction, noAction],
        forContext: UIUserNotificationActionContext.Minimal)
    releaseRoomCategory.setActions([yesAction, noAction], forContext: .Default)

    let settings: UIUserNotificationSettings =
    UIUserNotificationSettings(forTypes: [.Alert, .Badge, .Sound], categories:  NSSet(object: releaseRoomCategory) as? Set<UIUserNotificationCategory>)
    application.registerUserNotificationSettings(settings)
    application.registerForRemoteNotifications()

A: Hi finally found the answer my self this is how its done for GCM
{"to": <reg_token>, "notification": {"body": "Hello from GCM", "click_action": "RELEASEROOM_CATEGORY"}}

click_action is represent category :D thanks every one :D


text:
Q: Set customer "exempt of vat" when order is created in backend in WooCommerce I would like to add an action in woocommerce to remove the tax from orders when created in the backend and for special users as customers.
This code is working for the normal order process on the website, but not on the backend
add_action( 'woocommerce_checkout_update_order_review', 'remove_tax_from_user' );
add_action( 'woocommerce_before_cart_contents', 'remove_tax_from_user' );

function remove_tax_from_user( $post_data ) {
  global $woocommerce;
  $username = $woocommerce->customer->get_username();
  $user = get_user_by('login',$username);
  if($user)
  {
    if( get_field('steuer_befreit', "user_{$user->ID}") ):
    $woocommerce->customer->set_is_vat_exempt( true );
    endif;
  }
}

A:
In backend customer needs to be "exempt of Vat" before clicking on "Add order" .

You could try to use the hook save_post_shop_order that is triggered before order data is saved in backend, this way:
add_action( 'save_post_shop_order', 'backend_remove_tax_from_user', 50, 3 );
function backend_remove_tax_from_user( $post_id, $post, $update ) {

    if ( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE )
        return $post_id; // Exit if it's an autosave

    if ( $post->post_status != 'publish' )
        return $post_id; // Exit if not 'publish' post status

    if ( ! current_user_can( 'edit_order', $post_id ) )
        return $post_id; // Exit if user is not allowed

    if( ! isset($_POST['customer_user']) ) return $post_id; // Exit

    if( $_POST['customer_user'] > 0 ){
        $customer_id = intval($_POST['customer_user']);
        if( get_field('steuer_befreit', "user_{$customer_id}") ){
            $wc_customer = new WC_Customer( $customer_id );
            $wc_customer->set_is_vat_exempt( true );
        }
    }
}

Code goes in function.php file of your active child theme (or theme).
But this will not work and you will not be able with any exiting hook to make that work. The only way Is to make first customer exempt of vat, then you can Add an order for this customer.


text:
Q: alamofire get request return null value I have one problem. I am reuesting with alamofire an it return value. In alamofire i convert returned json to my custom class, its work goog. But when i am using this converted class out of alamofire body it returned nil value.
I put breakpoint in alamofire where i converted json value and appent to my class, it has value and it put it to my class.But out of body it equal nil. Why?
func getZakazDetail(orderID:Int,tableView:UITableView,spinner:UIActivityIndicatorView){

    if flag{
        let zD=ZakazDetailTableViewController()
        Alamofire.request(.GET, "myUrl")
            .responseJSON { response in
                guard response.result.error == nil else {
                    // got an error in getting the data, need to handle it
                    print("error calling GET on /todos/1")
                    print(response.result.error!)
                    return
                }

                if let value = response.result.value {
                    let product = JSON(value)
                    if product != nil{
                        for (_,subJson):(String, JSON) in product {
                            let p=ZakazDetail(id: subJson["id"].int!, tovar: subJson["tovar"].string!, count: subJson["count"].int!, orderid: subJson["orderid"].int!, cena: subJson["cena"].int!)
                            self.zakazDetail.append(p)
                            zD.detail.append(p)
                        }
                    }
                }
        }
        spinner.stopAnimating()
        UIApplication.sharedApplication().networkActivityIndicatorVisible = false
        tableView.reloadData()

    }
    else{
        let alert = UIAlertView(title: "Ошибка",message: "Нету интернета!",delegate: nil,cancelButtonTitle: "OK")
        alert.show()
    }

}

A: This is happening because alamofire loads the data asynchronously and before you append anything in zD.detail.append(p).
Add a completion handler for the program to wait till the loading is complete.
//here you call authenticateUser with a closure that prints responseObject
API().authenticateUser{ (responseObject, error) in
    println(responseObject)
}

Then:
//authenticateUser receives your closure as a parameter
func authenticateUser(completionHandler: (responseObject: String?, error: NSError?) -> ()) {
    //it passes your closure to makeAuthenticateUserCall
    makeAuthenticateUserCall(completionHandler)
}

//makeAuthenticateUserCall receives your closure
func makeAuthenticateUserCall(completionHandler: (responseObject: String?,
error: NSError?) -> ()) {
    Alamofire.request(.GET, loginUrlString)
        .authenticate(user: "a", password: "b")
        //here you pass a new closure to the responseString method
        .responseString { request, response, responseString, responseError in
            //in this closure body you call your completionHandler closure with the
            //parameters passed by responseString and your code gets executed
            //(that in your case just prints the responseObject)
            completionHandler(responseObject: responseString as String!, error: responseError)
    }
}

For more information read the documentation: Swift Closures


text:
Q: How to make userEmail the foreignkey connect to the emailId in Tbluser model I want to connect the userEmail from Tblbooking model and emailId from Tbluser model.
App\Models\Tbluser:
 protected $primarykey = 'EmailId';
 public function bookings(){
    return $this->hasMany('App\Models\Tblbooking');}

App\Models\Tblbooking:
protected $foreignkey='userEmail';
public function user(){
    return $this->belongsTo('\App\Models\Tbluser','userEmail','userEmail');
}

A: App\Models\Tbluser - https://laravel.com/docs/7.x/eloquent-relationships#one-to-many
use App\Models\Tblbooking;

class Tbluser
{
  public function bookings()
  {
    return $this->hasMany(Tblbooking::class, 'userEmail', 'EmailId');
  }
}

App\Models\Tbluser - https://laravel.com/docs/7.x/eloquent-relationships#one-to-many-inverse
use App\Models\Tbluser;

class Tblbooking
{
  public function user()
  {
    return $this->belongsTo(Tbluser::class, 'EmailId', 'userEmail');
  }
}

I would suggest refactoring your code and calling models User and Booking. You can use protected $table to define table that model should use, i.e. protected $table = 'tbl_bookings';.
use App\Models\User;

class Booking
{
  protected $table = 'tbl_bookings';

  public function user()
  {
    return $this->belongsTo(User::class, 'EmailId', 'userEmail');
  }
}

Also it might be of benefit to have a separate table where you can store all your emails, to follow 3NF (https://en.wikipedia.org/wiki/Third_normal_form#:~:text=Third%20normal%20form%20(3NF)%20is,in%201971%20by%20Edgar%20F.). It's also a common practice to use snake case to name columns.


text:
Q: Slow UICollectionView with asynchronous loading I have an UICollectionView which loads images of the iPad's memory and displays them in a grid,like Apple's Photos app. The UICollectionViewCell loads thumbnails asynchronously:
 func setImage(img:String){
        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), {
            //load the image in the background
            let image = UIImage(contentsOfFile: img)
            //when done, assign it to the cell's UIImageView
            dispatch_async(dispatch_get_main_queue(), {
                if let imageView = self.imageView{
                    imageView.image = UIImage(contentsOfFile: img)
                }
            })
        })
    }

However, while scrolling the view lags as if it is waiting for the images to load, especially with Retina graphics. The cells and images are about 240x180px big. Is there anything wrong with the image loading above or further optimisations need to be made?
UPDATE: Time profiler results

A: You've already found that you're loading the UIImage again on the main queue; fixing that will help.
UIImage lazy loads its internal image data in most cases.  One trick is to call its CGImage property while still on the background queue to force it to actually create its internal image data instead of lazily loading it when the image view is drawn the first time:
func setImage(img:String){
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), {
        //load the image in the background
        let image = UIImage(contentsOfFile: img)
        image.CGImage // <- Force UIImage to not lazy load the data
        //when done, assign it to the cell's UIImageView
        dispatch_async(dispatch_get_main_queue(), {
            if let imageView = self.imageView {
                imageView.image = image
            }
        })
   })
}

Note: If you have a lot of images you may end up getting a memory warning fairly quickly doing this. If you do, this probably won't help because the memory warning will typically cause UIImage to clear its internal image data again to free up resources.

A: On the line
imageView.image = UIImage(contentsOfFile: img)

I was loading the image again on the main thread, not the image loaded asynchronously. Changed to
imageView.image = image

Scrolling is a bit better, but yet choppy. The time profiler shows similar results as before. May the bottleneck be in the UIImageView drawing? It works fine with non-retina thumbnails.

A: The bottleneck was that some thumbnails were scaled improperly and were a lot bigger than the UIImageView, which caused the longer loading time. I also presume this caused slower drawing since the UIImage had to be downscaled to fit in the UIImageView.
I fixed the thumbnail-generating code and scrolling is smooth again.
P.S. I also fixed the misplaced UIImage(contentsOfFile: img) variable in the initial code, see my other answer.

A: in Swift:
    let priority = DISPATCH_QUEUE_PRIORITY_DEFAULT
    dispatch_async(dispatch_get_global_queue(priority, 0)) {
        let imagem = UIImage(named :"image")
        dispatch_async(dispatch_get_main_queue()) {
            cell.IMG_Novidades.image = imagem
        }
    }

    //THIS IS VERY IMPORTANT
    cell.layer.shouldRasterize = true
    cell.layer.rasterizationScale = UIScreen.mainScreen().scale


text:
Q: Can ElasticSearch be used purely for aggregations? In my current usecase, I'm using ElasticSearch as a document store, over which I am building a faceted search feature.
The docs state the following:

Sorting, aggregations, and access to field values in scripts requires a different data access pattern.
Doc values are the on-disk data structure, built at document index time, which makes this data access pattern possible. They store the same values as the _source but in a column-oriented fashion that is way more efficient for sorting and aggregations.

Does this imply that the aggregations are not dependent on the index? If so, is it advisable to prevent the fields from being indexed altogether by setting {"index": "no"} ?
This is a small deviation, but where does the setting enabled come in? How is it different from index?
On a broader note, should I be using ElasticSearch if aggregations is all I'm looking for? Should I opt for other solutions like MongoDB? If so, what are the performance considerations?
HELP!

A: It is definitely possible to use Elasticsearch for the sole purpose of aggregating data. I've seen such setups a few times. For instance, in one past project, we'd index data but we'd only run aggregations in order to build financial reports, and we rarely needed to get documents/hits. 99% of the use cases were simply aggregating data.
If you have such a use case, then you can tune your mapping to
The role of enabled is to decide whether your data is indexed or not. It is true by default, but if you set it to false, your data will simply be stored (in _source) but completely ignored by analyzers, i.e. it won't be analyzed, tokenized and indexed, and thus, it won't be searchable, you'll be be able to retrieve the _source, but not search for it. If you need to use aggregations, then enabled needs to be true (the default value)
The store parameter is to decide whether you want to store the field or not. By default, the field value is indexed, but not stored as it is already stored with the _source itself and you can retrieve it using source filtering. For aggregations, this parameter doesn't play any role.
If your use case is only about aggregations, you might be tempted to set _source: false, i.e. not store the _source at all since all you'll be needed is to index the field values in order to aggregate them, but this is rarely a good idea for various reasons.
So, to answer your main question, aggregations do depend on the index, but the (doc-)values used for aggregations are written in dedicated files, whose inner structure is much more performant and optimal than accessing the data from the index in order to build aggregations.
If you're using ES 1.x, make sure to set doc_values to true for all the fields you'll want to aggregate on (except analyzed strings and boolean fields).
If you're using ES 2.x, doc_values is true by default, so you don't need to do anything special.
Update:
It is worth noting that aggregations are dependent on doc_values (i.e. Per Document Values .dvd and .dvm Lucene files), which basically contains the same info as in the inverted index, but organized in a column-oriented fashion, which makes it much more efficient for aggregations.


text:
Q: How to add custom local marker image to mapbox I'm trying to add the local image as marker to mapbox (mapbox-gl: 2.9.2).
I can add marker from external url like https://placekitten.com/g/30/30, but can't add from local (from my project root dir). I'm using react.
My Attempts: (This shows nothing)
import myCatLogo from './assets/icons/my-cat-logo.png';

const imageCat: any = new Image(20, 20);
imageCat.src = myCatLogo;
map.addImage("myCat", imageCat);

map.addLayer({
    id: "marker",
    type: "symbol",
    source: "datas",
    layout: {
      "icon-image": "myCat",
      // "icon-size": [20, 20],
    }
});

My another attempts: (Uncaught (in promise) Error: Not Found at eval)
map.loadImage(myCatLogo, (error, image) => { // the image path is correct!
    if (error) throw error;
    map.addImage("myCat", image);
});

map.addLayer({
    id: "marker",
    type: "symbol",
    source: "datas",
    layout: {
      "icon-image": "myCat",
      // "icon-size": [20, 20],
    }
});

I can add other marker like circle:
  map.addLayer({
    id: "marker-circle",
    type: "circle",
    source: "datas",
    paint: {
      "circle-radius": 4,
      "circle-color": "rgb(0, 0, 0)",
    },
  });


text:
Q: Stop webview from loading and return to previous page I want to stop webview from loading a url when its starts with google.com from example and return back to default page[1. page].
In my webview client below it is not returning back to first page thougth the condition in should override method is good.
public class myWebClient extends WebViewClient
        {
            @Override
            public void onPageStarted(WebView view, String url, Bitmap favicon) {
                // TODO Auto-generated method stub
                super.onPageStarted(view, url, favicon);
                // view.setVisibility(View.GONE);
                rlChargement.setVisibility(View.VISIBLE);
                progresswheel.spin();
            }
            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                // TODO Auto-generated method stub
                // view.setVisibility(View.GONE);
                System.out.println("BROWSER URL : "+url);
                //Recherche sans filtre
                if (url.equalsIgnoreCase("http://www.google.com")){
                    System.out.println("INVALID");
                    web.clearCache(true);
                    ActToast.message="error message";
                    startActivity(new Intent(me, ActToast.class));
                    rlChargement.setVisibility(View.GONE);
                    progresswheel.stopSpinning();
                    view.stopLoading();
                    web.clearHistory();
                }

                view.loadUrl(url);
                return true;
            }
            @Override
            public void onPageFinished(WebView view, String url) {
                // TODO Auto-generated method stub
                super.onPageFinished(view, url);
                // animate(view);
                // view.setVisibility(View.VISIBLE);
                rlChargement.setVisibility(View.GONE);
                progresswheel.stopSpinning();
            }
            public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
                web.loadUrl("file:///android_asset/onreceivingerror.html");
            }
        }

A: You may want to override WebView.goBack():
  @Override
  public void goBack() {
    WebBackForwardList temp = copyBackForwardList();
    for (int i=0; i<temp.getSize(); i++) {
      WebHistoryItem item = temp.getItemAtIndex(i);
      // do whatever you want here...
    }

    // do whatever you want here...
    super.goBack();
  }


text:
Q: Get min value of a class reference field from a list of class references in R R Beginner here.
I have a list of class references. Each class has a field, "x". I want to find the class reference which has the lowest "x" in the list.
In python I would do this:
return min(item.x for item in myList)

I'm not sure if there is specific terminology for the type of statement above (if someone knows I would like to know), but is there are way of doing a similar type of thing in R ?
If not, what would be the best way to achieve this in R ?
** Edit re. Justins comment
Here is how the list is created ..
mylist <- list()
for (i in 1:10){
    mylist <- c(mylist, MyClass$new())
}

where:
MyClass <- setRefClass("MyClass",
                        fields = list(x = "numeric"),
                        methods = list(
                           initialize = function(){
                               x <<- sample(0:100, 1)
                           }
                        )
)

Many thanks

A: If you want to get to the entire instance of MyClass with the lowest value of x, as opposed to just the minimum value of x (you seem to be looking for the former), consider using which.min in something like the following:
mylist[[which.min(lapply(mylist, function(myClass) myClass$x))]]

A: Your list is just a list which can be accessed using its named components:
> mylist[[1]]$x
[1] 66
>

so the answer in my comment will work:
> min(unlist(lapply(mylist, function(y) y$x)))
[1] 20

I'll leave the details to someone who knows R's OO better than I do...


text:
Q: Fresh eyes needed with Apigee API and Node.js I have just started building my first API through API Management tool and I'm having some problems I'm hoping you can help me with.
My main goal is to have this API work with my mobile app and the Usergrid BAAS by creating calls to the API that link to external Javascript files I have uploaded. My experience so far is that my code worked the first day I tried it, but that exact same code starting breaking the next day, this is very confusing.
PS- I upload the RemoteController.js file as a Node type
Here is my very simple code, I hope you help me spot the issues causing the errors
Test Links:
http://jerryhamby-test.apigee.net/vdex-baas/hello
http://jerryhamby-test.apigee.net/vdex-baas/helloworld
============= my server-usergrid.js code ===========
var argo = require('argo');
var express = require('express');
var usergrid = require('usergrid');
var fs = require('fs');
fs.readFileSync('./RemoteController.js','utf8');

var app = express();
app.use(express.logger('dev'));
app.use(express.bodyParser());
app.use(app.router);

var proxy = argo()
    .target('https://api.usergrid.com')
    .build();

app.get('/hello', function(req, res) {
    res.send('Hello from Express2');
});

app.get('/helloworld', function(req, res) {
  res.setHeader("Access-Control-Allow-Origin","*");
  RemoteController.helloWorld(req, res);
});

app.all('*', proxy.run);
app.listen(3000);

============= my RemoteController.js code ===========
function RemoteController() {
}

var client = new usergrid.client({
    orgName:'myOrg',
    appName:'sandbox',
    logging: true, //optional - turn on logging, off by default
    buildCurl: true
});

// test of helloworld
RemoteController.helloWorld = function(req, res) {
        res.send('RemoteController inside helloWorld');
};

============= the error I get when calling RemoteController.helloWorld ===========
at /organizations/jerryhamby/environments/test/apis/vDex-BaaS/server-usergrid.js:35
(anonymous) at /node_modules/express/lib/router/index.js:164 (callbacks) at
/node_modules/express/lib/router/index.js:138 (param) at
/node_modules/express/lib/router/index.js:145 (pass) at
/node_modules/express/lib/router/index.js:90 (anonymous) at
/node_modules/express/lib/router/index.js:33 (router) at
/node_modules/express/node_modules/connect/lib/proto.js:193 (next) at
/organizations/grangaswamy/environments/test/apis/apigee-aws/node_modules/express/node_modules/connect/lib/middleware/multipart.js:97 (multipart) at
/organizations/grangaswamy/environments/test/apis/apigee-aws/node_modules/express/node_modules/connect/lib/middleware/bodyParser.js:64 (anonymous) at
/node_modules/express/node_modules/connect/lib/middleware/urlencoded.js:41 (urlencoded) at
/organizations/grangaswamy/environments/test/apis/apigee-aws/node_modules/express/node_modules/connect/lib/middleware/bodyParser.js:62 (anonymous) at
/node_modules/express/node_modules/connect/lib/middleware/json.js:42 (json) at
/organizations/grangaswamy/environments/test/apis/apigee-aws/node_modules/express/node_modules/connect/lib/middleware/bodyParser.js:60 (bodyParser) at
/node_modules/express/node_modules/connect/lib/proto.js:193 (next) at
/node_modules/express/node_modules/connect/lib/middleware/logger.js:158 (logger) at
/node_modules/express/node_modules/connect/lib/proto.js:193 (next) at
/node_modules/express/lib/middleware.js:30 (expressInit) at
/node_modules/express/node_modules/connect/lib/proto.js:193 (next) at
/node_modules/express/node_modules/connect/lib/middleware/query.js:45 (query) at
/node_modules/express/node_modules/connect/lib/proto.js:193 (next) at
/node_modules/express/node_modules/connect/lib/proto.js:201 (anonymous) at
/node_modules/express/node_modules/connect/lib/connect.js:65 (app) at
/Users/Apigee/src/noderunner/target/checkout/node10/node10src/src/main/javascript/io/apigee/trireme/node10/node/events.js:98 (anonymous) at
/Users/Apigee/src/noderunner/target/checkout/node10/node10src/src/main/javascript/io/apigee/trireme/node10/trireme/adaptorhttp.js:509 (anonymous) at
/Users/Apigee/src/noderunner/target/checkout/node10/node10src/src/main/javascript/io/apigee/trireme/node10/node/domain.js:183 (anonymous) at
/Users/Apigee/src/noderunner/target/checkout/node10/node10src/src/main/javascript/io/apigee/trireme/node10/node/domain.js:123 (anonymous) at
/Users/Apigee/src/noderunner/target/checkout/node10/node10src/src/main/javascript/io/apigee/trireme/node10/trireme/adaptorhttp.js:508 (anonymous) at
/Users/Apigee/src/noderunner/target/checkout/node10/node10src/src/main/javascript/io/apigee/trireme/node10/trireme/adaptorhttp.js:578 (anonymous)

A: Each node module (file ~= module) has it's own context.  You can export variables from that context and require them into your context.
Try this:
============= my server-usergrid.js code ===========
var argo = require('argo');
var express = require('express');
var RemoteController = require('./RemoteController');

var app = express();
app.use(express.logger('dev'));
app.use(express.bodyParser());
app.use(app.router);

var proxy = argo()
    .target('https://api.usergrid.com')
    .build();

app.get('/hello', function(req, res) {
    res.send('Hello from Express2');
});

app.get('/helloworld', function(req, res) {
  res.setHeader("Access-Control-Allow-Origin","*");
  RemoteController.helloWorld(req, res);
});

app.all('*', proxy.run);
app.listen(3000);

============= my RemoteController.js code ===========
var usergrid = require('usergrid');

function RemoteController() {
}

var client = new usergrid.client({
    orgName:'myOrg',
    appName:'sandbox',
    logging: true, //optional - turn on logging, off by default
    buildCurl: true
});

// test of helloworld
RemoteController.helloWorld = function(req, res) {
        res.send('RemoteController inside helloWorld');
};

module.exports = RemoteController;


text:
Q: When clicking selected radiobutton it goes error I am going to make a simple app of collecting people's personal information. But now i have some problem of radio button.I want to add selected radiobutton values to sql.
Here is the code.
MainActivity:
public void add(View view){
    EditText fn  = (EditText)findViewById(R.id.first_name);
    EditText ln   = (EditText)findViewById(R.id.last_name);

    first_name=fn.getText().toString();
    last_name =ln.getText().toString();

    radio_group=(RadioGroup)findViewById(R.id.radio_gender);
     String gender=    ((RadioButton)this.findViewById(radio_group.getCheckedRadioButtonId())).getText().toString();

    pf.execSQL("INSERT INTO Persone VALUES('"+first_name+"','"+last_name+"','"+gender+"');");
}

A: You can somehow compare the Radio Button methods with the switch case.
Here is an example of how your code could look like:
public void onRadioButtonClicked(View view) {
    // Is the button now checked?
boolean checked = ((RadioButton) view).isChecked();

// Check which radio button was clicked
switch(view.getId()) {
    case R.id.radio_pirates:
        if (checked)
            // Pirates are the best
        break;
    case R.id.radio_ninjas:
        if (checked)
            // Ninjas rule
        break;
}
}

So, practically you need to specify what happens when a specific Radio Button from your Radio Group is selected.
If you want a more detailed // to the point answer let me know in a comment and I will try to write the code you need using your Main Activity.


text:
Q: Unable to get value in  field using this.val() or this.attr('value') I am trying to get values of a number of input fields in a fieldset tag. But the $(this).val() or $(this).attr('value') is returning the old value of the field instead of the new value updated by the user. Below is the html code:
<fieldset id="fieldset_id">

        <input type="text" input_id="1" value="aaa_1">

        <input type="text" input_id="2" value="aaa_2">

</fieldset>

and below is the code which is executed after the user updates the input field and presses the "save" button:
$('#fieldset_id').find("input").each(function(){
    idsArray.push($(this).attr('input_id'));
    newValues.push($(this).val());
});

Now, here is the use case:

*

*The current values of the input fields are aaa_1 and aaa_2 respectively.

*The user updates the value of aaa_1 to aaa_111 and presses the save button.

*On pressing the save button, the code above is executed.

The values in newValues array are aaa_1 and aaa_2 instead of aaa_111 and aaa_2.

A: You need to clear array before pushing values.
Write:
idsArray = newValues = [];
$('#fieldset_id').find("input").each(function(){
    idsArray.push($(this).attr('input_id'));
    newValues.push($(this).val());
});

A: Your Arrays are not defined,
define it like this,
var idsArray = [], newValues= [];

A: Try this
HTML
<form id="fieldset_id">

        <input type="text" input_id="1" value="aaa_1"/>

        <input type="text" input_id="2" value="aaa_2"/>

    <button>Save</button>
</form>

Script
$('button').on('click',function(){
var idsArray = [], newValues= [];
$('#fieldset_id').find("input").each(function(){
    idsArray.push($(this).attr('input_id'));
    newValues.push($(this).val());
    console.log(idsArray, newValues)
});
});

DEMO


text:
Q: How to use quatifiers (* or +) in lookbehind regex? I'm learning regex with lookaround (lookbehind and lookahead) feature but I cannot use .* or .+ quantifiers in lookbehind (but I can on lookahead).
The regex I'm trying to fix is the following:
(?<!yellow.*)blue(?=.*brown)

The idea is to match lines that don't have yellow but has blue only if brown exists after blue. Here are some samples:
yellow blue brown                    // shouldn't match
f blue brown                         // should match
sdff blue brown                      // should match
asdf  f blue c                       // shouldn't match
yellow blue fblue b f brown          // shouldn't match

Here is my test:
http://regex101.com/r/fY4kI9/5
The error I get is:

. * Lookbehinds need to be zero-width, thus quantifiers are not
  allowed

Do you know how I can fix that?

A: You can use this regex without using variable length lookbehind but still getting the same functionality:
.*yellow.*(*SKIP)(*F)|^.*\bblue\b(?=.*brown).*$

Working Demo


text:
Q: How to execute kernel command from Front End? Documentation for Yuri E. Kandrashkin's OptionsExplorer package says to add the following menu commands in MenuSetup.tr:
   Item["Options &Explorer", KernelExecute[ToExpression["OptionsExplorer[]"]],
   MenuKey["o", Modifiers->{Control,Command}], MenuEvaluator->Automatic]

And I want to accomplish the same thing by a corresponding FrontEnd`AddMenuCommands... expression in an Autoload`PacletManager`Configuration`FrontEnd`init.m.
But I don't find any KernelExecute function.
How to do it?

A: You can add the menu command to your Insert menu using AddMenuCommands in the following manner.  (These modifications will only persist for the current front end session.)
First a demo function, just creating a dialog:
FrontEndExecute[FrontEnd`AddMenuCommands["DuplicatePreviousOutput",
  {Delimiter, MenuItem["CreateDialog &Demo",
    FrontEnd`KernelExecute[CreateDialog[{TextCell["Click OK to close"],
       DefaultButton[]}]],
    MenuKey["D", Modifiers -> {"Control", "Shift"}],
    System`MenuEvaluator -> Automatic]}]]

(Note the required context specification for MenuEvaluator.)
This version will run OptionsExplorer[]
FrontEndExecute[FrontEnd`AddMenuCommands["DuplicatePreviousOutput",
  {Delimiter, MenuItem["Options &Explorer",
    FrontEnd`KernelExecute[ToExpression["OptionsExplorer[]"]],
    MenuKey["O", Modifiers -> {"Control", "Shift"}],
    System`MenuEvaluator -> Automatic]}]]


text:
Q: How to parse object id from object I have two type of projects, Java and Node js
The java project returns the details with ObjectId
{
        "timestamp": 1491806328,
        "machineIdentifier": 9737042,
        "processIdentifier": 6393,
        "counter": 1399563,
        "date": 1491806328000,
        "time": 1491806328000,
        "timeSecond": 1491806328
    }

In node Js I am using the Mongoose. Now I dont know how to parse this to nodejs equalant ObjectId.
Edit :
Code I tried,
var mongoose = require("mongoose");
var idToParse = {
            "timestamp": 1491806328,
            "machineIdentifier": 9737042,
            "processIdentifier": 6393,
            "counter": 1399563,
            "date": 1491806328000,
            "time": 1491806328000,
            "timeSecond": 1491806328
        };

    mongoose.Schema.Types.ObjectId(idToParse);

it returns Undefined.

A: If you are using Java , try to make use of Jackson to map POJO to json and have a custom serializer for Object Id field so that Jackson understands that it needs to give String equivalent of ObjectId.
Custom serializer will look like this :
public class ObjectIdSerializer extends JsonSerializer<ObjectId>{
   @Override
   public void serialize(ObjectId id, JsonGenerator jgen, SerializerProvider provider)
        throws IOException, JsonProcessingException {

    if(id == null){
        jgen.writeNull();
    }else{
        jgen.writeString(id.toString());
    }
}}

and you can annotate ObjectId field in POJO like :
    @Id
    @JsonSerialize(using = ObjectIdSerializer.class)
    private ObjectId id;

A: Found the Answer for this.
function hex(length, n) {
 n = n.toString(16);
 return (n.length===length)? n : "00000000".substring(n.length, length) + n;
}

var idToParse = {
            "timestamp": 1491806328,
            "machineIdentifier": 9737042,
            "processIdentifier": 6393,
            "counter": 1399563,
            "date": 1491806328000,
            "time": 1491806328000,
            "timeSecond": 1491806328
        };

var idString = hex(8,idToParse.timestamp)+hex(6,idToParse.machineIdentifier)+hex(4,idToParse.processIdentifier)+hex(6,idToParse.counter);


text:
Q: Django Schedule/run tasks dynamically at particular time periodically from user's order in app (without celery) I am creating a Django App where the user can schedule some tasks to happen at a particular time.
for example. in google calendar we tell google what we will be doing tomorrow and then at right time it sends us a notification.
similarly here I want it to be flexible, for instance, the user can tell Django the time and function to run.
Django will wait for the time and then run the function.
like he said turn off lights at 12 pm
then Django will do it.
or for example:-
user says remind me to go to the gym in 30 minutes
And then after 30 minutes, he gets a notification.
Actually the tasks are added dynamically so we can't hardcode them at first.
code:-
skills.py # all the functions defined by user are imported in it
# for example take this task
def turn_off_light(room, id, *args, **kwargs):
    # turned off light using python (your logic)
    print(f"light no {id} is turned off!")

there's a Django model known as Function in which this function is stored and the user can access it easily.
I want users to select this function within the application and also give parameters and time and Django will run it at that time!
In short what I need is that the user from within the application is able to set the time of a function(or task) to run at a particular time(maybe periodically or once or maybe in the situation) and Django runs it on that particular time.

Note: user will also give args and kwargs(I am taking care of that). All I need is Django run the function with those args and kwargs.

(only Django method without celery or something will be appreciated)
Thanks!

A: Without Celery and using Django the best way to do is to create custom django-admin commands with Cron
For example :

*

*Create customer command called calendar_routine.py

*Create a cron schedule to call your function from your server at a given time

Otherwise there is no way to do it in pure Python/Django


text:
Q: How to preserve setTimeout parameter value until execution? I have a bit of code that executes on keypress and saves data to a database as the user types.
I added a setTimeout function with a clearTimeout infront of it so not EVERY single character the user enters is sending out an Ajax request to save data.
While the setTimeout works great for one input field , if the user decides to switch input fields quickly (before the setTimeout delay is up) the parameter passed to the callSomeAjax changes before the function is executed.
Simplified version of what's happening...
var a = 1; //some user data

//function to call ajax script to save data to database
function callSomeAjax(a)
{
   console.log(a);
}

setTimeout(function(){callSomeAjax(a)},1000); //executes callSomeAjax after 1 second delay

a=3; //change user data before callSomeAjax executes

// Result of console.log is 3, not 1 like I want it to be...

Code on fiddle
Any ideas?

A: Newer browsers will let you pass the argument to setTimeout, and retrieve it in the callback.
setTimeout(function(a){
    return callSomeAjax(a);
}, 1000, a);

Or you could bind it to the function
setTimeout(function(a){
    return callSomeAjax(a);
}.bind(null, a), 1000);

Aside from those, you'd need to create the setTimeout callback in a new scope with the value.
function callbackWithValue(a) {
    return function() {
        return callSomeAjax(a);
    };
}

setTimeout(callbackWithValue(a), 1000);

Or if you already have the function as you do, and there's nothing else to pass, then you can make it more generic...
function callbackWithValue(fn) {
    var args = [].slice.call(arguments, 1);
    return function() {
        return fn.apply(null, args);
    };
}

setTimeout(callbackWithValue(callSomeAjax, a), 1000);

This last one is shows the beginnings of a .bind() function. It can be further expanded to allow the binding of this and the concatenation of additional arguments passed after the bound one.

A: The problem is that setTimeout doesn't run the function passed in until 1 second has passed.  What that does happen a has changed, so when callSomeAjax(a) is ran, a is at its new value.
You need to capture (in a closure) the value of a before calling setTimeout.
var a = 1;

function show(a) {
    console.log(a);
}

(function(a){
    setTimeout(function () {
        show(a)
    }, 1000);
}(a));

a = 3;

DEMO: http://jsfiddle.net/U59Hv/2/

A: This works and can be also used within loop.

var x = "OK";
setTimeout(alertOK.bind(null,x), 3000);
x = "Would be WRONG";
console.log("before timeout:", x);

function alertOK(x){
 console.log("after timeout:",x);
}

It might not be better answer than the accepted one, just different idea. Since function is not created, it can also be used in loops.
In my opinion, code is a bit more readable this way.


text:
Q:  convert to single-spa will make directives in the index.html disappear I have an angular.js app where the index.html looks something like with ng-app in the  tag

      <custom-navbar-directive></custom-navbar-directive> //angular js directive
      <custom-loader></custom-loader>

I was following the steps in the single-spa angular.js guide. I removed the ng-app from  tag and added the following in my app.js
System.register([], function (_export) {
  return {
    execute: function () {
      _export(
        window.singleSpaAngularjs.default({
          angular: angular,
          mainAngularModule: "app",
          uiRouter: true,
          preserveGlobal: false,
        })
      );
    },
  };
});

Also I did the import map and singleSpa.registerApplication  steps in the index.html
My issue is now the content is rendering but the <custom-navbar-directive> and <custom-loader>  are missing. I added them inside the index.html since they are commonly used in each html template.
When I inspect and checked the rendered html I noticed that they are outside the loaded single spa angularjs app
<custom-navbar-directive></custom-navbar-directive>
<custom-loader></custom-loader>

I guess since they are directives if those are inside the
 then it should render.
Any idea how to solve this?


text:
Q: Ionic http session is lost after about 5 seconds. How to enable KeepAlive on ionic http post? I have an Ionic app that calls a website were a session is being created for the app. I can successfully issue the same call to the server 3 or 4 times in about 5 seconds and the server still recognizes the session, however after that a new session is created. Could anyone have an idea why this is happening?
btw: the session timeout on the server is 1 minute.
I am using a post operation as follows:
this.http.post(ProductDataProvider.Server+'/mobile/AddItem',{itemstr:itemid},{ withCredentials:true})...
Update 1: After searching it seems that I need to enable connection keep alive which might solve the problem. The issue is that I could not find a KeepAlive method or something to that effect in the documentation of Ionic Http.
Update 2: I have a way to solve this, assuming I could send the session ID to the Ionic mobile app, I could not find a way to set the session id in the post request, which i think should solve the problem.