Is DNS propagation still slow?

Question: I've been told to assume it takes as long as 48 hours for a DNS change to propagate throughout the entire Internet, because some DNS servers cache their entries for longer than my TTL.
However, for years and across ISPs and domains, every time I've made a DNS change I see the effects within a couple of hours.
Is it still true that I need to assume a full two days for everyone to see my changes?
Comment: In particular, web crawlers tend to cache DNS for a very long time.  I've seen the Baidu spider still hitting the old address three weeks after the TTL expired.  I've never seen the Googlebot take more than a couple of days but that's on TTLs of 15 minutes.
Comment: DNS doesn't propagate. There are issues relating to caching and TTL but that's not propagation.
Comment: They DO. There are issues related to caching and the common word for it is _propagation_. ;)
Answer: It takes until the last cache holding the old data expires and that server fetches the new data.
You have limited control over that with the TTL value on the records, but there are ISPs who disregard cache times, cache everything for the SOA expire or refresh time, assign their own arbitrary value (AOL used to be famous for caching everything for 1 day regardless of any other directives), and probably a few broken implementations that always re-query the data.
Bottom line: It takes as long as it takes.
48 hours is a good rule of thumb that has served the internet well.
Comment: You'd be surprised how many people in the world still use dial-up ISPs. In any case, blatantly violating the DNS RFCs by ignoring TTLs is still common enough that I take it into account when making DNS changes and decommissioning old services. I always suggest to others that they do the same, in the spirit of "Don't Break The Internet (even if the people it would break for are idiots)".
Comment: AOL is no longer a major ISP. Is disregarding TTL in widespread practice by current network operators?
Answer: Yes, and in some cases it can be much longer.
Answer: I think it's a 80/20 problem. Don't spend 80% of your energy trying to figure out how 20% of Internet users will get to your site. Stick to RFCs and you've done your job.  The rest is beyond your control anyway.

Is DNS propagation still slow?


if my iOS app freezes the entire phone, is this considered a bug in the OS itself?

Question: I am working on an iOS app where I am using AVPlayer to play different mp4 videos. Most of the times it works fine. except sometimes my app completely freezes the phone. I haven't been able to catch it at what place this happens but I think it usually happens right after this line. I verified this by placing a bunch of NSLog where I print the [[NSDate date] timeIntervalSince1970] :
mylayer =[AVPlayerLayer playerLayerWithPlayer:myplayer];

The freeze happens for a few seconds (sometimes much longer).
Even if I press home button or lock button, the phone is unresponsive.
I have to end up pressing the lock button for about 6-10 seconds which hard restarts the entire phone.
Note that the CPU and memory usage doesn't spike during this.
I understand my code might be buggy and all but shouldn't the OS be intelligent enough to not let a single app completely freeze the entire phone? Would this be considered an OS bug? If so, I might log a DTS with Apple.

****EDIT: added code****
Note the comment which says "// this is the line which freezes"
dispatch_queue_t LOADQUEUE = dispatch_queue_create("com.yolo.LOADQUEUE", DISPATCH_QUEUE_CONCURRENT);
        dispatch_async(LOADQUEUE, ^{
            AVURLAsset *avAsset = [[AVURLAsset alloc] initWithURL:url options:nil];

            NSLog(@"current time 4: %f",[[NSDate date] timeIntervalSince1970]);
            if ([avAsset tracksWithMediaType:AVMediaTypeVideo] && [avAsset tracksWithMediaType:AVMediaTypeVideo].count>0) {
                NSLog(@"current time 4.5: %f",[[NSDate date] timeIntervalSince1970]);
                CGSize size = [[[avAsset tracksWithMediaType:AVMediaTypeVideo] objectAtIndex:0] naturalSize];
                NSLog(@"current time 5: %f",[[NSDate date] timeIntervalSince1970]);
                CGRect r = self.topHeader.frame;
                r.size.height=((size.height*self.view.frame.size.width)/size.width)+self.topheaderBottomView.frame.size.height+self.topheadertopview.frame.size.height+self.itemTitle.frame.size.height;
                howMuchToScrollToShowCommentButton=r.size.height;

                dispatch_async(dispatch_get_main_queue(), ^{

                    self.topHeader.frame=r;
                    [UIView animateWithDuration:0 animations:^{

                        [self.mytableview setTableHeaderView:self.topHeader];

                    }completion:^(BOOL finished) {

                        NSArray *keys = @[@"playable"];
                        NSLog(@"current time 6: %f",[[NSDate date] timeIntervalSince1970]);
                        [avAsset loadValuesAsynchronouslyForKeys:keys completionHandler:^{
                            dispatch_async(dispatch_get_main_queue(), ^{
                                NSLog(@"current time 7: %f",[[NSDate date] timeIntervalSince1970]);
                                AVPlayerItem *newItem = [[AVPlayerItem alloc] initWithAsset:avAsset];
                                if (!myplayer) {
                                    myplayer = [[AVPlayer alloc]initWithPlayerItem:newItem];
                                } else {
                                    [myplayer replaceCurrentItemWithPlayerItem:newItem];
                                }
                                NSLog(@"current time 7.5: %f",[[NSDate date] timeIntervalSince1970]);
                                [myplayer addObserver:self forKeyPath:@"status" options:(NSKeyValueObservingOptionNew | NSKeyValueObservingOptionInitial) context:nil];
                                [myplayer addObserver:self forKeyPath:@"rate" options:(NSKeyValueObservingOptionNew | NSKeyValueObservingOptionInitial) context:nil];
                                [[NSNotificationCenter defaultCenter] addObserver:self
                                                                         selector:@selector(playerItemDidReachEnd:)
                                                                             name:AVPlayerItemDidPlayToEndTimeNotification
                                                                           object:[myplayer currentItem]];
                                myplayer.actionAtItemEnd = AVPlayerActionAtItemEndNone;
                                NSLog(@"current time 7.6: %f",[[NSDate date] timeIntervalSince1970]);
                                mylayer =[AVPlayerLayer playerLayerWithPlayer:myplayer]; // this is the line which freezes
                                NSLog(@"current time 7.7: %f",[[NSDate date] timeIntervalSince1970]);

                                [playerView.layer addSublayer:mylayer];
                                mylayer.videoGravity = AVLayerVideoGravityResize;
                                [mylayer setFrame:playerView.bounds];
                                [myplayer seekToTime:kCMTimeZero];
                                NSLog(@"current time 8: %f",[[NSDate date] timeIntervalSince1970]);
                            });
                        }];

                    }];
                });
            } else {
                NSLog(@"ITEM doesn't exist");
            }
        });

Output:
Note the 21 second break between time 7.6 and 7.7 :
2016-06-04 01:27:20.853 XYZ[402:49072] current time 7: 1465018040.853897
2016-06-04 01:27:20.875 XYZ[402:49072] current time 7.5: 1465018040.875220
2016-06-04 01:27:20.875 XYZ[402:49072] current time 7.6: 1465018040.875871
2016-06-04 01:27:41.841 XYZ[402:49072] current time 7.7: 1465018061.841419
2016-06-04 01:27:41.841 XYZ[402:49072] current time 8: 1465018061.841863

Edit 2:
I paused the app in xcode and looked at what the threads were doing on the left. Here's a screenshot:
Answer: This could be a symptom of debugging and running through XCode.  You're right, normally you should always be able to hit the Home button and exit the application.
Edit your scheme and change from Debug to Release.  Run a build once through Xcode.  Kill the app, then Launch it without Xcode from the Home screen of the device.
Comment: I have noticed my app freeze the OS even when not in debug mode and not connected to my mac. this especially seems to happen when my internet is slow (when I am on train and my network is shitty)
Comment: If you could update your question and include more code related to the action that causes the problem we might be able to help.  It sounds like something on the main thread is locking everything up.
Comment: thanks for your help, I just added my code and NSLog output.
Comment: is "mlayer" an @property (atomic, strong) ?  If not, that might help.  This looks like a dead lock of some sort.
Comment: It's defined in the interface as an instance variable. defined as:

AVPlayerLayer *mylayer;
Comment: still same problem even if i change it to a @property
Comment: I added a screenshot of xcode paused when the freeze occurs
Comment: Yea, it's definately a dead lock waiting on something else to finish with the CALayer but obviously never happens.. The only stuff in your code touching the UI is the UIAnimation.. Maybe that has something to do with it.. Try not doing that to test it. edit: first try adding a slight duration instead of "0"
Comment: but the problem comes after the animation is already done because the problem is inside the completion block.


Help visualizing solutions to the (1D) wave equation.

Question: I know that the one-dimensional wave equation can be written as $$ \frac{\partial^2 u}{\partial t^2} = c^2 \frac{\partial ^2 u}{\partial x^2}$$ and has solutions of the form $$ u = F(x+ct) + G(x-ct)$$
I'm having trouble developing a proper intuition about the meaning of the solution, though. I superficially understand that it's the sum of two functions "travelling" in different directions with time, but that doesn't help me be able to really visualize what solutions look like. More specifically, I'd like to develop an intuitive or visual understanding of what solutions to the wave equation have in common, and what separates them from functions that aren't solutions.
Comment: For starters, do you feel you intuitively understand the cases $F = 0$ or $G = 0$?
Comment: A good place to continue is to consider the IVP with $u(0,x)=f(x),u_t(0,x)=g(x)$ and rewrite the solution in terms of $f$ and $g$. This is not very hard to do (some basic linear algebra, now that you have the form of the general solution) but it is helpful.
Comment: @AndrewD.Hwang , not really.
Comment: The case $F=0$ or $G=0$ gives solutions to the transport equation. These are easy to visualize because there is no "interaction" going on.
Comment: Am I correct in thinking that for F = 0, the solution is *literally* any function whose waveform moves to the right at c x-units per t-unit? So, a constant function (say, u = 1) would still count as a wave?
Comment: @SquarerootSquirrel: Yes, precisely. :) In other words, you can make a real-time analog movie by drawing your favorite graph on a piece of stiff paper and dragging it horizontally past your eyes at constant speed. (For a constant, both second partials vanish identically.) To get the general picture, you just have to imagine linear superposition of leftward- and rightward-moving solutions.
Answer: In the hope an animation is worth a thousand words: The blue wave $F$ travels left, the red wave $G$ travels right. Their sum is magenta. Both $F$ and $G$ were chosen to be spatially periodic so the loop would be smooth.
Comment: What did you use to create this animation?
Comment: This works really well, thanks! Is there a similar visual example of a function you could give that depends on both x and t, but does not satisfy the wave equation?
Comment: @mathematician: [ePiX](http://mathcs.holycross.edu/~ahwang/epix/ePiX.html). Squarerootsquirrel: "Anything not of this form," such as a single graph moving to the right but whose speed varies ($u = G(x - v(t))$ for some differentiable function $v$ with $v'$ non-constant), or $u = \sin(xt)$, or....


How can I know if a json body has content?

Question: I have a filter to do some code if the body has body or not, because the enrich mediator cant work with a null body, but I dont know the expression
I tried boolean($body) but doesn't work
<filter regex="default_regex" source="boolean($body)">
<then>
    <enrich>
       <source clone="true" type="body"/>
       <target property="payload" type="property"/>
    </enrich>
 </then>
 <else>
    <log level="full"/>
 </else>

Answer: Could you update the regex to true and give it a try.
<filter regex="true" source="boolean($body)">
<then>
    <enrich>
       <source clone="true" type="body"/>
       <target property="payload" type="property"/>
    </enrich>
 </then>
 <else>
    <log level="full"/>
 </else>

And if it doesn't get the json payload, try assigning it to a property and do filter.
<property name="JsonBody" expression="json-eval($.)/>
<filter regex="true" source="boolean($ctx:JsonBody)">
<then>
    <enrich>
       <source clone="true" type="body"/>
       <target property="payload" type="property"/>
    </enrich>
 </then>
 <else>
    <log level="full"/>
 </else>

Thanks


ContentProvider is not returning data

Question: So I have this simple method for getting all words from the dictionary:
<code>public static void getFromDictionary(Activity a) {
        System.out.println("Inside getFromDictionary");
        ContentResolver resolver = a
                .getContentResolver();
        String[] projection = new String[] { UserDictionary.Words._ID,
                UserDictionary.Words.WORD, UserDictionary.Words.FREQUENCY };
        Cursor cursor = resolver.query(UserDictionary.Words.CONTENT_URI,
                projection, null, null, null);
        while (cursor.moveToNext()) {
            String word = cursor.getString(1);
            Log.e("DICCIONARIO", word);

        }
    }
</code>
Well, I tried it in different phones and the while bucle won't enter (there is nothing in the cursor).
What am I doing wrong?
Comment: Are you sure there are words in the user dictionary?
Comment: I don't know! how do I check? I tried with 3 different phones...
Comment: Go into the Settings on your phone, go to Language & Input, then go to Personal Dictionary.  You can add words there.
Answer: Try to limit your projection list by only one item as UserDictionary.Words._ID
or put null as projection parameter

ContentProvider is not returning data


recyclerview item mishap(undesirable behaviour) in android studio

Question: I have a recycler view with a list of items and each of those items have checkboxes attached to them. When a checkbox is checked, it behaves properly and there is no problem with unwanted items getting checked. But when a checked item is deleted, then the unwanted item gets checked.
My Adapter Class :
public class TaskAdapter extends RecyclerView.Adapter<TaskAdapter.TaskHolder> {
private static List<Task> tasks = new ArrayList<>();
private static OnItemClickListener listener;
private static TaskAdapter adapter = new TaskAdapter();

@NonNull

@Override
public TaskHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
    View itemView = LayoutInflater.from(parent.getContext())
            .inflate(R.layout.task_item, parent, false);
    return new TaskHolder(itemView);
}

@Override
public void onBindViewHolder(@NonNull TaskHolder holder, int position) {
    Task currentTask = tasks.get(position);
    holder.a_tname.setText(currentTask.getTname());
    holder.a_tdate.setText(currentTask.getTDate());
    holder.a_ttime.setText(currentTask.getTTime());
    holder.a_tprior.setText(currentTask.getTprior());
    holder.bind(tasks.get(position));
   holder.bind2(tasks.get(position));

}
@Override
public int getItemCount() {
    return tasks.size();
}
public void setTasks(List<Task> tasks) {
    this.tasks = tasks;
    Collections.sort( tasks, Task.comparepriority);
    notifyDataSetChanged();
}
public Task getTaskAt(int position){
    return tasks.get(position);
}

 class TaskHolder extends RecyclerView.ViewHolder  {
    private final TextView a_tname;
    private final TextView a_tdate;
    private  final TextView a_ttime;
    private final TextView a_tprior;
    ImageView priorityIndicator;
    CheckBox checkbox;

    public TaskHolder(View itemView) {
        super(itemView);
        a_tname = itemView.findViewById(R.id.a_tname);
        a_tdate=itemView.findViewById(R.id.a_tdate);
        a_ttime = itemView.findViewById(R.id.a_ttime);
        a_tprior = itemView.findViewById(R.id.a_tprior);
        priorityIndicator = itemView.findViewById(R.id.priorityIndicator);
        checkbox = itemView.findViewById(R.id.checkbox);

        itemView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                int position = getAdapterPosition();
                if(listener!=null&&position!=RecyclerView.NO_POSITION){
                    listener.onItemClick(tasks.get(position));
                }
            }
        });

    }

    private void bind(Task task){
        int drawableId;int red = R.color.red;int yellow = R.color.yellow;int green = R.color.green;
        int color1 = ContextCompat.getColor(a_tprior.getContext(), red);
        int color2 = ContextCompat.getColor(a_tprior.getContext(),yellow);
        int color3 = ContextCompat.getColor(a_tprior.getContext(),green);
        switch(task.t_prior){
            case "1": drawableId = R.drawable.ic_baseline_priority_high_24;
            a_tprior.setTextColor(color1);
            break;
            case "2": drawableId = R.drawable.ic_baseline_priority_middle_24;
            a_tprior.setTextColor(color2);
            break;
            case "3" : drawableId = R.drawable.ic_baseline_low_priority_24;
            a_tprior.setTextColor(color3);
            break;
            default: drawableId = R.drawable.ic_baseline_crop_square_24;
        }
        priorityIndicator.setImageDrawable(ContextCompat.getDrawable(priorityIndicator.getContext(),drawableId));
    }

    public void bind2(Task task){
        final boolean[] checked = {true};
        checkbox.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(checkbox.isChecked()) {
                    String pos = Integer.valueOf(getAdapterPosition()).toString();
                    PreferenceManager.getDefaultSharedPreferences(checkbox.getContext()).edit().
                            putBoolean("checkbox" + pos , checked[0]).apply();
                    Toast.makeText(checkbox.getContext(), "Way to go! Now swipe to delete", Toast.LENGTH_LONG).show();
                }
                else  {
                    checked[0] =false;
                    String pos = Integer.valueOf(getAdapterPosition()).toString();
                    PreferenceManager.getDefaultSharedPreferences(checkbox.getContext()).edit().
                            putBoolean("checkbox" + pos, checked[0]).apply();
                }
            }
        }); String pos = Integer.valueOf(getAdapterPosition()).toString();
        boolean cb = PreferenceManager.getDefaultSharedPreferences(checkbox.getContext()).getBoolean
                ("checkbox" + pos, false);
        checkbox.setChecked(cb);
    }

 }
public interface  OnItemClickListener {
    void onItemClick(Task ta);
}
public void setOnItemClickListener(OnItemClickListener listener){
    this.listener = listener;
}

}

My code to delete in HomeFragment.java -
  new ItemTouchHelper(new ItemTouchHelper.SimpleCallback(0,
            ItemTouchHelper.LEFT | ItemTouchHelper.RIGHT) {
        @Override
        public boolean onMove(@NonNull RecyclerView recyclerView, @NonNull
                RecyclerView.ViewHolder viewHolder, @NonNull  RecyclerView.ViewHolder target) {
            return false;
        }

        @Override
        public void onSwiped(@NonNull  RecyclerView.ViewHolder viewHolder, int direction) {
            int position = viewHolder.getAdapterPosition();
            new AlertDialog.Builder(getActivity())
                    .setMessage("Do you want to delete this task?")
                    .setPositiveButton("Delete", ((dialog, which) ->
                            taskViewmodel.delete(adapter.getTaskAt(viewHolder.getAdapterPosition()))))
                    .setNegativeButton("Cancel", ((dialog, which) -> adapter.notifyItemChanged(position)))
                    .setOnCancelListener(dialog -> adapter.notifyItemChanged(position))
                    .create().show();

        }
    }).attachToRecyclerView(recyclerView);

Edit : I guess the problem is with the code associated with saving the state of the checkbox because the checkbox at a particular item position is checked so when the item is deleted, the below item takes its place and so it gets checked. Suppose item at 2nd position is checked, and I delete that item, then the item at the 3rd position takes its place and so that gets checked. I need to know how to resolve this.May i know what changes should i make to rectify this problem?
Thankyou
Comment: @Danish Nope, it's still not working
Comment: Do you notify change when an item is removed from the list?
Comment: I provide notifyItemChanged(position). I have posted my delete code now
Comment: Use adapter.notifyDataSetChanged()  after your notifyItemChanged(position).
Comment: @Danish It still doesn't work
Comment: the problem is you havent notified your adapter on your positive button.
Comment: Oh, so where should I add that code, because the setPositiveButton() can have only one argument
Comment: add the line in your onswiped after showing dialog box.More specifically after this:create().show()
Comment: @Harshitha you have to use adapter.notifyItemRemoved(position) and you are using lamba funfion in your setPositivebutton so you can add as many lines you want.
Comment: But it shows an error. I used it like this - setPositiveButton ("Delete"..... adapter.getTaskAt(...)), adapter.notifyItemRemoved(position). But it shows an error, the next few lines of code and this turns red
Comment: @Danish can you show how the code is
Comment: If its not confidential then you can upload your xml and your code,i will provide you with solution.
Comment: @Danish may I know which xml and code you're asking, the entire project? I just wanted to know how and where to add the code notifyItemRemoved(position)
Answer: back at the day, there was no delete intuition, now since you're storing the state of whether an item checked or not in SharedPreferences using its position, if you have 3 items where position =2  is checked, and you delete this checked item at pos=2, then the third item would take its place behaving as new item at pos=2, that's why when you delete one, all checked states will get shifted.
I guess there's no option here but to use some identifier in your Task class, where one Task is uniquely identified using this number/string and you use that unique identifier to store the items state in your SharedPreferences as a key.
a quick cheap way to do it is to make Task class behave like how Room database identify its automatic unique int/long identifiers.
the way to do it is by

defining a static int/long counter field in your Task class that identifies how many ids you used so far so to not repeat any id that was taken before (even if it was deleted and not used now)

define a private int/long id field in the Task class, while in the Task class constructor when you're initializing a new Task you would increment the static counter field and use this new value as a value for your private id for your newly created Task.
N.B : you shouldn't increment the static value and assign a new id for every created task if the one you're creating an object for is an old one that you retrieved from SharedPreferences/Database that already have an old id, for that case you might have two constructors one that accepts an old id as paramter and one that increments the taskCounter and get a new id, you might also have two constructors that one calls the other incase you have some other paramteres you're passing to the task object at creation and you want to avoid duplicating code in both constructors.

that way when you're checking status using SharedPreferences for some task, you would use the private id value of Task instead of its position.

your Task class might look like this (in case of two constructors without any additional code in the constructor):
public class Task {
    public static int tasksCounter =0;
    public int taskId ;
    ...
    //constructor for a new Task
    public Task(){
        this.taskId= ++tasksCounter ;
    }
    //constructor for an old Task
    public Task(int oldId){
        this.taskId= oldId ;
    }

your Task class might look like this (in case of two constructors and you want to avoid code dublication):
public class Task {
    public static int tasksCounter =0;
    public int taskId ;
    //you'd call that one if you're creating a completely new Task and it will call
    the other constructor for you
    public Task(){
        Task(++tasksCounter)
    }
    //you'd call that one if you're creating a Task that you already have an id for
    public Task(int id){
        this.taskId= id ;
        //some other code here
    }

and in your adapter when you ask about whether its checked or not it would be like this :
PreferenceManager.getDefaultSharedPreferences(checkbox.getContext()).getBoolean
                ("checkbox" + task.taskId, false);

and when you the checkbox status get changed you'd change its value in preferences likewise using the task.taskId instead of position.
that of course would raise another problem that every time you start your application that static field will get reset to 0 again.
so you should store its value too in sharedpreferences maybe either

when you create a new Task, its value will be incremented so you should store the new value
or
just before the activity or fragment getting destroyed by overriding the method onDestroy() in either the activity or the fragment, you should store the last value it had
and when you start your activity or fragment you need to fetch it from sharedpreferences and assign it to Task.tasksCounter.

N.B : just incase you don't know, you get the value of static field by calling the class it self and you don't need to create a new object of this class to get its value, calling the next code is sufficent to get and edit its value :
Task.tasksCounter

and at the end,
since you have your complex data now (Task class), I would highly suggest to stop using SharedPreferences for storing everything and you start reading and switching to Room Database
Room Database provides you with necessary storing abilities of a Database including :

having an autoincrement identifier without having you worried about their values
storing and getting your data with just one line of code with a simple query instead of calling get with keys a 100 times.

with changing your Task class into an entity that have an autoincrement field you'll be good to go and ready to use Room to store your tasks.
Comment: Thank you so much, I already had the task.id in my Task class, but didn't think of using it this way. This helped a ton!
Answer: I am not much familiar with lambda function so I am sharing how I would have did the same task.I tried this code for my own app and it worked perfectly fine.
Check the below code:
        @Override
        public void onSwiped(@NonNull RecyclerView.ViewHolder viewHolder, int direction) {
            int position = viewHolder.getAbsoluteAdapterPosition();//getAdapterPosition is depreciated, use getAbsoluteAdapterPosition
            AlertDialog.Builder builder = new AlertDialog.Builder(getContext());
            builder.setMessage("Do you want to delete this task?");
          builder.setPositiveButton("Delete",new DialogInterface.OnClickListener() {
              @Override
              public void onClick(DialogInterface dialog, int which) {
    taskViewmodel.delete(adapter.getTaskAt(viewHolder.getAdapterPosition()))
    adapter.notifyItemRemoved(position);
              }
          });
                  builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
                      @Override
                      public void onClick(DialogInterface dialog, int which) {
                          dialog.cancel();
                      }
                  });
                  builder.setOnCancelListener(new DialogInterface.OnCancelListener() {
                      @Override
                      public void onCancel(DialogInterface dialog) {
                   adapter.notifyItemChanged(position);
                      }
                  }).show();

        }
    }).attachToRecyclerView(recyclerView);

Comment: It's still not resolving my checkbox problem. I guess the problem is with the code associated with saving the state of the checkbox because the checkbox at a particular item position is checked so when the item is deleted, the below item takes its place and so it gets checked. Suppose item at 2nd position is checked, and I delete that item, then the item at the 3rd position takes its place and so that gets checked. I need to know how to resolve this, but thanks for your help though
Comment: yes that's the reason if you look at your checkbox code you are saving the state of your checkbox as checked in your shared preference and when you are deleting your recycler view item your checkbox is again set to checked.
Comment: Try making your checkbox public static then access it in your onSwipe and set to true. like this:checkbox.setChecked(false)
Comment: the onSwiped() is in HomeFragment.java and the checkbox is in TaskAdapter.java, they are in two different activities, how do I access it then?
Comment: Make it public static.
Comment: The checkbox is not being identified by Home fragment.java. It shows "cannot resolve symbol checkbox"
Comment: Placing public static Checkbox checkbox in your TaskAdapter class would resolve the issue of cannot resolve symbol checkbox.


Speeding up rsync over smb

Question: I'm backing up a Linux box over SMB to a NAS. I mount the NAS locally and then I rsync a lot of data (100GB or so). I believe it's taking an awfully long time to do it: more than 12 hours. I would expected to be much faster once everything is copied since almost nothing is changed from day to day.
Is there a way to speed this up?
I was thinking that maybe rsync thinks it's working with local hard disks and uses checksum instead of time/size comparisons? But I didn't find a way to force time and date comparisons. Anything else I could check?
Comment: I'd also suggest looking at NFS instead fo SMB - I've noticed (and maybe it's just me) that it's faster tha Samba
Comment: Unfortunately, this NAS doesn't have NFS and for now, I'm stuck with it.
Comment: Check the NAS's capabilities using a port mapper, like nmap.  I've run into several NAS units that ran a native rsync service, even though there was no mention in the documentation, and no mention in the config.
Comment: Please also check this thread ["rsync to NAS copies everything every time"][1]

  [1]: http://serverfault.com/questions/262411/rsync-to-nas-copies-everything-every-time/262424#262424
Comment: Please also check this thread [rsync to NAS copies everything every time][1]

  [1]: http://serverfault.com/questions/262411/rsync-to-nas-copies-everything-every-time/262424#262424
Answer: I think you're having a misunderstanding of the rsync algorithm and how the tool should be applied.
Rsync's performance advantage comes from doing delta transfers-- that is, moving only the changed bits in a file. In order to determine the changed bits, the file has to be read by the source and destination hosts and block checksums compared to determine which bits changed. This is the "magic" part of rsync-- the rsync algorithm itself.
When you're mounting the destination volume with SMB and using rsync to copy files from what Linux "sees" as a local source and a local destination (both mounted on that machine), most modern rsync versions switch to 'whole file' copy mode, and switch off the delta copy algorithm. This is a "win" because, with the delta-copy algorithm on, rsync would read the entire destination file (over the wire from the NAS) in order to determine what bits of the file have changed.
The "right way" to use rsync is to run the rsync server on one machine and the rsync client on the other. Each machine will read files from its own local storage (which should be very fast), agree on what bits of the files have changed, and only transfer those bits. They way you're using rsync amounts of a trumped-up 'cp'. You could accomplish the same thing with 'cp' and it would probably be faster.
If your NAS device supports running an rsync server (or client) then you're in business. If you're just going to mount it on the source machine via SMB then you might as well just use 'cp' to copy the files.
Comment: Ooo! Downvotes! I'd be curious to hear why you downvoted the answer, considering it's technically accurate.
Comment: What behaviour are you seeing that's telling you that it's checksumming the files? The "quick check" behaviour is the default behaviour, so there's no way to "force" it.  If you can't run rsync on the NAS just use 'cp'. It'll be as fast or faster.
Comment: I can't run rsync server on the NAS, otherwise I would be doing so. When not using an rsync server, rsync can use the checksum or the size and datetime to find out whether a file changed or not. According to the man page, it'll use the size and datetime by default, but my experience is that it is not doing that and I don't see a way to force it. I only see a way to force checksumming.

--checksum: Without this  option,  rsync  uses  a  "quick check"  that (by default) checks if each file's size and time of last modification match between the sender and receiver.
Comment: Evan, give me a couple of minutes to write my comment.
Comment: According to how I understand rsync work, it should check the local date and time, the remote date and time and if they match not copy the file. Which means it shouldn't copy 99% of the files, but the fact that it takes more than 12hs for 60GB or so tells me that is either copying everything (which seems to be what you are implying by saying that cp will be faster) or that it is actually checksumming, which means it's not copying everything, but it is downloading everything.
Comment: I'd run it with the "--dry-run" and "--verbose" arguments to see what it thinks it's doing. I wonder if your NAS device isn't representing the modification times exactly the same as the source. You could add a "--size-only" argument and see if that changes things. What filesystem are you running on the NAS device?
Comment: Thanks Evan, I'll try those recommendations. Regarding NAS' FS, I'm not sure, but I would guess it's ext3.
Comment: @Evan Anderson: He's locally mounting the SMB share. According to the rsync docs, copies to and from a local path doesn't use the delta transfers but instead copies the whole file. That coupled with the fact that rsync is less efficient than cp results in slow transfers.
Comment: @Starfish: That's what I say in my third paragraph. It switches to whole copy mode and doesn't do delta transfers in that situation.
Answer: It sounds like timestamps are your problem, as this page relates:
http://www.goodjobsucking.com/?p=16
The proposed solution is to add
--modify-window=1

to the rsync parameters.
Answer: Yes, you can speed it up. You need to make either the source or destination look like a remote machine, say by addressing it as "localhost:".
You stated that you are mounting the SMB share locally. This makes the source or destination look like a local path to rsync. The rsync man page states that copies where the source and destination are local paths will copy the whole file. This is stated in the paragraph for the "--whole-file" option in the man page. Therefore, the delta algorithm isn't used. Using the "localhost:" workaround will restore the delta algorithm functionality and will speed up transfers.
Comment: I wonder what sense that should make... `rsync` uses time and date stamp to check whether or not a file needs to be updated. If it needs an update, then rsync will divide the file in chunks and compare the checksums. That means it will read the whole file to be able to do that. So if you do not have a rsync daemon running remotely you will need to transfer the whole file anyway to do the chunking and checksumming so you can just as well transfer it straight away. So the "workaround" outlined here buys you in fact nothing in this scenario.
Comment: `-W // --whole-file` was the key in my case (over local network). I went from ~3.5 MB/s to ~35 MB/s. a 10x factor!!
Answer: Thought I would throw my 2p in here.
My brother has just installed a Buffalo NAS on his office network. He's now looking at off-site backups, so that should the office burn down, at least he still has all his business documents elsewhere (many hundreds of miles away).
My first hurdle was to get the VPS he has (a small Linux virtual private server, nothing too beefy) to dial-in as a VPN user to his broadband router (he's using a DrayTek for this) so that it itself can be part of his VPN, and so it can then can access the NAS directly, in a secure fashion. Got that sorted and working brilliantly.
The next problem was then transferring the files from the NAS to the VPS server. I started off by doing a Samba mount and ran into exactly the same (or even worse) issue that you've described. I did a dry-run rsync and it took over 1 hour 30 mins just to work out what files it was going to transfer, because as Evan says, under this method, the other end isn't rsync so it has to do many filing system calls/reads on the Samba mount (across a PPTP/tunnelled connection, with a round trip time of about 40ms). Completely unworkable.
Little did I know that the Buffalo actually runs an rsync daemon so, using that instead, the entire dry-run takes only 1 minute 30 seconds for 87k files totalling 50Gb. Obviously, to transfer 50Gb of files (from a NAS that is on a broadband link with only 100k/sec outbound bandwidth) is another matter entirely (this will take several days) but, once the initial rsync is complete, any incremental backups should be grease lightening (his data is not going to change much on a daily basis).
My suggestion is use a decent NAS, that supports rsync, for the reasons Evan has said above. It will solve all your problems.
Comment: +1 for making me aware that Buffalo NASes run rsync -- thanks!
Answer: Smells like you have a cheaper NAS. It could also be from your network bandwidth...
"Standard" consumer NAS are really weak when it comes to heavy IO which is what you are trying to do here. It could also be a cheap switch connecting your PC and your NAS that is not strong enough to handle all the packets correctly.
Comment: The same NAS, the same switch, another computer, running Windows, back up to it, much more information, in under four hours.
Answer: try this it think aleast gives you 10% more what speed your getting http://www.thegeekstuff.com/2009/09/linux-remote-backup-using-rsnapshot-rsync-utility/
Comment: Can it work over SMB instead of SSH?
Answer: There are two potential sources of the problem - either you use incorrect comman line options or your NAS has issues with timestamping (or both :-). Please check this thread "rsync to NAS copies everything every time" for more info.

Speeding up rsync over smb


Simpler alternative for $\int\frac{dx}{2\sin x+3\cos x+7}$

Question: Find
$$\int\frac{dx}{2\sin{x}+3\cos{x}+7}$$
My attempt:
$$I= \int\frac{dx}{\sqrt{13}\sin{\left(x+\theta\right)}+{7}}$$
where $\sin{\theta}=\frac{3}{\sqrt{13}}$.
Then, subsititute
$$t = \tan{\frac{y}{2}}$$where
$y=x +\theta$.
But, I think there is a simpler solution than above substitution. Would you help me?
Comment: @Hussien Mohamed: Using the formulas $\sin(x)=2\sin(x/2)\cos (x/2)$ and $\cos(x)=\cos^2(x/2)-\sin^2(x/2)$ one can transform your integral as $I=\int\frac{dt}{4t^2+4t+10}$, where $t=\tan(x/2)$. This enables you to finish the integration.
Comment: @Marian G That is the same solution i have mentioned
Comment: Do you mean you want to let $t=\tan y/2$?
Comment: Look at the solution to the integral here: https://www.wolframalpha.com/input/?i=integrate+dx%2F(2sinx%2B3cosx%2B7). Do you think there can be a simple set of steps that could lead to that kind of answer?
Comment: @Hussien Mohamed: I'm somewhat confused from your approach.
Answer: Below is an alternative to the half-angle substitution
\begin{align}
&\int\frac{1}{2\sin x+3\cos x+7}\ dx\\
=& \int\frac{1}{\sqrt{13}\sin y +7}\ dy
=\int \frac{\sec^2 y \ (\sqrt{13}\sin y+7)}{\sec^2y\ (\sqrt{13}\sin y+7)^2} \ dy\\
=& \int \frac{\sqrt{13}\sec y \tan y + 7\sec^2 y}{13\tan^2 y + 49 \sec^2 y + 7\sqrt{13} \sec y \tan y} \ dy\\
=&\int \frac{d(\sqrt{13}\sec y+7\tan y)}{(\sqrt{13}\sec y+7\tan y)^2 +36}
=\frac16 \tan^{-1}\frac {\sqrt{13}\sec y+7\tan y}6\\
= &\ \frac16 \tan^{-1}\frac {13\sec x +7(2\tan x+3)}{6(2-3\tan x)}
\end{align}
Comment: What is the formula for $y$?
Comment: @gist076923 - same as OP's $y=x+\theta$


Select no banco de dados, somente com jQuery

Question: Como eu faço um select no banco de dados utilizando somente utilizando um jQuery? Tenho dois combobox e quero usar o valor deles para fazer um select no meu banco de dados:
<code>        $.getJSON('/MinhaDoenca/rest/hospital/get', function(data) {

            for ( var index in data) {

                $("#idHospital").append(
                        '<option value="'+data[index].nome+'">'
                                + data[index].nome + '</option>')
            }

        });

        $.getJSON('/MinhaDoenca/rest/especialidade/get', function(data) {

            for ( var index in data) {

                $("#idEspecialidade").append(
                        '<option value="'+data[index].descricao+'">'
                                + data[index].descricao + '</option>')
            }

        });
</code>
Gostaria de pegar esses dois valores e fazer uma consulta no meu banco de dados, mas utilizando somente jQuery e HTML, sem PHP. É possível? Alguém poderia me passar um exemplo? (meu banco de dados é PostegreSQL)
Answer: Não é possível, pois o jQuery é uma biblioteca desenvolvida em Javascrit puro como provavelmente você deve saber ou deveria, que é uma linguagem de programação de script interpretado pelo Browser(Navegador) no lado do cliente(client-side), onde ela não consegue executar comandos internos no lado do servidor(server-side).
Então dessa forma não dar para fazer comandos de select no seu banco de dados usando somente JQuery, porque também seria algo de total insegurança para o seu site. E ser isso fosse possível qualquer programador poderia acessar seu site pelo console do Browser é fazer select's, insert's, update's, delete's etc em seu banco de dados.
O que seria possível seria criar uma API Rest, Soap, RPC em uma liguagem de programação do lado do servidor, onde com jQuery você a consumiria, que pelo seu código provavelmente é o que você quer fazer.
Se você está querendo criar um Web Service onde o consumiria somente com jQuery você poderia usar o framework slimframework do PHP, caso seja PHP que você está usando, aqui é um exemplo bem simples do uso dele:
<code><?php
$app = new \Slim\Slim();
$app->get('/MinhaDoenca/rest/hospital/get', function() {

  //Seu código para acessar o banco de dados

});
$app->run();
</code>
Obs.: Mas isso até é possível ser você usar Node.js que é uma plataforma construída sobre o motor JavaScript do Google Chrome que roda no lado do servidor como PHP, Java, Python etc, que não vez a caso aqui.
Comment: Mesmo consumindo um Web Service?
Comment: Quando eu disse API eu me referir a isso API Rest, Soap etc, que são formas de ser desenvolver Web Service's.
Comment: Que também usando um Web Service não fugiria de uma liguagem  de programação server-side como o PHP.


Systematically Missing Data

Question: I have a problem regarding regression with sistematically missing data. I cannot describe the exact setting, so I will make up a situation that captures everything that is essential.
Let's imagine the following experiment setting: I am doing research on the probability of individuals participating in the labour market (binary variable). One of the independent variables in my dataset is the age of the first kid. When the individual has a kid, then the variable is simply its age. When the individual doesn't have offspring, it is NA. Note that the data is not missing at random: it reflects the observable characteristic that some people have kids while other don't. More importantly, it divides the sample into two sub-samples, in a way that is potentially very correlated with the outcome variable.
Now, how can I use this variable in a Logit model? I cannot simply fill the column with zeroes. I also cannot use the variable has_children x age_of_firstborn, since the value of that variable would be the same as just filling with zeroes. I also thought about doing two regressions, one for people with kids, and one for those who don't, but I think it would be a pity, because I would loose generality. I am not even sure if it can be considered truncated data. Any ideas?
Answer: There are a lot techniques for dealing with missing values (multiple imputation, EM, weighting, etc.) However, none of these apply to your situation, as your missing values are not missing values as these techniques understand them. For a value to be missing it first needs to exist. In your case the age of the child just does not exist for people without children, so it cannot be missing. Unfortunately for you, they still have a missing value code in your data. So you need to do something, but those techniques are not applicable to your situation.
Lets say you want to explain a variable $y$ with respondent's education ($educ$), which is observed for everybody, and age of youngest child ($chage$), which is only observed for people with children. The child's age cannot influence $y$ for persons without children; this characteristic just does not exist for those persons. So for these persons the logistic regression model is $P(y=1|x)=\Lambda(\beta_0 + \beta_1educ)$, where $\Lambda(\cdot)= \frac{\exp(\cdot)}{1+\exp(\cdot)}$. For people with children, your model is $P(y=1|x)=\Lambda(\beta_0^* + \beta_1educ + \beta_2chage)$. It reasonable to suspect that just the fact of having children has its own effect on top the children's age, so $\beta_0\neq\beta_0^*$.
You can estimate this model. The first step is to create a new variable indicating whether or not a person has children (in all likelihood you don't need to create that variable as it is probably already in your data). Lets call that variable $child$. The second step is to change the variable $chage$ to 0 for all persons without children. Than you can add $child$, and $chage$ to your model. So we have $P(y=1|x)=\Lambda(\beta_0 + \beta_1educ + \beta_2chage + \beta_3 child )$
If someone does not have children, then $child$ = 0 and $chage$ = 0. So the model becomes:  $P(y=1|x)=\Lambda(\beta_0 + \beta_1educ + \beta_2 0 + \beta_3 0 ) =  Lambda(\beta_0 + \beta_1educ )$, which is what we wanted.
If someone has children, then $child$ = 1. So the model becomes $P(y=1|x)=\Lambda(\beta_0 + \beta_1educ + \beta_2chage + \beta_3 1 ) = \Lambda(\underbrace{\beta_0 + \beta_3}_{\beta_0^*} + \beta_1educ + \beta_2chage  ) $
, which is what we wanted.
Notice that the number of variables in your model differ depending on whether $chage$ had a missing value or not. In your case that is exactly what we wanted, because quite sensibly we don't want to control for characteristics that don't exist for an individual. However this also means that this trick does not work for a general case of missing values, i.e. the value exists but we have not observed it.
Comment: Thank you for the great answer. I guess you could furthermore add an interaction term multiplying _educ_ and _child_ to account for different effects of education on _y_ depending on _child_?
Comment: Sure, you can add all kinds of interaction effects, but keep in mind that the purpose of a model is to simplify reality. Your model does not simplify much if you add all interactions... So there is always a trade-off.
Answer: What about binning the children's ages so that you have
$Y=B_0+B_1(no\_child) + B_2(child0-2)+B_3(child2-4)...etc$
I realize it's a logit but my latex skills are weak and the idea is the same even if this is the wrong syntax.
Comment: The nice thing about this solution is that it acknowledges that children's age is likely to have a highly non-linear effect. For some dependent variables it is likely highly discrete (pre-kindergarten, kindergarten, school), like your solution suggests. For other dependent variables you might want to choose a more smooth function. It takes care of the systematic missing values in the same way as my solution: you set the dummy variables $child0-2$, $child2-4$, ... to 0 when child's age is missing, and add a dummy for no child.

Systematically Missing Data


Como adicionar elementos de uma lista em um dicionário em Python3

Question: Boa tarde, estou com problema para adicionar elementos de uma lista em um dicionário.
Os elementos da lista para colocar no dicionário são:
['Joao', '83889023', 'Maria', '81944356', 'Marcos', '32258899', 'Ana', '88235423', 'George', '1254345', 'Rafaela', '8899345671', 'Pedro', '83223345', 'Aline', '842234565', 'Carlos', '83554463', 'Julia', '13565446', 'Murilo', '23543646', 'Mayra', '233253425', 'Italo', '842142543', 'Rita', '3253464457', 'Aldo', '77443456', 'Raquel', '8384423553', 'Henrique', '88342235', 'Joyce', '987676342', 'Daniel', '3253456346', 'Livia', '325346634', 'Pablo', '87461723', 'Carla', '87351236']

O problema é: No dicionário a chave terá que ser o número e o valor terá que ser o nome.
O que eu tentei foi:
dic = {}
x = 0
y = 0
for elem in dados:
    dic[elem] = dados[y]
    x = x + 1
    y = y + 1
print(dic)

Porém o que eu recebo é:
{'Joao': 'Joao', '83889023': '83889023', 'Maria': 'Maria', '81944356': '81944356', 'Marcos': 'Marcos', '32258899': '32258899', 'Ana': 'Ana', '88235423': '88235423', 'George': 'George', '1254345': '1254345', 'Rafaela': 'Rafaela', '8899345671': '8899345671', 'Pedro': 'Pedro', '83223345': '83223345', 'Aline': 'Aline', '842234565': '842234565', 'Carlos': 'Carlos', '83554463': '83554463', 'Julia': 'Julia', '13565446': '13565446', 'Murilo': 'Murilo', '23543646': '23543646', 'Mayra': 'Mayra', '233253425': '233253425', 'Italo': 'Italo', '842142543': '842142543', 'Rita': 'Rita', '3253464457': '3253464457', 'Aldo': 'Aldo', '77443456': '77443456', 'Raquel': 'Raquel', '8384423553': '8384423553', 'Henrique': 'Henrique', '88342235': '88342235', 'Joyce': 'Joyce', '987676342': '987676342', 'Daniel': 'Daniel', '3253456346': '3253456346', 'Livia': 'Livia', '325346634': '325346634', 'Pablo': 'Pablo', '87461723': '87461723', 'Carla': 'Carla', '87351236': '87351236'}

Como resolvo esse problema?
Answer: O seu código gera um resultado errado porque o valor de y sempre coincidirá com o índice de elem na lista e, desta forma, sempre serão o mesmo valor. Para implementar algo deste gênero, você precisa percorrer a lista a cada dois elementos:
dic = {}
y = 1
for elem in dados[::2]:
    dic[dados[y]] = elem
    y = y + 2
print(dic)

Mas uma solução mais simples é apresentada abaixo.

O Python possui uma recomendação da implementação da função pairwise baseada na função itertools.tee
def pairwise(iterable):
    "s -> (s0,s1), (s1,s2), (s2, s3), ..."
    a, b = tee(iterable)
    next(b, None)
    return zip(a, b)

Porém, veja que o segundo elemento do primeiro par será o primeiro elemento no segundo par e não é isso que precisamos. Isto acontece pois a e b são iteradores diferentes. Ao fazermos ser o mesmo iterador, teremos a saída desejada:
def pairwise(iterable):
    "s -> (s0,s1), (s2,s3), (s4, s5), ..."
    it = iter(iterable)
    return zip(it, it)

Desta forma, basta fazermos:
name_map = {number: name for name, number in pairwise(data)}

Para obter o resultado:
{
    '83889023': 'Joao',
    '81944356': 'Maria',
    '32258899': 'Marcos',
    '88235423': 'Ana',
    '1254345': 'George',
    '8899345671': 'Rafaela',
    '83223345': 'Pedro',
    '842234565': 'Aline',
    '83554463': 'Carlos',
    '13565446': 'Julia',
    '23543646': 'Murilo',
    '233253425': 'Mayra',
    '842142543': 'Italo',
    '3253464457': 'Rita',
    '77443456': 'Aldo',
    '8384423553': 'Raquel',
    '88342235': 'Henrique',
    '987676342': 'Joyce',
    '3253456346': 'Daniel',
    '325346634': 'Livia',
    '87461723': 'Pablo',
    '87351236': 'Carla'
}

Veja funcionando no Repl.it | Ideone | GitHub GIST


Compact,connected set

Question: How could be proved that a function that sends compacts into compacts and connected into connected implies f continuous ?
I'd appreciate even just the idea behind that (if the proof is too long)
Thanks
Comment: I don't think it is true.
Comment: Could sin(1/x) be a counter-example?
Comment: @ChrisCulter I don't think this duplicates that question. This question is not restricted to $\mathbb R^n$.
Comment: @UmbertoP. I'm assuming that the OP is working with some unstated assumptions, since they seem to be looking for a proof of a true statement.
Comment: @ChrisCulter possibly. On the other hand, there are lots of requests on this site for proofs of false statements.
Comment: I don't know if it's true or false,i'd like to know it (and why) so that i could work on the proof
Answer: Let $X$ and $Y$ be topological spaces and $f : X \to Y$.
If $X$ is a totally disconnected space its only connected subsets are singletons. In this case $f$ sends connected sets to connected sets.
If $Y$ is a two-point set then every subset of $Y$ is compact. In this case $f$ sends compact sets to compact sets.
So, you should look for a discontinuous function from (say) the irrational real numbers with the relative topology to the set $\{0,1\}$ to obtain a counterexample.

Compact,connected set


Prove $T$ is a Fredholm operator

Question:
Question: If $H$ is a Hilbert space and $T:H\rightarrow H$ is a bounded linear operator, $\mathrm{ran}\,T$ is closed, and
  $$\dim \ker T=d<\infty$$
  if $T-T^*$ is compact, prove that $T$ is a Fredholm operator with index $0$.

My attempt Since $T=(T-T^*)+T^*$, by Fredholm theory, if $$\mathrm{codim}\,\mathrm{ran}\,T<\infty$$
then $T$ is Fredholm, so $$\mathrm{ind}\,T=\mathrm{ind}\,T^*$$
however, by definition we have $\mathrm{ind}\,T=-\mathrm{ind}\,T^*$, so $\mathrm{ind}\,T=0$. So the remaining problem is to prove
$$\mathrm{codim}\,\mathrm{ran}\,T<\infty$$
I do not know how to begin, any help will be appreciated.
Answer: Since $\dim \ker T<\infty$ and $\mathrm{ran}\,T$ is closed, it results that $T$ is semi-Fredholm. Hence $T^*$ is semi-Fredholm with $\mathrm{codim}\,\mathrm{ran}\,T^*<\infty$ (and $\mathrm{ran}\,T^*$ is closed). Furthermore we have
$$(1) \quad \mathrm{ind}\,T=-\mathrm{ind}\,T^*.$$
Now let $K:= T -T^*$. Since $K$ is compact, $T-K$ is semi- Fredholm with
$$(2) \quad \mathrm{ind}\,T=\mathrm{ind}\,(T-K).$$
But we have $T^*=T-K$, hence
$$(3) \quad \mathrm{ind}\,T=\mathrm{ind}\,T^*.$$
From $(1)$ and $(3)$ we now see, that $ \mathrm{ind}\,T=\mathrm{ind}\,T^*$ is finite $=0$ and therefore $\mathrm{codim}\,\mathrm{ran}\,T<\infty.$

Prove $T$ is a Fredholm operator


Mimicking Google's Persistent Disks -- Is this a logical FreeBSD disaster recovery strategy?

Question: I am looking into FreeBSD to provide a more comprehensive backup and disaster recovery strategy for database servers. Ideally I want to mimic what google is doing with "Persistent disks" https://developers.google.com/compute/docs/disks#snapshots
I am hoping someone who knows more about FreeBSD can validate these ideas/questions:

I have read that FreeBSD can take instant disk snapshots, therefore if our databases trigger a consistent state (Block all
writes, and flush buffers to disk), I would assume I could take
snapshots every hour without service interruption for more than a
few seconds. Is this true?
Is there a way to take snapshots and back them up offsite easily? Can this be done incrementally as to save how much disk
space is actually used?
If a rollback needed to be done, how long does this typically take? Is a rollback also instantaneous?

Thanks!
Comment: Is FreeBSD a requirement?
Comment: No, FreeBSD is not a requirement, but it seemed like low hanging fruit.
Answer: I recommend you use FreeBSD with ZFS. See the FreeBSD handbook's section on ZFS at https://www.freebsd.org/doc/handbook/filesystems-zfs.html . And FreeBSD 10 has some major improvements over earlier versions.

ZFS can take instant disk snapshots without any noticeable service interruption. Many shops do this this with MySQL & Postgres databases. Oracle database administrators do this using Oracle Solaris & ZFS.
ZFS snapshots can be rolled back.

You can backup the .zfs/snapshot directory using your regular backup software. I have heard of people using zfs send and zfs receive for this purpose, but we couldn't get it to work. In theory, you could do something like zfs send snapshot.today | mybackupsoftware --hostname backup.offsite.example.org and store the image offsite.
   zfs send [-vR] [-[iI] snapshot] snapshot

   Creates  a  stream  representation of the second snapshot, which is
   written to standard output. The output can be redirected to a  file
   or  to a different system (for example, using ssh(1).

   zfs receive [-vnF] filesystem|volume|snapshot

   Creates a snapshot whose contents are as specified  in  the  stream
   provided  on  standard  input

Comment: Very cool, this is exactly what I needed confirmed. Thanks!
Answer: FreeBSD can do UFS snapshots (the process is described in the handbook). Many operations (mine included) take advantage of this by quiescing a database (we do a full shutdown on our slave DB), making a snapshot, then reactivating the database.
The snapshot can then be mounted and backed up using your regular backup tools (in our case Bacula).
(For more drum-banging on how UFS is awesome, see here).
The big disadvantage I see is that UFS snapshots can't be (easily) rolled back - the most efficient technique I'm aware of is to rsync data off the snapshot (which isn't very efficient because of the nature of UFS snapshots), but for making backups they're usually fine.

As Stefan points out ZFS may be a better choice.
ZFS has a number of advantages over UFS for something like a database (like the ability to quickly and easily add more disk space to the partition if you outgrow it, and the ZFS Send/Receive capability for moving snapshots around).
Another advantage of ZFS is that snapshots are effectively "free" (ZFS is a non-overwrite filesystem so all it does is not reuse any sectors in the snapshot - UFS needs to do some extra bookkeeping while the snapshot exists), and you can make them writeable if you have to.
The only disadvantage of ZFS that I can think of is it's memory hungry, particularly compared to UFS. You will want to think about that (and about tuning ZFS) before rolling it out in production.
Comment: Note that for both UFS and ZFS you may not have to quiesce your database (for example, Postgres would happily recover if I just took a snapshot with the DB running - it would declare an "unclean shutdown" and replay its transaction log). We do the shutdown mainly as an extra level of paranoia, to guarantee that the database is "ready to start immediately" with no replay required in the event we need to go to our backups.
Comment: So you suffer downtime every night in order to shorten the time window for a presumably very rare DR scenario by at most a few minutes? That makes zero sense.
Comment: @rmalayter read carefully: ***we do a full shutdown on our slave DB***. There is no "downtime", merely a ~1 minute window where the slave is not replicating from the master (during shutdown/restart). This is (IMO) entirely sensible in order to have a 100% guarantee that the backup is of a clean, consistent database that will restart with no issues *every time*. These backups are also regularly restored to our QA environment (both as a restore test and for QA testing purposes), so it's saving "a few minutes" quite often.
Comment: Thanks this info is really good. Based on what you have said I think ZFS is better suited for me, specifically because I want to take snapshots at 30min intervals (Forcing a very brief < 5s pausing of database operations each time), and be able to rollback very quickly. The memory issue is concerning, but I expect no single server will have over 1TB of data. I think with out setup I could easily give ZFS 1GB-RAM/TB-Disk. Any thoughts on this?


Find / Rename command not catching the filenames I want it to find

Question: I have these two files in my home directory -
hello_newest.txt
goodbye_newest.txt

I want to rename them so that the "newest" part of the filename is removed completely, so that they would recome hello.txt and goodbye.txt
This is the command I am running -
find -name "*.txt" -exec rename 's/newest//i' {} ";"

It doesnt throw an error or do anything to the files after I run this command.  I've checked out http://www.computerhope.com/unix/rename.htm and it looks like it should be working based on some of those examples that are there.
I'm sure it's something simple, but what am I missing?
Comment: It seems to be working except that you need to include `_` in the matched string to be removed.
Comment: Even adding that, none of the files are renamed after running the command.  This on on RHEL 5.
Answer: Looks like it might be the version of Redhat we were on.  The command -
rename _newest '' *
Seems to accomplish the same goals.
Thanks for the help.
Answer: Different Syntax. But worked for me :
for i in *.txt; do mv "$i" "`echo $i | sed 's/_[^.]*//'`"; done

All the txt files are found using for loop and then the charecters after underscore is removed using sed.


Como comparar memória usada por 2 processos

Question: Olá. Estou desenvolvendo um programa em vb.net que encontra alguns processos, pega o PID dos mesmos, e depois coleta algumas informações sobre eles.
O problema é quando tem 2 processos iguais. Nesse caso, eu precisaria que ele visse qual dos dois está utilizando mais memória no momento, e deletar o outro da listbox. Meu code para achar os PID's:
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
    Me.TopMost = True
    Me.Focus()

    For Each Proc As Process In Process.GetProcesses()
        ListBox1.Items.Add(Proc.ProcessName)
        ListBox2.Items.Add(Proc.Id)
        Proc.Start()
    Next

Private Sub Proc_Tick(sender As Object, e As EventArgs) Handles Proc.Tick
'variáveis
Dim actualProcess as String
Dim ListBox1Items as String
Dim actualProcessExists as Boolean = False
Dim ProcID as Integer
'----------------------------------------------
actualProcess = "explorer"
    ListBox1Items = ListBox1.Items.Count - 1

'Checando se o processo existe
    For ia As Integer = ListBox1Items To 0 Step -1
        ListBox1.SelectedIndex = ia
        If ListBox1.SelectedItem = actualProcess Then
            actualProcessExists = True
        Else
            Proc.Stop()
            Proc2.Start()
        End If
    Next
'----------------------------------------------------------

'Adicionando PID à outra ListBox

    If actualProcessExists = True Then
For i As Integer = ListBox1Items To 0 Step -1
    ListBox1.SelectedIndex = ia
        If ListBox1.SelectedItem = actualProcess Then
        ListBox2.SelectedIndex = ListBox1.SelectedIndex
        ProcID = ListBox2.SelectedItem
        ListBox3.Items.Add(ProcID)
    Else
   Proc.Stop()
   Proc2.Start()
End if
End Sub

Bom, o que eu precisava era que ao ver 2 itens na ListBox2, ele, pelos PID's dos processos, visse qual usa mais memória, e definisse esse como "ProcID". Poderiam me ajudar?
Agradeço desde já.
Comment: Editei. Tinha esquecido de colocar o "Form_Load" no code, daí não ia dar pra entender o código do timer...
Comment: Porque utiliza duas `ListBox`? Qual o objetivo do seu código?
Comment: Na primeira, serão adicionados todos os processos sendo executados no momento. Na segunda, serão adicionados os PIDS desses processos. Depois utilizando FOR, ele muda o selectedindex da listbox1, a qual contém todos os processos, e verifica se o item selecionado corresponde à variável "actualProcess", se corresponder, ele irá definir o selectedindex da listbox2 para o mesmo selectedindex da listbox1, e então, teremos o pid do processo. E então o pid do processo será adicionado à listbox3. (Editei o código)
Answer: O seu código pode ser largamente otimizado, isto se o que percebi está correto.
Reestruturei-o para o seguinte:
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
    TopMost = True
    Focus()
    PreencheListBox()
    Proc.Start()
End Sub

Private Sub PreencheListBox()
    ListBox1.DataSource = Process.GetProcesses().OrderBy(Function(r) r.ProcessName).ToList()
    ListBox1.ValueMember = "Id"
    ListBox1.DisplayMember = "ProcessName"
End Sub

Private Sub Proc_Tick(sender As Object, e As EventArgs) Handles Proc.Tick
    PreencheOutraListBox("explorer")
End Sub

Private Sub PreencheOutraListBox(ByVal processName As String)
    Dim processesSource = CType(ListBox1.DataSource, List(Of Process))
    Dim processes = processesSource?.Where(Function(r) String.Compare(r.ProcessName, processName) = 0).ToList()

    If processes?.Count > 0 Then
        Dim process = processes.OrderByDescending(Function(r) r.WorkingSet64).FirstOrDefault()

        If Not process Is Nothing Then
            ListBox2.Items.Add(process.Id)
        End If
    End If
End Sub

A propriedade WorkingSet64 devolve a quantidade de memória alocada para determinado processo, então ordenei a lista por aí e apenas coloquei na nova ListBox esse PID.
De salientar que o nome do processo no Timer é apenas um exemplo (porque de X em X tempo vai resultar no mesmo).


How to calculate notes beats and properly draw notes beams?

Question: I am fairly new to music theory and i find these 2 topics related but not explained in depth in...pretty much every resource i have found.

How are beats normally calculated? I went through the process of converting each note using equivalent fractions so every note had the same denominator and then added them all, making the result the number of beats out of a maximum of 4. However, i have the feeling i am over-complicating the process and there is a much simpler way to do it:

I noticed musescore writes beams in a way i do not understand, it writes the beams of the quaver, semiquaver and demisemiquaver to the right or the left in what feels an arbitrary way, making confusing when should i write the beams to the right and when to the left. What's the rule involving the direction of the beams for quaver, semiquaver and demisemiquaver?

This example shows what i mean about the arbitrary beam location:

If possible i would like easy-to-understand answers to this topic, that do not use much musical jargon as i would not understand overly-technical answers with my currently limited music theory knowledge.
Comment: In your examples where you state *its beams are in the opposite direction* - I can honestly say I've never seen it not done this way when using a bar to join notes (as in your examples).  Do you have *any* example where it's not done this way?  So the answer to that part, is: because that how it's done.
Comment: @freedomn-m often things are done a certain way because there is some benefit, such as making the music easier to read.  Of course, it can be difficult to determine whether people find something more legible because of some objective factor or because of familiarity.  If it's purely because of familiarity, the practice may nonetheless have arisen because it makes the music easier to write.
Answer: Wow, thanks for a well-documented and clear question!
You calculated correctly that the example adds up to 2 beats. However, it normally wouldn't be as challenging as that example, since it breaks a convention of beaming: Beams are normally organized to avoid connecting across beats, making it easier to see beats as groups at a glance. What if you had this:

... It's hard to tell at a glance which notes belong to the first beat and which to the second. It ought, properly, to be beamed like this:

... making it much easier to see the beats.
To beam your example properly: The dotted quaver "overflows" beat 1; all there's room for in the beat is a quaver. So the dotted quaver should be split up into a quaver tied to a semiquaver (since the pitch is the same, it will sound as one note):

To the second part of your question, about the direction of beams: The central point is that beams connect notes. The example you give is complicated somewhat by the dotted semiquaver followed by a demisemiquaver.

If the dotted semiquaver were split up, it would yield a semiquaver plus a demisemiquaver:

... and that's why the partial beam of the B demisemiquaver, in the dotted example, points left: it "belongs" to the other demisemiquaver contained within the dotted semiquaver. (See this earlier question, or rather its answer; the question is rather confusing.)
Comment: I agree that the left-pointing partial beam helps to group the note with its associated dotted note, but if the shorter note is unbeamed, this doesn't happen with its flag or flags (for example if it is vocal music in older style of syllabic beaming or if the notes are a dotted quarter and an eighth).  I wonder how this was done in older styles where stem-down flagged notes had their flags on the left side of the stem.
Answer: Your first question is partially correctly answered. The only issue is that you should consider note values as relations to the reference meter, not only the beat.
For instance, while technically a quaver is a quarter of a beat (in an x/4 meter where x is between 1 and 4), you also have to remember that there are meters that have different layouts; for instance, the compound meter of 6/4 considers 2 subdivisions of 3 "sub-beats", but it's also commonly considered as a 2-beats based meter (similarly to 6/8). So, one could say that a semiquaver, in that case, is not a quarter of a beat, but a 12th.
A very important thing to remember in rhythmic notation (and music in general) is that it's all relative.
Regarding your second question, these are some rules to keep in mind:

beams are always grouped based on their "siblings" (notes that have the same duration): in your last image, that further line makes no sense, since it's preceeded by a note that has a similar duration;
beams usually extend only within the beat or subdivision, not over;
notes that share a common parent duration also share the beam related to the biggest duration;

Considering the above, this is not completely unusual, and it has the benefit of clearly showing the quaver grouping within the beat:

"broken" beams exist only for notes that have no "siblings" (both preceding or following notes that have a different duration);
"broken" beams are always towards their closest "parent" beamed note: a demisemiquaver between a quaver and a semiquaver is always beamed towards the semiquaver; if, for musical reasons, you need to group them differently, the parent beam is separated;
in special situations for which the parent beamed notes are the same (consider a semiquaver between two quavers in a 5/16 meter), the direction is based on the beat, subdivision or musical requirement (phrasing); considering the 5/16 case above, the direction depends on the subdivision: if it's a 2+3 meter, then the beam is on the right, otherwise, and in the rare situation for which there's no actual sub-beat, it's on the left;[1]

Finally, consider that what you're asking is about very rare and specific situations. Your first image and the first example related to the second questions are generally considered as bad notation practice.
Remember that the first rule of notation is to ensure the score can be read as much easily as it's possible: the performer should focus on making music, not decypher how it's written. Beams (and groups) should always help the musicians, not distract them.[2]
In both cases, you have notes grouped along more than one beat (or grouped subdivision), which makes them really awkward.
Here are better versions of them:

While they might seem more complex than your examples, they're actually much more readable and understandable, since the hierarchy of beats and durations is much more clear: the musician can clearly see where (and when) one beat ends and the other starts.
[1] I've seen very special situations for double-sided broken beams, but that's generally a very odd case for very odd notations that cannot be considered as standard.
[2] obviously, the first real rule is music theory, so you could get properly written sheet music that's still hard to read for some reason (consider cases with lots of double sharps or flats), but, as with any rule, there are exceptions; for instance, sheet music for harp sometimes ignores harmonic rules, as the technical "limitations" of the instrument suggest that it's better to write an enharmonic note that properly indicates the string to play instead of the harmonically correct note; for percussion instruments, you can get "pointless" durations (you'll get the same sound and sustain from a snare drum hit, no matter if you write a crotchet, a quaver or a demisemiquaver), but specifying them is actually nonsensical most of the times.
Answer: Just an idea, fuse pairs of notes with same duration next to eachother mentally so they become a note with one flag less, split the ones with dots so there is another note next to it with one more flag and then continue fusing. Is a bit more intuitive than bringing out calculator. (You might need to go dots first, then do the ones with the most flags bottom up, not sure).


Is there a Gaussian Process Kernel that limits functions to sigmoids?

Question: I am modeling a large number of Dose-response curves. I have strong reason to believe that the generating function will be sigmoidal against the concentration of the assay (Michaelis-Menten kinetics). I also know that there will be no effect at 0 concentration (homeopathy is not real). I have been playing with using Gaussian Process regression because I really like the idea of being able to model my uncertainty and sometimes I only have noisy measurements at a couple of concentrations over a given curve.
Is there a Gaussian Process Kernel that limits functions to sigmoids? There is no example in Duvenaud's excellent kernel cookbook.
I have seen people mention such a thing, but I cannot find any concrete expression of such a kernel. Also, I cannot think of a way to use a covariance matrix to express ideas like monotonicity or sigmoidalness, maybe I have a fundamental confusion about GPs
Comment: If I understand correctly, there's strong theoretical reason to believe the curve has a particular parametric form. If that's the case, why bother with nonparametric techniques like GP regression? Instead, you could simply fit the parametric model (e.g. using Bayesian inference if you want to handle uncertainty that way). If the form of the model is correct, this will make much more efficient use of the data than black box methods like GP regression.
Comment: I might be misunderstanding, but this sounds like you would use a transformation from some real-valued numbers to your preferred scale; for example, $$
z \sim \mathcal{GP}\left(\mu(x),\Sigma(x)\right)\\
y = \text{logit}^{-1}(z)
$$ where $y$ is the thing you want to be bounded in [0,1]. Is this a correct reading of your question, or are you asking for something else?
Comment: Hmm, I had not thought of transforming my space before doing the GP. However, I am not sure this works as not everything will have full effect at high concentrations. many of my sigmoids have partial effect at high concentrations, so that logit transform may do weird things.
Comment: Unless otherwise specified, the fitting weights are all implicitly 1.0. If you are certain that the curve passes through the origin, that is, there is zero uncertainty of that value, because uncertainty in weighted regression is inversely proportional to the assigned weight you can assign all points a weight of 1.0 *except* at the origin, which is included in the regression and is assigned an extremely large weight, such as 1.0E10, This technique will have the effect of forcing the curve to pass through any single point in all software which can perform weighted regression.
Answer: No such kernel exists:

There is no nontrivial kernel such that samples from the GP are (almost surely) bounded, i.e. $0 \le f(x) \le 1$ as required for a sigmoid. The marginal distribution of, say, $f(0)$ is  a normal distribution, and normal distributions are only almost surely bounded if they have zero variance.
There is no nontrivial kernel such that samples from the GP are (almost surely) monotonic. Once you've sampled $f(0)$, the conditional distribution of $f(1) \mid f(0)$ is also Gaussian, and thus either must have zero variance or else have some probability of being either larger than or smaller than $f(0)$.

As discussed in the comments, the normal thing to do in GP-land is to model some transformation of the data, e.g. $z$ in Sycorax's comment. You can choose some suitable non-stationary kernel to avoid the issue you mentioned about the influence of the kernel, e.g. $k_z(z, z') = k_\mathrm{base}(\operatorname{z\_to\_x}(z), \operatorname{z\_to\_x}(z'))$.
Or just don't use a GP if you really think a parametric model is the right choice. Or you could consider a "semi-parametric" approach.


Are these two structs equivilant?

Question: I'm a bit new to structs and just wondering if these two structs are equivalent. I dont know if this is relevant, but im using these structs to build a stack.
Is this:
struct dataT
{
    int m;
};

struct stack
{
    int top;
    struct dataT items[100];
} st;

equivalent to this?
struct stack
    {
        int top;
        int items[100];
    } st;

Arent these basically the same? The second method only uses one struct.
If im wrong, could you please tell me why it is not.
Comment: absolutely not. access methods will be different.
Comment: Yea, but structre vise they are the same right? Why are we creating another struct if you can just do it the way I did it the second way, this way there is only 1 strcut. This is what is confusing me
Answer: It will make a difference if you ever decide to change the dataT structure. If you know that it will always be only a wrapper for int, then it is a pretty useless structure. But if it may change, then the top one will probably be easier to maintain.
Comment: With the program I am building it will always be the same. I will not be adding anything  other than the int in the struct. So the second method is better and will function the same way in this case right?
Comment: Yeah, I don't see any reason to use the top version, it seems to be unnecessarily complex. The second way is functionally equivalent in terms of data storage.

Are these two structs equivilant?


How to access current langcode in theme?

Question: I use Integrity theme and want to make the slider images i18n aware.
I want to get the current langcode in the
<code>function _integrity_get_home_block_contents
</code>
Previously it worked like this:
<code>   global $language;
   $lang_id = $language->language;
</code>
What do I do now?
Answer: Here's how to do the same in Drupal 8:
<code>$language = \Drupal::languageManager()->getCurrentLanguage();
// Will return "en".
$shortcode = $language->getId());
// Will return "English".
$language_name = $language->getName();
</code>
Read more here.


Why is Selenium Chrome driver not able to find elements below scroll bar?

Question: I have been trying to write a clear dashboard step that would clear all objects we call widgets off of a dashboard page like this:
    public static void ClearDashboard(string widgetToKeep = null)
    {
        var widgets = Driver.FindElements(
            By.XPath(
                $"//div[@widget-name and descendant::span[@class='title' and text()[not(contains(., '{widgetToKeep ?? "dummyText"}'))]]]"
            ));

        if (widgets != null)
        {
            foreach (IWebElement widget in widgets)
            {
                var closeButton = widget.FindElement(By.XPath(".//span[@class='delete']"));
                closeButton.Click();
            }
    }

It totally works.
It gets all span elements back with a title and I can roll through those elements, get a span delete button for each one, and delete the widget with:
closeButton.Click()

Except for a widget object which is a bit off of the screen.
It can't seem to find the span button if the widget is a little off the screen.

This is the exception:
  InvalidOperation was unhandled by user code
An exception of type 'System.InvalidOperationException' occurred in WebDriver.dll but was not handled in user code
Additional information: unknown error: Element is not clickable at point (951, 760). Other element would receive the click:
...

(Session info: chrome=52.0.2743.116)
(Driver info: chromedriver=2.22.397933 (1cab651507b88dec79b2b2a22d1943c01833cc1b),platform=Windows NT 6.1.7601 SP1 x86_64)
Answer: You should use scrolling to reach every element before click using IJavascriptExecutor and wait until element to be clickable using WebDriverWait as below :-
IWait wait = new WebDriverWait(Driver, TimeSpan.FromSeconds(3));
IJavaScriptExecutor js = Driver as IJavaScriptExecutor;
foreach (IWebElement widget in widgets)
{
 var closeButton = widget.FindElement(By.XPath(".//span[@class='delete']"));

 //Now scroll to this element first
 js.ExecuteScript("arguments[0].scrollIntoView(true);", closeButton);

 wait.Until(ExpectedConditions.ElementToBeClickable(closeButton)).Click();
}

Comment: No, you shouldn't. The WebDriver is supposed to do this automatically by the spec: `they will implicitly scroll elements into view` © https://www.w3.org/TR/webdriver/#element-interaction


Finding density of the distance from an arbitrary starting point to the nearest tree

Question:
Trees in a forest are distributed according to a Poisson process. Let $X$ be the distance from an arbitrary starting point to the nearest tree. Given that the average number of trees per square metre is $\lambda,$ find the density $f(x)$ of $X.$

The probability that there are $0$ trees within a circle of radius $x$ from the starting point is $e^{-\lambda \pi x^2},$ since $\lambda \pi x^2$ is the average number of circles that would be expected in that region. But I'm not sure how to relate this to $X,$ the distance from an arbitrary starting point to the nearest tree. Fix a starting point $S.$ If the distance from $S$ to the nearest tree is $x,$ then doesn't that mean that there's at least one tree within that distance of $x$? If so, then the probability of the nearest tree being a distance of $x$ from the starting point should be the probability of at least one tree occurring in the circle of radius $x,$ which is $1-P(no \,trees\, occur).$ This is the cumulative distribution function as it's the sum of the probabilities that the nearest tree is a distance of $0\leq y\leq x$ from the start point, and so to find the density, we just take the derivative.

Is this correct?
Comment: Related: https://math.stackexchange.com/questions/1696941
Answer: What you have said looks correct to me but does not seem answer the original question:

The expected number of trees within $x$ of the point is $\lambda \pi x^2$

The probability there is exactly one tree within $x$ of the point is, as you say,  $\lambda \pi x^2 e^{-\lambda \pi x^2}$ as this is a Poisson process, but this is not particularly helpful

The probability there are no trees within $x$ of the point is $e^{-\lambda \pi x^2}$ as this is a Poisson process

The probability there is at least one tree within $x$ of the point is $1-e^{-\lambda \pi x^2}$ and this is a cumulative probability

The density for the distance of the nearest tree is then $2 \lambda \pi x e^{-\lambda \pi x^2}$ by taking the derivative


Como alinhar itens da lista

Question: Tenho o seguinte código:

ul {
  list-style: none;
  list-style-position: outside;
  padding-left: 0;
}

li {
  margin-bottom: 20px;
}

    li:before {
      content: "\2192";
      padding-right: 10px;
    }

p {
  display: inline;
}

Item 1 alaksjd fçalksdj fçlaksjd fçlaksjd fçlkasdj flçkajsdlçkfjasldçkjflçaksd jfçlkasjd flçkajsdlkçf asd

Item 2 adflçaksd jglçakhsd flaksdh kjahsdf gjhdfjkh skjchvçz,xckhvj çzlxkcjv zçlxckjvlçz xckjvçzlxkcjv

Item 3 asdlçfkj asdlkfj çalsdjf

O resultado obtido é esse:

O resultado desejado é esse:

Obs.: A linha vermelha é apenas para marcar o alinhamento e não faz
  parte do resultado desejado.

É possível fazer isso via CSS?
Answer: Acredito que utilizar o display: inline no elemento p é o que complica tudo. Como alternativa, você pode posicionar o elemento li:before de forma absoluta e definir uma margem esquerda para o elemento p. Veja:

ul {
  list-style: none;
  list-style-position: outside;
  padding-left: 0;
}

li {
  margin-bottom: 20px;
  position: relative;
}

li:before {
  content: "\2192";
  padding-right: 10px;
  position: absolute;
}

p {
  margin-left: 20px;
}

Item 1 alaksjd fçalksdj fçlaksjd fçlaksjd fçlkasdj flçkajsdlçkfjasldçkjflçaksd jfçlkasjd flçkajsdlkçf asd

Item 2 adflçaksd jglçakhsd flaksdh kjahsdf gjhdfjkh skjchvçz,xckhvj çzlxkcjv zçlxckjvlçz xckjvçzlxkcjv

Item 3 asdlçfkj asdlkfj çalsdjf

Comment: muito obrigado! Sua resposta me ajudou muito, e também consegui entender melhor o funcionamento. Ainda não tenho um bom relacionamento com CSS, rsrsrs... Se gostar de desafios como esse, [aqui vai mais um](https://pt.stackoverflow.com/questions/199424/como-ocupar-restante-da-section), haha...
Saudações!

Como alinhar itens da lista


CORS issue with a statically generated Nuxt 2 site and Netlify serverless function

Question: I'm encountering a CORS (Cross-Origin Resource Sharing) issue while attempting to make requests from a statically generated Nuxt.js site hosted on Netlify to a serverless function handling Mailchimp API requests. The serverless function is set up to subscribe users to a Mailchimp list.
I am able to successfully invoke the function using the Netlify CLI but when requesting client side (both locally and in prod) the function returns the below:
Access to XMLHttpRequest at 'https://us11.api.mailchimp.com/.netlify/functions/mailchimp/mailchimp' from origin 'https://localhost:3000' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.

I am setting both the headers in the serverless function and in the netlify.toml to allow cross-origin requests but as you can see in the error it seems I am hitting the Mailchimp API directly rather than proxying the endpoint so I am wondering if I am misunderstanding the approach to serverless functions or have missed a step in the process which is causing the error?
See code below:
netlify.toml
[dev]
  command = "yarn dev"
  targetPort = 3000

[build]
  command = "yarn generate"
  publish = "dist"
  functions = "functions/"

[[headers]]
  # Define which paths this specific [[headers]] block will cover.
  for = "/*"
    [headers.values]
    Access-Control-Allow-Origin = "*"

Form component
...
  methods: {
    async subscribe() {
      try {
        const response = await this.$axios.$post(
          "/.netlify/functions/mailchimp/mailchimp",
          { email: this.email }
        );
        console.log(response); // You can handle success message or redirect here
      } catch (error) {
        console.error("Failed to subscribe:", error);
        // Handle error (e.g., show error message)
      }
    },
  }

Serverless function
// Path: /functions/mailchimp/mailchimp

const mailchimp = require("@mailchimp/mailchimp_marketing");

mailchimp.setConfig({
  apiKey: process.env.MAILCHIMP_API_KEY,
  server: process.env.MAILCHIMP_SERVER,
});

const headers = {
  'Access-Control-Allow-Origin': '*',
  'Access-Control-Allow-Headers': 'Content-Type',
  'Access-Control-Allow-Methods': 'POST',
};

exports.handler = async (event) => {
  if (event.httpMethod !== 'POST') {
    return {
      statusCode: 405,
      body: 'Method Not Allowed',
      headers: { 'Allow': 'POST' }
    }
  }

  const data = JSON.parse(event.body)

  console.log(data);

  if (!data.email) {
    return { statusCode: 422, body: 'email is required.' }
  }

  const mailchimpData = {
    email_address: data.email,
    status: "subscribed",
    skip_merge_validation: true,
  }

  try {
    await mailchimp.lists.addListMember(process.env.MAILCHIMP_LIST_ID, mailchimpData)

    return {
      statusCode: 200,
      headers: {
        'Access-Control-Allow-Origin': '*',
        'Access-Control-Allow-Headers': 'Content-Type',
        'Access-Control-Allow-Methods': 'POST',
      },
      body: 'Your message was sent successfully!'
    }
  } catch (error) {
    return {
      statusCode: 422,
      headers: {
        'Access-Control-Allow-Origin': '*',
        'Access-Control-Allow-Headers': 'Content-Type',
        'Access-Control-Allow-Methods': 'POST',
      },
      body: `Error: ${error}`
    }
  }
}

Any insights, suggestions, or alternative approaches to successfully integrate the serverless functions be greatly appreciated. Thank you!
Answer: The CORS error you are experiencing is due to the serverless function calling the Mailchimp API directly, bypassing the Nuxt.js proxy. To resolve this issue, it is necessary to make the Mailchimp request through the Nuxt.js proxy.
Replace the serverless function:
const mailchimp = require("@mailchimp/mailchimp_marketing");

mailchimp.setConfig({
  apiKey: process.env.MAILCHIMP_API_KEY,
  server: process.env.MAILCHIMP_SERVER,
});

const headers = {
  'Access-Control-Allow-Origin': '*',
  'Access-Control-Allow-Headers': 'Content-Type',
  'Access-Control-Allow-Methods': 'POST',
};

const proxyMailchimpUrl = process.env.NUXT_PROXY_URL + '/mailchimp'; // Assuming Nuxt.js proxy is configured to route '/mailchimp' to the Mailchimp API

exports.handler = async (event) =>
{
  if (event.httpMethod !== 'POST') {
    return {
        statusCode: 405,
        body: 'Method Not Allowed',
        headers: { 'Allow': 'POST' }
    }
}

const data = JSON.parse(event.body);

if (!data.email) {
    return { statusCode: 422, body: 'email is required.' };
}

const mailchimpData = {
    email_address: data.email,
    status: 'subscribed',
    skip_merge_validation: true,
};

try {
    const response = await require('@nuxt/http').default.post(proxyMailchimpUrl, mailchimpData);
    console.log(response.data);

    return {
        statusCode: 200,
        headers: {
            'Access-Control-Allow-Origin': '*',
            'Access-Control-Allow-Headers': 'Content-Type',
            'Access-Control-Allow-Methods': 'POST',
        },
        body: 'Your message was sent successfully!'
    }
} catch (error) {
    console.error('Failed to subscribe:', error);
    return {
        statusCode: 422,
        headers: {
            'Access-Control-Allow-Origin': '*',
            'Access-Control-Allow-Headers': 'Content-Type',
            'Access-Control-Allow-Methods': 'POST',
        },
        body: `Error: ${error}`
    }
  }
};

This modified serverless function will proxy the Mailchimp request through the Nuxt.js proxy, ensuring that the CORS headers are correctly set and the request is routed to the Mailchimp API through the Nuxt.js proxy.
Comment: A serverless function isn't subject to the SOP or CORS.
Comment: The problem in the code above is that Nuxt.js makes a direct request to the Mailchimp API, bypassing the serverless function.  @jub0bs
Comment: @B_Cbk thanks for the response! Which Nuxt Proxy are your referring to? Unfortunately in my experience I cannot leverage the Axios module with proxies as I am using Nuxt static not universal (server), hence the serverless function. Or do you mean setting up some sort of middleware? Would you mind elaborating?
Comment: I just wanted to give you a quick answer in my busy schedule. Axios is unavailable, that's right. You should be able to make requests with `@nuxt/http` module in serverless function. If not, you can install `npm install @nuxt/http `and try using it. I'm updating the code above, if it doesn't work, I'll delete my post because a wrong solution shouldn't stay here. I gave the answers that may be within my knowledge. @strnr


From joint cdf to joint pdf

Question: We can get the joint pdf by differentiating the joint cdf, $\Pr(X\le x, Y\le y)$ with respect to x and y. However, sometimes it's easier to find $\Pr(X\ge x, Y\ge y)$. Notice that taking the complement doesn't give the joint CDF, so we can't just differentiate and flip signs. Is there still some simple rule to differentiate this and get the pdf?
Answer: A joint distribution has domain $(-\infty, \infty) \times  (-\infty, \infty)$. If we partition each component of the cartesian product in two by selecting some value $x$ and some value $y$, then we get $4$ subsets,
$$(-\infty, x] \times  (-\infty, y],\;\;(-\infty, x] \times  [y,\infty),\\
[x, \infty) \times  (-\infty, y],\;\;[x, \infty) \times  [y,\infty)$$
made up of intersections of two events,
$$A = P(X\le x), \;\; B = P(Y\le y)$$
and their corresponding complements.
Then (as the OP noted in a commnent),
$$\Pr(X\ge x, Y\ge y) = P(A^c\cap B^c) = 1 - P(A\cup B)$$
$$=1-\big[P(A) + P(B) - P(A\cap B)\big]$$
So it appears that by taking the cross-partial derivative of $\Pr(X\ge x, Y\ge y)$ we should again get the joint density. Let's verify that:
$$\Pr(X\ge x, Y\ge y) = \int_x^{\infty}\int_y^{\infty}f(s,t)dtds$$
$$\frac {\partial \Pr(X\ge x, Y\ge y)}{\partial y} = \int_x^{\infty} \left(\frac{\partial}{\partial y}\int_y^{\infty}f(s,t)dt\right)ds $$
$$=\int_x^{\infty}-f(s,y) ds$$
$$\frac {\partial^2 \Pr(X\ge x, Y\ge y)}{\partial y\partial x} = \frac {\partial }{\partial x} \int_x^{\infty}-f(s,y) ds = -\left(-f(x,y)\right) = f(x,y)$$
The above  also means that we can obtain the joint pdf from any of the four joint events indicated by the breakdown of the support -but in the other two cases, we should multiply by $-1$.
$$\begin{align} f(x,y) =& \frac {\partial^2 \Pr(X\le x, Y\le y)}{\partial y\partial x}\\
=&\frac {\partial^2 \Pr(X\ge x, Y\ge y)}{\partial y\partial x}\\
=&-\frac {\partial^2 \Pr(X\le x, Y\ge y)}{\partial y\partial x}\\
=&-\frac {\partial^2 \Pr(X\ge x, Y\le y)}{\partial y\partial x}
\end{align}$$
Comment: but can't I say $\Pr(X\ge x, Y\ge y) = 1 - (Pr(X \le x) + Pr(Y \le y) - Pr(X \le x, Y \le y))$. Thus I can differentiate twice which gets rid of the other terms and gives the pdf.
Comment: Oh dear, De Morgans laws, of course. Excellent. But no flipping signs here. I am editing my answer.

From joint cdf to joint pdf


Invoking lambda function manually simulating S3 ObjectCreated event trigger? (php aws sdk)

Question: We had a third party create a python based image thumbnail script that we set up to trigger on an S3 ObjectCreated event. We then imported a collection of close to 5,000 images after testing the script, but the sheer volume of the image files ended up filling up the lambda test space during the import and only about 12% of the images ended up having thumbnails created for them.
We need to manually create thumbnails for the other 88%. While I have a php based script I can run from EC2, it's somewhat slow. It occurs to me that I could create them 'on demand' and could avoid having to create thumbnails for all of the files that didn't auto-create already during the import.
Some of the files may never be accessed again by a customer - the existing lambda thumbnailer already has a slight delay that I account for in the javascript setTimeout retry loop, but before invoking this loop, I could conceivably check if it's a recent upload -- e.g. within the last 10 seconds -- whenever a thumbnail is not found then trigger the lambda manually before starting the retry loop.
But to do this, I need to have the ability to trigger the Lambda script with the parameters similar to the event trigger. It appears as though their script is only accessing the bucket name and key from the event values:
<code>bucket = event['Records'][0]['s3']['bucket']['name']
key = urllib.parse.unquote_plus(event['Records'][0]['s3']['object']['key'], encoding='utf-8')
</code>
Being unfamiliar with lambda and still somewhat new to the sdk, I am not sure how I do a lambda trigger that would include those values for the python script.
I can use either the php sdk or the javascript sdk. (or even the cli)
Any help is appreciated.
Comment: *"but the sheer volume of the image files ended up filling up the lambda test space during the import"*  You have to clean up the temp space yourself because you don't know if the container will be reused on a subsequent invocation... but only one Lambda function invocation at a time has access to a particular `/tmp` directory.
Comment: note, we third party contracted that piece. I would have cleaned the temp file if I had done it. (but I wasn't familiar enough with python/node or the lambda environment) Their's is now cleaning the temp space itself after receiving that error. Doesn't help us much now though, since the import is finished.
Answer: I think I figured it out, copying the data structure in the python references to create a bare-bones payload and triggering it as event:
<code>$lambda = $awsSvc->getAwsSdkCached()->createLambda();
//    bucket = event['Records'][0]['s3']['bucket']['name']
//    key = urllib.parse.unquote_plus(event['Records'][0]['s3']['object']['key'], encoding='utf-8')
$bucket = "mybucket";
$key = "somefolder/someimage.jpg";
$payload_json = sprintf('{"Records":[{"s3":{"bucket":{"name":"%s"},"object":{"key":"%s"}}}]}', $bucket, $key);

$params = array(
        'FunctionName' => 'ThumbnailGenerator',
        'InvocationType' => 'Event',
        'LogType' => 'Tail',
        'Payload' => $payload_json
);
$result = $lambda->invoke($params);
</code>