text:
Q: show table update time in oracle Apex I have a scenario where I am updating an table in oracle APEX (v 20.2.0.00.20) every day.
I would like to display the information in the page navigation bar at top or as a card anywhere on the page,  as when the table gets updated as
"Last updated : date & time"
Is this achievable or possible in oracle APEX , could not find any documents or information related to that?
Any leads would be great

A:
Step 1: Go to Shared components / Application Items and create one item. Call it whatever you want.

Step 2: Go to Shared components / Application Processes and create one and write your query to save the result into the Application Item that you created before.

Step 3 and final step: Add the Application Item into a new item in Shared components / Lists / Desktop Navigation Bar. You have to add a &ITEMNAME. as part of substitution string.

Also, you can use this item wherever you want because is stored in session

A: Presuming that table contains last_update_date column which is populated "somehow"  - could be a database trigger, for example:
create or replace trigger trg_biu_your_table
  before insert or update on your_table
  for each row
begin
  :new.last_update_date := sysdate;
end;
/

then you'd create an item (on that particular Apex page) whose source is SQL query which looks like this:
select max(last_update_date)
from your_table

That should do it.


text:
Q: Modify a specific line in HTML using grunt task I have a line in my html file like
    <script type="text/javascript" src="/path/jsfilename.js?ver=123">
The goal is to update the version number ?ver=123 by timestamp or some dynamic entity everytime the js file is updated on the server. How can I achieve this with a grunt task?

redpajama_set_name: RedPajamaStackExchange


text:
Q: Why doesn't a software VPN take advantage of an already existing Direct Connect connection? The official sample of AWS Advanced Networking Speciality questions contains a question about the most cost-effective connection between your
on-premises data centre and AWS ensuring confidentiality and integrity of the data in transit to your VPC (the question #7).
The correct answer implies establishing of the managed VPN connection between the customer gateway appliance and the virtual private gateway over the Direct Connect connection.
However one of the possible options in the list of answers offers a software VPN solution ("Set up an IPsec tunnel between your customer gateway and a software VPN on Amazon EC2 in the
VPC"). The explanation why this answer is incorrect says that:

it would not take
  advantage of the already existing Direct Connect connection

My question is: why would not this software VPN connection take advantage of the already existing DC connection? What's the principal difference here?

A: Option 1: The question is flawed.
If you built a tunnel between a customer gateway device and an EC2 instance with traffic routing through the Direct Connect interconnection, then you are quite correct -- that traffic would use the existing Direct Connect connection.
If, on the other hand, you built a tunnel from the customer gateway to an EC2 instance over the Internet, then of course that traffic would not use the Direct Connect route.
There appears to be an implicit assumption that a tunnel between a device on the customer side and an EC2 instance would necessarily traverse the Internet, and that is a flawed assumption.
There are, of course, other reasons why the native solution might be preferable to a hand-rolled one with EC2 (e.g. survival of a the complete loss of an AZ or avoidance of downtime due to eventual instance hardware failures), but that isn't part of the scenario.
Option 2.  The answer is wrong for a different reason than the explanation offered.
Having written and reflected on the above, I realized there might be a much simpler explanation: "it would not take advantage of the already existing Direct Connect connection" is simply the wrong justification for rejecting this answer.
It must be rejected on procedural grounds, because of the instruction to Choose 3.  Here are the other two correct answers.

A) Set up a VPC with a virtual private gateway.
C) Configure a public virtual interface on your Direct Connect connection.

You don't need to have either of these things in order to implement a roll-your-own IPSec tunnel between on-premise and EC2 over Direct Connect.  A Virtual Private Gateway is the AWS side of an AWS-managed VPN, and a Public Virtual Interface is necessary to make one of those accessible from inside Direct Connect (among other things, but it is not necessary in order to access VMs inside a VPC using private IPs over Direct Connect).
I would suggest that the answer you selected may simply be incorrect, because it doesn't belong with the other two, and the explanation that is offered misses the point entirely, and the explanation is itself incorrect.


text:
Q: For $n \geq 6$, why are the number of prime pairs $(p,q)$ where $p+q=6n$ > $6n+2$ and $6n+4$ pairs? Noticed a pattern for $n \geq 6$, the number of prime pairs $(p,q)$ where $p+q=6n$, is always greater than the pairs for $6n+2$ and $6n+4$.
For example, when $n=6$
$36$ has $8$ prime pairs
(5,31) (7,29) (13,23) (17,19) (19,17) (23,13) (29,7) (31,5)

$38$ has $3$ prime pairs
(7,31) (19,19) (31,7)

$40$ has $6$ prime pairs
(3,37) (11,29) (17,23) (23,17) (29,11) (37,3)

The charts below show peaks for $6n$ and troughs for $6n+2$ and $6n+4$

This pattern seems to continue indefinitely ...

Question
Does this pattern hold true for all $6n$ peaks?

A: As a few commentors have pointed out, a prime is either $1$ or $5$ (mod $6$), and single prime has a ~$50$% of being in either group. Thus, we only need one of each to get a sum of $6n$, but we need two numbers that are equal (mod $6$) to get $6n+2$ or $6n+4$ (only a $25$% chance).
The specifics of your question have likely been worked out here. You have found a cool visual way to see this!


text:
Q: Mailto link in paragraph creating line break in Talkback on Android I'm having this problem with a mailto link inside a paragraph, on Android using Talkback voice over:
image from Android

Lorem ipsum sit dolor amet email consectetur adipiscing elit. Vestibulum faucibus est lobortis.

In Talkback, when you tap and the voice over reads the text, it stops before "email," then you have to tap on "consectetur..." and that gets read as if it were a new section.
Essentially, the email link splits up a single paragraph into two sections. I want the paragraph to be read/viewed by Talkback as one paragraph.
Any insight appreciated.


text:
Q: How to generate SWIG interface from C++? Is there any way generate SWIG interface from existing C++ code, if I want to expose everything one-to-one for my Java application?
To clarify, this is 3rd-party library and I don't have headers for top level files to generate interface from them.

A: Because you don't have access to the header files, your only option is libraries that directly introspect the C++-based binaries. I would start by taking a look at JNA: it is the java equivalent of lua's libffi and python's ctypes. Since you need C++, look then at BridJ, nativelibs4java and JNAerator. I haven't used any so can't comment on their robustness or power.


text:
Q: What should be my query to get a list of nodes in firebase
What should be my query be if I want to get the list of all records which gender = 0 and userType = 1? I'm quite new to firebase and I can't find any sources that teaches compound some queries.

A:
first of all create a node name userList and add instances of user with key 0,1,2,3 and so on like in screen shot in question. It becomes an array of userList

List<User> userList = new ArrayList<>();
Firebase ref = new Firebase(FIREBASE_URL);

  ref.addValueEventListener(new ValueEventListener() {
      @Override
      public void onDataChange(DataSnapshot snapshot) {
          for (DataSnapshot postSnapshot: snapshot.getChildren()) {
            <User> user = postSnapshot.getValue(<User>.class);
            userList .add(user);
          }
      }
      @Override
      public void onCancelled(FirebaseError firebaseError) {
          Log.e("The read failed: " ,firebaseError.getMessage());
      }
  });

And you can also use Firebase RecyclerAdapter like this
Firebase is no SQL. it doesn't have where clause. You can use orderBy,startAt,endAt function to achieve filtering . See this and this.
Filter most on the server, do the rest on the client
 orderBy('gender')
  .startAt('0').endAt('0')

and in onDataChange
  for (DataSnapshot postSnapshot: snapshot.getChildren())
  {
       <User> user = postSnapshot.getValue(<User>.class);
       if(user.getUserType == 1)
           userList .add(user);
  }


text:
Q: Aws RedShift sampling For a data quality check I need to collect data in a specific interval.
Some tables are huge in size.
Is there any hack to do this without affecting the performance?
Like select 100 rows randomly.

A: How random do you need?  The classic way to do this is with "WHERE RANDOM() < .001".  If you need it to give you a repeatable "random" set then you can add a seed.  The issue is that your tables are huge and this means reading (scanning) every row from disk just to throw most of them away and since table scan can take a significant time this isn't what you want to do.
So you may want to take advantage of Redshift "limited table scan" capabilities as part of your "random" sampling.  (The fastest data to read from disk is the data you don't read from disk.)  The issue here is that this solution will depend on your table sort keys and ordering which will push the solution into even "more pseudo" random territory (less of a true random sampling).  In many cases this isn't a big deal but if the statistics really matter then this may not work for you.
This is done by sampling "blocks", not rows, based on the sort key(s).  This sampling of blocks can be done randomly and each block of data will represent about 250K rows (based on sort key data type, compression etc. and COULD range anywhere from <100K rows to 2M rows).  Doing this process will take a little inspection of STV_BLOCKLIST.  The storage quanta for Redshift is the 1MB block and each and every block's metadata in the system can be referenced in STV_BLOCKLIST.  This system table contains min and max values for each block.  First find all the blocks for the sort key for the table in question.  Next pick a random sample of these blocks (and if you are still dealing with a lot of data make sure that this sampling picks an even number from across all the slices to avoid execution skew).
Now the trick is to translate these min a max metadata values into a WHERE clause the performs the desired sampling.  These min and max values are BIGINTs and are hashed from the data in the sort key column.  This hash is data type dependent.  If the data type is BIGINT then the has is quite simple - if the data type is timestamp then it is a bit more complex.  But the ordering will be preserved across the hashing function for the data type involved.  Reverse engineering this hash isn't hard - just perform a few experiments - but I can help if you tell me the type involved as I've done this for just about every data type at this point.
You can even do a random sampling rows on top of this random sampling of blocks.  Or if you want you can just pick some narrow ranges of the sort key value and then randomly sample row and avoid all this reverse engineering business.  The idea is to use Redshift "reduced scan" capability to greatly reduce the amount of data read from disk.  To do this you need to be metadata aware in your choice of sampling windows which often means a sort key where clause.  This is all about understanding how the database engine works and using its capabilities to your advantage.
I understand that this answer is based on some unstated information so please reach out in a comment if something isn't clear.


text:
Q: Accessing to the zero position with a pointer Why can't we access for exemple position zero(0), one hundred(100),
two hundred(200) in the memory;
Ex:
void main() {
    int* a;
    a = 0;
    printf("what is inside position o %d",*a);

}

A: Quoting C11, chapter §6.5.3.2p4

... If an invalid value has been assigned to the pointer, the behavior of the unary * operator is undefined.

Quoting C11, chapter §note102

... Among the invalid values for dereferencing a pointer by the unary * operator are a null pointer, an address ...

 Emphasis mine
Also,
Quoting C11, chapter §6.3.2.3p3

An integer constant expression with the value 0, or such an expression cast to type void *, is called a null pointer constant. If a null pointer constant is converted to a pointer type, the resulting pointer, called a null pointer, is guaranteed to compare unequal to a pointer to any object or function.

You are thus trying to dereference a null pointer, the behavior of which has been explicitly said to be Undefined by the standard.

A: Apart from *(char*)NULL being undefined behavior, as Ajay Brahmakshatriya correctly points out, there is another reason why this won't work on any sane system: The linker and/or system kernel usually make special provisions to ensure that no accessible memory is ever mapped at address zero.
As such, any attempt to dereference a null-pointer will invariably trigger a hardware exception because there simply is no memory that the hardware could access. This hardware exception directly alerts the system's kernel about the condition, and the system's kernel usually reacts by killing the process with a segmentation fault.
The reason for this is that accidentally dereferencing a null-pointer is a really common mistake, and that it is generally not advisable to let a process continue doing possibly harmful stuff after it already entered the territory of undefined behavior. An immediate crash of the process is generally seen as the smaller evil. And it makes debugging of null-pointer accesses so much easier: If the process is being executed under a debugger, the debugger will directly point the programmer to the exact line that tried to dereference a null-pointer. The only thing that's left for the programmer to do, is to figure out why that line tried to dereference a null-pointer, and where the actual logical mistake was. This is much easier than with other forms of undefined behavior where the symptoms may appear at some fully unrelated location in the program.


text:
Q: FCM with Cloud Datastore I have a Java App Engine standard project (for about 4 years), using the Cloud Datastore (with Objectify). One of my services is using GCM to push notifications to mobile clients. Google has announced that GCM is deprecated and will be shut down 11th of April, and from then on Firebase messaging should be used instead of GCM.
After reading the docs it seemed straight forward to migrate, however I cannot create a Firebase database on my existing project, apparently I need to create a new App Engine project for this?
My question is, how can I use messaging on my existing App Engine project?
Starting a new project seems to me a bit overkill just to migrate from GCM to FCM.

A: Currently, once you select a database for your GCP project, you can't switch back. That's why you would have to create a new GCP project and a new App Engine.
I'm not very familiar with the Firebase products or the migration process from GCM to FCM, but if what you need is to switch from Cloud Datastore to Cloud Firestore, be aware that this change will be done automatically in the future.
You can also contact GCP support directly and request the upgrade.

A: I figured it out, I'm not able to create a new Firestore database, which is the "new" Firebase database currently in beta. This because I already using the Cloud Datastore in my current app engine project and cheese two cannot coexist whiten the same app engine project. However I was able to create a "old" Firebase database (real time database).
I don't really need a new database or my existing one migrated, I only need messaging to work (FCM) and using the Admin SDK the only way to initialise the library I need a database.


text:
Q: Multiple views iphone app - starter Hello I am quite new in iphone programming
and i am trying to create a new app with game elements
my problem is that i have a difficulty in undertanding delegates.. so in order to create multiple view this is what i have done
i created a switchview method which is called every time a button is pressed in order to go to the next screen.
- (void)switchView:(UIView *)View1 toView:(UIView *)View2
{

[UIView beginAnimations:@"" context:nil];
[UIView setAnimationCurve:0.75];
[UIView setAnimationTransition:UIViewAnimationTransitionFlipFromLeft forView:self.window cache:YES];
[window addSubview:View2];
[UIView commitAnimations];

}

My problem is that i want after the instruction to insert a viewController for video and then another one for finding and updating the location of the user..
Do i have to insert handle every viewcontroller from the AppDelegate.m
or is there another way??
e.g  the following code normally goes into the AppDelegate.m for the MediaPlayerViewController
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
MediaPlayerViewController *vc = [[MediaPlayerViewController alloc] init];
[[self window] setRootViewController:vc];
[vc release];

[self.window makeKeyAndVisible];
return YES;
}

how do i make it so after pressing the e.g start button the next screen with the video player pops up??
I am such a beginner it would be really helpful if smbd can answer..
Thanksss

A: From your description and code snippets it looks like you have manually implemented a UINavigationController - and in the process created a lot of work for yourself.
Apple provide the UINavigationContoller class as a core part of the UIKit framework for presenting users with a hierarchy of views.  This hierarchy is implemented using a stack data structure, where the stack is composed of a number of UIViewController instances.  The usage of a stack fits well with the navigation paradigm, as the user moves through the navigation hierarchy more views are pushed onto the stack.  Take for example the Contacts app, its UINavigationController contains at first a UIViewController listing all contacts.  Subsequently when a user taps on a contacts name they are presented with that contact's information.  This translates to a new UIViewController containing the contact's information being pushed onto the UINavigationController's stack.  Subsequently when the user moves back to the list of contacts they pop the contact information UIViewController from the stack.
The easiest way to see how this all works in practice is to create a new 'Navigation Based' project and look at the code.

A: I hope you might be knowing about inbuilt video player, you can make use of this to play video which can be presented as modal view:
MPMoviePlayerViewController *m_MoviePlayer =[[MPMoviePlayerViewController alloc] initWithContentURL:pUrl];
[self presentMoviePlayerViewControllerAnimated:m_MoviePlayer];


text:
Q: Counting # of index of undefined char array in C I'm trying to count the number of indexes of an undefined char array which is used as a parameter in the function.
I am already aware that if my array was fixed I can use "sizeof", which isn't the case here.
Attempt:
int counting(char *name3) {
  int count = 0;
  int i;

  //I have no idea what to put as my condition nor do I believe
  //I am approaching this situation correctly...
  for (i = 0; i < sizeof(name3); i++) {
      if (name3[i] != '\0') {
        count++;
      }
  }
return count;
}

Then if it is run by the following code
int main(void) {
char *name = "Lovely";
int x = counting(name);
printf ("The value of x = %d", x);

Prints: The value of x = 0
Any help or pointers would be amazing. Thank you in advance.

A: In C, Every string ends with '\0' (Null Character)
You can iterate until you meet the Null Character
The example code would be like this
char* name = "Some Name";
int len = 0;
while (name[len] != '\0') {
    len++;
}

Also, if it is a char pointer, not char array, sizeof(char*) will always return 4 in 32-bit application and return 8 in 64-bit application (the size of the 'pointer' itself - the memory address size)

A: #include <stdio.h>

int main()
{

    int i=0;
    char *name = "pritesh";
    for(i=0;;i++)
    {
        if(name[i] == '\0')
        {
            break;
        }
    }
    printf("%d", i);

    return 0;
}

This should work

note: this might be syntactically incorrect as I have not had my hands on c since a long time


text:
Q: Книга про профессиональный JavaScript Я прочитал "JavaScript руководство программиста" и потом ~год практиковался Я знаю клиентский JavaScript на уровне 7 из 10 Раньше не имел практики Ajax (небыло сервера) теперь есть "сервер" (Denwer), Учу PHP и хочу создать крупный проэкт (уже начал) где мне потребуется отличное знание КЛИЕНТСКОГО JS на уровне отличного понимания работы библиотеки JQuery (например просматривая её код узнал новые незнакомые ключевые слова (delete например) ) И уметь создавать кроссбраузерные так же использующие и современные технологии  скрипты. У меня есть "книга с носорогом" я начал её читать но она мне не понравилась...
Посоветуйте пожалуйста книгу по JS (очень желательно на русском) типа "сборник рецептов с описанием" про технологии клиента (и различии работы с ними в разных браузерах) и клиент-серверные технологии и всякие "фишки" js (Например я с удивлением узнал в википедии (о PHP) про любой_сценарий.php?=PHPE9568F36-D428-11d2-A769-00AA001ACF42)
PS: под

на уровне отличного понимания работы
библиотеки JQuery

имеется в виду знание тех принципов и методов которые использовал автор этой библиотеки при её написании, а не "умение пользоваться ею".
A:
имеется в виду знание тех принципов и методов которые использовал автор этой библиотеки при её написании, а не "умение пользоваться ею".

То есть вы хотите понять как на javascript написать аналог jquery?
Для этого следует почитать в книге с 'носорогом'(Javascript - подробное руковоство Д. Фленаган 5-е издание) главы 7,8,9 Объекты и массивы, функции, классы конструкторы и прототипы.
Если не усвоить ООП, то понимание принципов работы Jquery никогда не придет, сколько ни практикуйся. А для успешного завершения серьезных самописных проектов, создающихся в одиночку, рекомендуется хорошо знать C++, так как это дает понимание функционирования высокоуровневых языков и многих концепций программирования, в том числе и ООП.
A: Благодаря @Spectre (не зря плюсанул) нашёл как раз ту книгу которую искал -

John Resig Pro JavaScript™ Techniques

от автора JQuery. Правда не люблю на английском читать поэтому нашёл не последнее (шестое) 2010 г. а пятое 2008 г. зато полный русский перевод:

JavaScript. Профессиональные приемы
программирования

Так что вопрос можно считать закрытым, спасибо всем кто участвовал в его обсуждении.
A: Маккоу А. - Веб-приложения на JavaScript [2012, PDF, RUS].
A: Книга с носорогом не нравится?
Это хорошо
Это говорит о том что ты достаточно хорошо знаешь язык
Лично я в ней нашел очень много ошибок
Что касается книг - на озоне есть книга с птичкой шаблоны javascript и еще книгу его коллеги посмотри, они оба на яхо работают - вот книги и читай
Потом можешь взять код scriptjava.net и оптимизировать под свои нужды
Главное все заверни в функции чтобы убрать код из глобальной области видимости


text:
Q: possible javascript ajax call race condition so i am implementing in javascript this feature: when the document is opened by the user its data gets saved every 10 seconds and when the user closes it is saved one more time. It works seemingly well. Here is the implementation:
var data = "blabla";
var saveagain = false;
var t1;

function onDocumentOpen() {
    saveagain = true;
    savedata();
}

function onDocumentClose() {
    saveagain = false;
    savedata();
}

function savedata() {
    if (!saveagain) clearTimeout(t1);
    SaveDataAjaxCall(data, function() {
        //data was saved
        if (saveagain) t1 = setTimeout("savedata()", 10000);
    });
}

I was wondering if my approach is correct and if it can lead to some possible race condition in extreme circumstances such as:
when the savedata() instance called from onDocumentClose() is after the if(!saveagain) step, the savedata() instance called from the previous timer of the setTimeout() is before that step, so it gets to be called once more. Can this or anything more weird happen ?
Thanks in advance
EDIT:
After considering T.J. Crowder's and Bengi's comments I finalized the code as such:
var data = "";
var saveagain = false;
var t1;
var beingsaved = false;

function onDocumentOpen() {
    saveagain = true;
    savedata();
}

function onDocumentClose() {
    saveagain = false;
    savedata();
}

function saveData() {
    if (beingsaved) {
        if (!saveagain) setTimeout(saveData, 100);
        return false;
    }
    beingsaved=true;

    if (!saveagain) clearTimeout(t1);

    data=getData();

    SaveDataAjaxCall(data, function() {
        //data was saved
        beingsaved=false;
        if (saveagain) t1 = setTimeout(saveData, 10000);
    });

}

I think I have handled every occasion now. I think the beingsaved solution is equal to the atomic countr that T.J Crowder suggested.
EDIT2: Hm, I'm not sure i solved it because there may be a case when if(beingsaved) gets evaluated by the setTimeout call JUST before the beingsaved is set to true by the onDocumentClose call. Can this happen ?

A: I assume your save operation is asynchronous, as all good ajax operations should be. If so, you'll want to put some kind of guarding condition around it so that the two save triggers don't overlap. Or, of course, allow them to overlap but handle it server side (perhaps with a sequence number or timestamp), where it ignores an earlier save if a later one has already been committed.

A: No. Javascript is single-threaded (apart from innovations like WebWorkers and Co, which need to communicate on a event-based interface).
So once your synchronous execution is started (the global script, the timeout, the ajax event handler), it runs and can't be stopped. Everything else (new events, 0ms-timeouts, etc.) will be scheduled afterwards.
Your script contains 2 asynchronous scenarios: the timeout and the ajax callback. After you started the loop onDocumentOpen, it just goes like that:

*

*execute saveData: start ajax request

*wait (until ajax event happens)

*execute success callback: set a new timeout for saveData

*wait (until timeout event happens)

*execute saveData: start ajax request

*wait...

...and so on.
Your onDocumentClose can only execute during a wait period, when no other execution runs. You'd exspect the following:

*

*...execute saveData: start ajax request

*nothing happens

*ajax event: execute success callback: set a new timeout for saveData

*nothing happens

*documentClose event: clears the timeout, starts ajax request

*nothing happens

*ajax event: execute success callback: does not set a new timeout any more. End.

But you didn't secure the case when documentClose happens during the ajax request:

*

*...execute saveData: start ajax request

*nothing happens

*ajax event: execute success callback: set a new timeout for saveData

*nothing happens

*timeout event: execute saveData, start ajax request

*nothing happens

*documentClose event: clears the (non-existing) timeout, starts ajax request (a second time)

*nothing happens

*one of the ajax event: execute success callback: does not set a new timeout any more.

*nothing happens

*other ajax event: execute success callback: does not set a new timeout any more. End.

So it will always come to an end. If one of the events would fire during something executes, there just would be no "nothing happens" in between - but it will get executed one after the other. Even if the timeout should end during the execution of the ajax callback and before it is cleared, it will be de-scheduled when it's getting cleared after its end:
var id = setTimeout(function(){
    alert("still waiting for execution"); // never alerts
}, 500);
setTimeout(function(){
    alert("still waiting for execution"); // this alerts
}, 500);
for(var d = Date.now(); Date.now()-d < 1000; ) {
    ; // wait - the timeouts end during this heavy processing
}
clearTimeout(id);


text:
Q: ReactJS - How to detect when cancel is clicked on file input? I want an event or get notified when the user clicks on the cross icon or the cancel button on the fileInput dialog so that I can perform some task based on this.
The onChange event is only triggered when the user clicks on Open Button.
Is there a way to get notified when the user clicks on a cross icon or cancel button using ReactJS?

Below is the working code snippet.

class Test extends React.Component {
  constructor() {
    super();
    this.fileInputClicked = this.fileInputClicked.bind(this);
  }

  fileInputClicked(event){
    let file = event.target.files[0];
    console.log("File is Selected", file);
  }

  render() {
    return (

Hello world

            <input type="file" onChange={this.fileInputClicked}/>

    );
  }
}

ReactDOM.render(<Test/>, document.getElementById('app'))

A: Well, this is probably what I would do but I don't really like it, also I think that the whole idea of performing something because the user decided not to upload a file isn't a good user experience so use it wisely.
fileInputClicked(event){
        let file = event.target.files[0];
        console.log("File is Selected", file);
        window.removeEventListener('focus', this.handleFocusBack);
}

handleFocusBack(){
    console.log('focus-back');
    window.removeEventListener('focus', this.handleFocusBack);
}

clickedFileInput(){
    window.addEventListener('focus', this.handleFocusBack);
}

render() {
    return (

Hello world

                <input onClick={this.clickedFileInput} type="file" onChange={this.fileInputClicked}/>

    );
}

This way, when the user decides to close the file input, he focuses back on the window and you get the handleFocusBack functionality you want and when he adds a file he goes to the fileInputClicked.
Afaik, there is no 'out of the box' mechanism to achieve what you want.

A: A simple way is to verify your files array if empty or not.
The cancel event means that the user has not select any file which means :

event.target.files.length = 0

const onFileChange = (e) => {
    if(e.target.files.length ===0) {
      setFile(null); // undefined take place instead by default
      // the cancel event logics will always land here
    }
    else{
      setResume(e.target.files[0]);
    }
  }


text:
Q: Understanding types of layout handles I am going through this link to understand Layout handles. Here I have seen that the layout handles are in the form of [module_front_name]_[controller_name]_[action_name]. So, for example the layout handle for "Contact us" page is contacts_index_index, which calls the "indexAction" method available in "indexController" controller of "Contacts" module.
Later, I have seen other layout handles like:

*

*page_empty

*page_one_column

*page_two_columns_left

*page_two_columns_right

*page_three_columns
in "page.xml" layout file. (which are also in config.xml file of "page" module)
The above Layout handles are not in the form of [module_front_name]_[controller_name]_[action_name]. Then what are they?
My understanding is not  clear on both the types of Layout handles. (Are there any other Layout handle types?)
Please explain

A: Layout handles are somehow independent from the actions.
You can declare any layout handle you want as long as it is a valid XML tag.
Each action loads by default the handle [module_front_name]_[controller_name]_[action_name] but you can load any layout handle either in the controller, see an example here:
Mage_Catalog_CategoryController::viewAction()
$update->addHandle('catalog_category_layered_nochildren');

or you can load a handle inside an other handle using
<update handle="handle_here" />

See an example in the newsletter.xml layout file, inside the tag newsletter_manage_index.

A: In the next article the author digs deeper into layouts including creating your own layout handles.
http://magebase.com/magento-tutorials/digging-deeper-into-magentos-layout-xml-part-2/
Scroll about halfway down and there's a good explanation!


text:
Q: Let $f(x)$ be a differentiable function in $R\rightarrow R$ then how to obtain the derivative of $g(x)$ based on the following information Let $f:R\rightarrow R$ be a differentiable function such that $f(2)=2$ and
$\left | f(x)-f(y) \right |\leq5\left ( \left | x-y \right | \right )^{\frac{3}{2}}$, and $g(x)=x^3f(x)$, then what is the value of $g'(2)$.
Since, $g(x)=x^3f(x)$, by taking derivative both sides, we get:
$g'(x)=x^3f'(x)+3x^2f(x)$ which gives $g'(2)=8f'(2)+24$ on using the information $f(2)=2$. The answer is $24$, so I am sure that the $f'(2)$ will vanish but not able to understand how. If anybody could help me with the problem, it will be very beneficial for me. Probably, I have to use the $\left | f(x)-f(y) \right |\leq5\left ( \left | x-y \right | \right )^{\frac{3}{2}}$, but I am not sure how can I use this?.

A: \begin{align*}
\dfrac{\left|f(x)-f(2)\right|}{|x-2|}\leq 5|x-2|^{1/2}\rightarrow 0,
\end{align*}
as $x\rightarrow 2$.

A: Use the fact $$\left | f(x)-f(y) \right |\leq5\left ( \left | x-y \right | \right )^{\frac{3}{2}}$$ to show $f'(2)=0.$
Note that $$f'(2) =lim_{X\to 2 \frac {f(x)-f(2)}{x-2}}                               $$
$$|f(x)-f(2)|\le 5|x-2|^{3/2}$$
Therefore $$|\frac {f(x)-f(2)}{x-2}| \le 5|x-2|^{1/2} $$
Note that $$    lim_{x\to 0} 5|x-2|^{1/2} = 0$$ Thus $f'(2)=0$


text:
Q: How can I write a SPQuery to filter items based on a LinkFieldValue? I need to select a single value from a SharePoint list based on a field value. The type of the field is LinkFieldValue. How should I write the CAML query?
When I select the items with an empty query, I receive all the items in the list as expected.
When I add constraints to the query, it returns an empty result. I have tried constructing the query as follows:
string.Format("<Where><Eq><FieldRef Name=\"PollInstancePoll\" /><Value "
+"Type=\"Text\">{0}</Value></Eq></Where>",
new LinkFieldValue { NavigateUrl = "/az/Lists/Polls/DispForm.aspx?ID=1",
Text = "example poll" });

which results in the following query text:
<Where><Eq><FieldRef Name="PollInstancePoll" />
<Value Type="Text">example poll</Value>
</Eq></Where>

A: I have solved my problem with the following query:
new SPQuery
{
    Query =
        CAML.Where(
            CAML.And(
                CAML.Contains(
                    CAML.FieldRef("PollInstancePoll"),
                    CAML.Value(pollPath)),
                CAML.Contains(
                    CAML.FieldRef("PollInstancePage"),
                    CAML.Value(pagePath))))
};

Essentially I am checking only the URL part of the Link field, and providing the value for comparison as Type="Text". It is important to remember that SharePoint stores the values in database always as server-relative URLs.


text:
Q: Fast way of solving this iterative matrix equality in Python (with PyTorch) In one of my neural network implementations I have to solve the following problem:
w = f(v) with Lv = q+Dw, where w, v, q are vectors, D is a matrix and L is a diagonal matrix. This of course seems like a difficult dependency problem, but if we assume D is strictly lower triangular, the problem is iteratively solvable. For clarity I'll write out the problem below:
[l1  0  0 ... 0 ] [v1]     [ 0   0   0  ...  0] [w1]   [q1]
[ 0 l2  0 ... : ] [v2]     [D21  0   0  ...  :] [w2]   [q2]
[ 0  0 l3 ... : ] [v3]  =  [D31 D32  0  ...  :] [w3] + [q3]
[ :  :  : ... 0 ] [ :]     [ :   :   :       :] [ :]   [ :]
[ 0  0  0 ... ln] [vn]     [Dn1 Dn2 ...Dnn-1 0] [wn]   [qn]

[w1]     ( [v1] )
[ :] = f(  [ :]  )
[wn]     ( [vn] )

(I hope it is clear with the lack of math typesetting :P)
I solve this in a batch-wise setting, hence the vectors w, v, q are of the dimension (N_batch, n).
As I'm not a python expert, I now only see the possibility to solve this using the following iterative procedure:
l = torch.diag(L)  # size: (n,)
vi = [ (1 / l[0]) * q[:, 0] ]  # size: (N_batch, 1)
for i in range(1, n):
    # building up the vector w out of v1 ... vi
    w = f(torch.stack(vi, dim=1))
    # calculate the new vi with the new w vector
    vi.append( (1 / l[0]) * ( q[:,i] + torch.einsum('j,bj->b', D[i,:i], w) ) )
# final step
w1_n = f( torch.stack(vi, dim=1) )

This however takes up literally 85% of the time to calculate my one-step-forward procedure in the training of a neural network, hence it would be really nice to optimize this procedure :P
Is there some function I don't know that solves this, or is there some python guru around that can optimize my problem? Thanks in advance :D
MWE:
import torch
import time

n = 20
N_batch = 150
l = torch.rand(n)+1 # size: (n,)
q = torch.rand(N_batch, n)
f = torch.nn.Tanh()
D = torch.tril(torch.rand(n,n),diagonal=-1)

tic = time.time()
vi = [ (1 / l[0]) * q[:, 0] ]  # size: (N_batch, 1)
for i in range(1, n):
    # building up the vector w out of v1 ... vi
    w = f(torch.stack(vi, dim=1))
    # calculate the new vi with the new w vector
    vi.append( (1 / l[0]) * ( q[:,i] + torch.einsum('j,bj->b', D[i,:i], w) ) )
# final step
w1_n = f( torch.stack(vi, dim=1) )
print('Total time: ' + str(time.time()-tic))


text:
Q: Can $f \in C[0, 1]$ with a countable number of zeros be a zero divisor? Let us consider the ring of all continuous functions $ C[0,1]$. Let $f \in C[0,1]$ be such that $f$ has countable number of zeros.

Can $f$ be a zero divisor?

Surely $f$ can't be an unit. If it is a zero divisor then there must exist an element $g \neq 0$ such that $fg \equiv 0$. That is, $g$ must vanish on uncountable number of points in $[0,1]$. But I can't figure out if it's true.

A: Suppose that $f$ is a zero divisor, then there is $g \in C[0, 1]$, $g \neq 0$, such that $fg = 0$. That is, for every $x \in [0, 1]$, $(fg)(x) = f(x)g(x) = 0$. So, for every $x \in [0, 1]$ with $f(x) \neq 0$, we must have $g(x) = 0$; in particular, $g$ takes non-zero values on at most countably many points.
Denote the set of zeroes of $f$ by $A$. As $g$ must vanish on the complement of $A$, but $g \neq 0$, there is $a \in A$ such that $g(a) \neq 0$; without loss of generality, let's suppose $g(a) > 0$. As $g$ is continuous at $a$, there is $\delta > 0$ such that $g(x) > 0$ for $x \in (a - \delta, a + \delta)$ which contradicts the fact that $g$ is non-zero on at most countably many points.

A: Here $f$ cannot be a zero divisor. Suppose that $fg$ is zero and $g$ is nonzero. Clearly $g(x) = 0$ whenever $f(x) \neq 0$.
Let $c \in [0,1]$ be a zero of $f$. Suppose that $g(c) \neq 0$. By continuity of $g$, produce an interval $(c - \delta, c + \delta)$ on which $g$ is nonzero. Then $f$ must be zero on $(c - \delta, c + \delta)$. This contradicts that $f$ has countably many zeroes.


text:
Q: Rails 2 + Microsoft SQL Server: ActiveRecord returns -1 but SQL server returns records? Why does ActiveRecord always return -1 whether it's through a browser or through the console?
SQL statement:
SELECT category.categoryname,  sum(lineitems.qty) as totalSales,
sum(lineitems.qty*size.sizeship) as volume,
sum(lineitems.qty*lineitems.purcprice) AS totmerchandise  FROM category, products,
orders, shipments, lineitems, size  WHERE
category.categoryid = products.categoryid  AND products.productid =
lineitems.productid  AND lineitems.posshipid = shipments.posshipid  AND
shipments.posorderid = orders.posorderid  AND size.sizeid = products.size  AND
category.categoryid NOT IN (77,79)  AND orders.orderstatus in
(1,4,5)  AND orders.ordercomplete = 1  AND numbotincase > 0  AND orders.date >=
'20130501'  AND orders.date < '20130531'  GROUP BY
category.categoryname  ORDER BY category.categoryname`

When I execute this in Microsoft SQL server, it loads a bunch of records.
However, in Rails when I try to do this:
query_for_category_bottles_volume_totalsales = "SELECT category.categoryname,
sum(lineitems.qty) as totalSales,  sum(lineitems.qty*size.sizeship) as volume,
sum(lineitems.qty*lineitems.purcprice) AS totmerchandise  FROM category, products,
orders, shipments, lineitems, size  WHERE category.categoryid = products.categoryid
AND products.productid = lineitems.productid  AND lineitems.posshipid =
shipments.posshipid  AND shipments.posorderid = orders.posorderid  AND
size.sizeid = products.size  AND category.categoryid NOT IN (77,79)  AND
orders.orderstatus in (1,4,5)  AND orders.ordercomplete = 1  AND numbotincase > 0
AND orders.date >= '20130501'  AND orders.date < '20130531'  GROUP BY
category.categoryname  ORDER BY category.categoryname"

category_bottles_volume_totalsales = ActiveRecord::Base.connection.execute(query_for_category_bottles_volume_totalsales)

This happens not only for this query, but something simple like this as well: ActiveRecord::Base.connection.execute("select * from orders where id = 987;"). However, in the console when I do Order.find(987) it returns a record.

A: So the solution was to change the way ActiveRecord was making the query.
  database = ActiveRecord::Base.connection

  query_for_category_bottle_casecost_case_price = "SELECT ..."

  category_bottle_casecost_case_price = database.select_all(query_for_category_bottle_casecost_case_price)


text:
Q: Taking the Fourier transform of a Hankel function Considering the following inverse Fourier transform
$$ f(t) = -\alpha \int_{-\infty}^{\infty} F(\omega)H_0^{(2)}(k(\omega) \beta) \exp(+j\omega t) d\omega$$
where $F$ is an arbitrary function and $H_0^{(2)}$ is the Hankel function of second kind and order zero, and $\alpha, \beta$ are constant.
The main question is; how to evaluate the (inverse) Fourier transform of a Hankel function ?
I've been told that in order to evaluate this analytically almost everything requires approximations. Therefore, it is computed numerically in general.
Any suggestions on what method that should be used and why ?
Kind regards.

A: decompose the exponential function in terms of besselfunction as well as F, then integrate using the usual orhogonality relations.


text:
Q: GridBagLayout in cocoa Is there any feature equivalent to "GridBagLayout as in swing" in cocoa?
Spent some time in searching with no luck.
Any help or suggestions to create something like GridBagLayout in cocoa is appreciated:)
Thanks:)

A: There isn't. Closest thing to GridBagLayout in Java is probably the NSCollectionView displaying an array of content as a grid of views:
https://developer.apple.com/library/mac/#documentation/Cocoa/Reference/NSCollectionView_Class/Introduction/Introduction.html
https://developer.apple.com/library/mac/#documentation/Cocoa/Reference/NSCollectionView_Class/Introduction/Introduction.html#//apple_ref/occ/cl/NSCollectionView


text:
Q: How can I merge or concatenate 2 or more *.3gp files into jaust another 3gp file? In 2003 there was celular phones that record videos in the 3GP Format; I downloaded them to my computer; they were played by a software named Platform4Player by Philips. But now they can be played with Windows Media Player (WMP).
What I want to do now is: to join/merge or concatenate those 3gp files.
I am using Windows XP.
How can I do such a merge?
Someone can help me?
Isabel

A: Not familiar with that file format, but try the following -
copy /B fileA.3gp+fileB.3gp combined.3gp

A: FFMpeg will convert from 3gp to another format, and you can also use it to join the files together.
First you convert the files from 3gp to Mpg (which you can join together) and then convert the joined mpg file to a better format (smaller generally)
(you can use Bryan's joining method on .Mpg files, but not on 3gp's.)


text:
Q: Trying to checkin on Facebook through ShareLinkContent using FBSDKSharekit pod version 14.1.0 but no luck I'm trying to add checkin functionality on my app. I got the place Id from admin panel and If user wants to checkin their they can do that through my app using the code below, but for some reason this code is not working only posting the link without taking the location, even this code can post quote as well but no location.
PS: The Facebook app is in development mode and the place id is valid as the same place id is working on android.
    let content : ShareLinkContent = ShareLinkContent()
            content.contentURL = URL(string: "https://www.google.com")
            content.placeID = "493869400814446"
            let dialog = ShareDialog(
                viewController: self,
                content: content,
                delegate: nil
            )
            dialog.mode = .automatic
            dialog.show()


text:
Q: For each number $d$ dividing 12, list the a's with $1 \leq a < 13$ and $e_{13} (a) = d$ For each number $d$ dividing 12, list the a's with $1 \leq a < 13$ and $e_{13} (a) = d$
Can some explain the method of solving this number theory problem. Giving me a hard time, thanks.

A: Take any $a\neq 1$, for example, $2$. Now compute the successive powers of $a$:
$$2,4,8,3,6,12,11,9,5,10,7,1$$
We have been lucky: $2$ is a primitive root, that is, the powers of $2$ span every element of $\Bbb Z_{13}$.
Now, what would be $e(4)=e(2^2)$? And $e(5)=e(2^9)?$


text:
Q: Unable to load from csv to mysql table?  LOAD DATA LOCAL INFILE 'hr.csv' INTO TABLE hr_analytics  FIELDS TERMINATED BY '`' IGNORE 1 LINES(NO,SATISFACTION_LEVEL,LAST_EVALUATION,NUMBER_PROJECT,AVERAGE_MONTLY_HOURS,TIME_SPEND_COMPANY,WORK_ACCIDENT,LEFT,PROMOTION_LAST_5YEARS,SALES,SALARY)

when i run above query i get:

You have an error in your SQL syntax; check the manual that
  corresponds to your MySQL server version for the right syntax to use
  near 'LEFT,PROMOTION_LAST_5YEARS,SALES,SALARY)' at line 1

how to solve this?

A: The problem seems to be that LEFT is a MySQL key word. Try this:
LOAD DATA LOCAL INFILE 'hr.csv' INTO TABLE hr_analytics  FIELDS TERMINATED BY '`' IGNORE 1 LINES(`NO`,`SATISFACTION_LEVEL`,`LAST_EVALUATION`,`NUMBER_PROJECT`,`AVERAGE_MONTLY_HOURS`,`TIME_SPEND_COMPANY`,`WORK_ACCIDENT`,`LEFT`,`PROMOTION_LAST_5YEARS`,`SALES`,`SALARY`)

A: You have a problem because you use a reserved SQL word 'LEFT'.

If an identifier contains special characters or is a reserved word,
  you must quote it whenever you refer to it.

The identifier quote character is the backtick "`".


text:
Q: Excel VBA - Data Validation - Indirect List Error '1004' I am trying to indirectly reference a list in VBA but keep hitting Run Time Error 1004.
I need to add data validation to the range defined below, which will look at the value of the cell in the previous column to determine what list to show.
Any help will be greatly appreciated.
Range("Q2:Q" & LastRow).Select
 With Selection.Validation
    .Delete
    .Add Type:=xlValidateList, AlertStyle:=xlValidAlertStop, Operator:= _
    xlBetween, Formula1:="=INDIRECT(RC[-1])"
    .IgnoreBlank = True
    .InCellDropdown = True
    .InputTitle = ""
    .ErrorTitle = ""
    .InputMessage = ""
    .ErrorMessage = ""
    .ShowInput = True
    .ShowError = True
End With

NB I have also tried;
    .Add Type:=xlValidateList, AlertStyle:=xlValidAlertStop, Operator:= _
    xlBetween, Formula1:="=INDIRECT($P2)"


text:
Q: Should child objects not know parents while in views/view code? As of iOS 6, Apple thought Unwind Segues would be added to their layout/views. What this means is, when you're on the 7th view of a stack, you can pop back to any other one. For those of you pure OO fans (like myself), I cringed a little. I cringed even more when I learned these also work with pop-ups.
Why would a modal on top of a stack know about the Nth view before?
I'm a big fan of OO because when you stick to its principles, you don't get spaghetti. And once you have a complex set of modals that are shared among multiple navigation controllers, these Segues begin to cluster into a bunch of lines on your storyboard that effectively don't enhance the navigation (as compared to an Obj-Oriented solution), but take up space on your Storyboard.
If you change a parent view, you immediately break the unwind segue and have to edit all the code that pointed to it, which is one of the exact same reasons we avoid doing this in code.
This has made me cringe for awhile, and I don't see any questions that bring this up in relation to views.

A: Immutability is a principle in more than OOP.
Isolation is a principle in more than OOP.
Reaching out and touching whatever you feel like is a bad idea for the same reason pouring glue over the gears of a clock is a bad idea. Sure it holds the clock together but that only works well now. Eventually you want things to be able to move.
Functional programmers will complain about this by talking about side effects. They'll insist on avoiding them until the last minute.
OOP programmers will complain about this by talking about the service locator pattern and tell you to instead use pure dependency injection to make your dependencies explicit.
Lazy programmers will keep doing it anyway because they know by the time anyone catches them at it they'll already be at a different Job.
Rather than rail against the inevitable learn to refactor. Rather than preach ideals show how they can be followed. Rather than ask people to have faith show them the real benefits.
Either that or update the ol' resume.

A: The primary goal is not that your software follows some principles, but that the software provides the user experience that it should provide.
If your user interface designer declares - after thoughtful analysis - that the user should go from a three times nested inner screen directly to the outmost screen, then that's what your code needs to do. If you do this with code that goes against your principles, tough.
Apple has created this method because some people, in some situations, want to go straight to a specific screen sometimes. Much better than doing it by hand because you only get one animation, and your code stays unchanged if intermediate levels change.

A: Child objects should be able to get access to their parents.
Sure, from a philosophical point of view, they shouldn't, every piece of data should be nicely partitioned, etc. Unfortunately the real world has a tendency to bulldoze over every 'elegant' model without a second thought. So, if you make something with airtight, but abstract OO principles, you will likely make something useful for only a very small subset of problems, and make impossible everything else.

"There are only two kinds of languages: the ones people complain about and the ones nobody uses."

That's not to say you should abandon all reason, and make a tangled ball of mud and spaghetti. But, sometimes real-world problems need bits of zip-ties and duct tape in certain places, because no model will ever match the complexity of the real world.

if you make the language impossible to do stupid things in, you'll also make it impossible to do clever things


text:
Q: Does virtual inheritance increase the size of derived class?
Possible Duplicate:
object size with virtual

Does virtual inheritance change the size of the derived class? I executed the following code, where I have two derived classes one virtually inherited and the other non virtually inherited:
class A {
 public:
int a;
  virtual void a1();
};

class non_vir_der: public A{
 public:
int c;
  virtual void aa();
};

class vir_der: public virtual A{
public:
int d;
virtual void bb();
};

int main()
{
cout<<sizeof(non_vir_der)<<"\n";
cout<<sizeof(vir_der)<<"\n";
return 0;
}

output:
12 (imo: 4(int a)+ 4(int c)+ 4(vir ptr))
16 (extra 4?)
to check again if i had missed something, i tried the minimum code required, by deleting all ints in the classes and the output was:
4
4
the second output indicates that the two derived classes are of same size.
Why is the size of vir_der 16 in the first run, why is it not 12?

A: This behavior is completely implementation-specific and there are no guarantees about what will happen.  That said, most compilers implement virtual inheritance by having a single copy of the base class lying around, then having each instance of the derived class store a pointer inside its class body that points to that one unique instance.  That way, if you cast the object to its virtual base, the compiler can emit code to find out where that object is.  On a 32-bit system, this means that virtual inheritance might increase the size of the object by four bytes, as you've observed.
So why is there no difference if there are no data members?  I'm not sure, but I'm guessing that this is because the compiler is smart enough to realize that if you have a virtual base class with no data members, you don't ever actually need to access anything contained within it.  Consequently, the object can be optimized by eliminating the extra pointer to the virtual base, since there's never a way that it could be accessed.  I could be wrong about this, though.
Hope this helps!

A: Basically,when you declare a function or class virtual,the compiler instantiates a virtual
pointer which is required in case of UPCASTING .Actually,a virtual pointer table is created
where all virtual instances are stored with their actual address .Thus,when you inherited
virtual class in 2nd case ,an extra *vptr got created.
Now the second case, why is that 4 in both cases...That's completely compiler specific.
It should have been 1 in 1st case and 4 in 2nd case according to simple logic.
Thanx


text:
Q: Send additional info in security context I am using oauth2, and I have an authorization server and a (separate) resource server. A client gets a token from the authorization server and then uses the token to make requests to the resource server. When the resource server fetches the SecurityContext from the authorization server, I would like to add additional info. At the moment it gets the username of the user and I would like to add the user ID too.
In the authorization server I have the following setup:
public org.springframework.security.core.userdetails.UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
//... more logic in here
return new CurrentUser(user.getId(), user.getUsername(), user.getPassword(), true, true, true, true, grantedAuthorities);

}

where CurrentUser is defined as follows:
public class CurrentUser extends org.springframework.security.core.userdetails.User {

private Long userId;

public CurrentUser(Long userId, String username, String password, boolean enabled, boolean accountNonExpired,
                   boolean credentialsNonExpired, boolean accountNonLocked,
                   Collection<? extends GrantedAuthority> authorities) {

    super(username, password, enabled, accountNonExpired, credentialsNonExpired, accountNonLocked, authorities);

    this.userId = userId;

}

}
In the resource server Im trying to cast the principal to CurrentUser but the principal is just a String. Looks like it is not being sent. Do you have an idea what am I missing?
Authentication a = SecurityContextHolder.getContext().getAuthentication();

CurrentUser user = (CurrentUser)a.getPrincipal(); //throws exception

The resource server (a separate application) is configured as follows:
@Configuration
@EnableResourceServer
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class ResourceServerConfiguration extends
ResourceServerConfigurerAdapter
{
   private static final String RESOURCE_ID = "my_id";

   @Override
   public void configure(ResourceServerSecurityConfigurer resources)
{
    resources.resourceId(RESOURCE_ID).stateless(false);
}

@Override
public void configure(HttpSecurity http) throws Exception {
    http.authorizeRequests()
            .antMatchers("...").access("...")
            .and()
            .exceptionHandling().accessDeniedHandler(new OAuth2AccessDeniedHandler());
}
}

In the properties file of the resource server I have the necessary information where to validate the token:
security.oauth2.resource.token-info-uri=http://localhost:8000/auth-service/oauth/check_token
security.oauth2.client.client-id = my-client
security.oauth2.client.client-secret = password


text:
Q: Does the main clause determine everything? If the clause is If I disturbed you:

*

*If I disturbed you, I am sorry.

*If I disturbed you, I would give you money.

Both of them use the past tense of disturb in the 'if-clause'
According to the subjunctive mood of past, 2 means 'As I don't disturb you, I will not give you money' (assuming the opposite of the present fact or situation: past subjunctive).
According to the indicative mood, 1 means 'I disturbed you in the past and I am sorry now.'
1 and 2 use same if clause using the same disturbed (literally the same if-clause) but has two different meanings due to different main clauses (I am sorry and I would give you money).
How do you know if a speaker says 'if-clause' with the intention of indicative or subjunctive. Do I have to wait for the main clause that follows the 'if-clause'?
If so, does the main clause determine the mood of the 'if clause'? (An important fact is that "a speaker opens his mouth and says exactly the same sound/thing").

A: Distinguish Real vs Unreal,not Indicative vs Subjunctive
English conditional clauses like these should not be classed as
"subjunctive" vs "indicative" because English doesn't really have "moods"
in any inflectional or morphological sense of that term.
Instead of moods,
what English does have is
modals, which with
one unique exception, are what we must use whenever something is other than
real. And your reals always come in exactly one of English's two
inflectional tenses, either past or present.
It is convenient to group conditionals by the nature of the verbs in their
consequent
clauses,
which can therefore be exactly one of either real or unreal. All modals are by definition unreals.

*

*If I disturbedreal (past) you, I amreal (present) sorry.

*If I disturbedreal (past) you, I wouldunreal (modal) give you money.

In both your two cases, the if parts use a real verb: disturbed. It is
not "subjunctive".  The reality or lack of same is indeed indeterminate
until you get to the then part.  At that point, the first is real and the
second is unreal.
There are various other possibilities, including those with other reals and
other modals alike.  Remember that to make something unreal, you always
need a modal (or singular were).

*If I disturbreal (present) her, she always becomesreal (present) upset.

*If I disturbedreal (past) her, she always becamereal (past) upset.

*If I disturbedreal (past) her, she wouldunreal (modal) always become upset.

*If I canunreal (modal) disturb her, she mayunreal (modal) wake up.

*If I wereunreal (were) to disturb her, she mightunreal (modal) become upset.

*If she needunreal (modal) not be disturbed, I willunreal (modal) leave her in peace.

Here's a bit of background on this classification system. It works out much better than imagining things that English does not even have.
1. Reals
Real presents
These are actually "non-pasts", but most people call them presents.
Except for be, these have a special inflection in only the third-person
singular alone and nowhere else.

*

*She disturbs me.

*I disturb them.

*I am disturbed.

*You have got to be kidding!

*He has disturbed you.

*It has been stopped.

Real pasts
These are inflect for the past tense, with all persons and numbers
the same except for be.

*

*I disturbed her.

*They disturbed me.

*He did disturb her.

*It had been stopped.

*She was disturbed.

*I was going to disturb her.

*They were disturbed.

2. Unreals
All unreals are modal unreals except sometimes for be.
Unreals via modals
These always use one of the standard English modals plus an uninflected
lexical verb following.
Additionally, there are three pairings of modals that for
backshifting purposes pair a "present/non-past" version coupled with a "past"
version: will/would, shall/should, and may/might.

*

*I canmodal disturb her.

*Shallmodal I disturb her?

*He couldmodal disturb her.

*You shouldmodal not disturb her.

*I maymodal disturb her.

*I willmodal disturb her.

*I wouldmodal disturb her.

*They mightmodal have disturbed.

*Daremodal he disturb you?

*One needmodal not disturb them.

*Oughtn'tmodal you not disturb her now?

The zero modal
One other modal verb that comes into play with these uninflected lexicals
is the so-called "zero-modal". It isn't an actual word, but we can construe its existence here because it modally marks the verb following in the very same way that a written-out modal does.
This type of modal is found only in special clause types.

*

*They are insisting that I zero-modal be there early.

*They were insisting that I zero-modal be there early.

*God zero-modal bless you.

*Long zero-modal live the king.

*zero-modal Have a nice day.

Being modals albeit of the zero variety, these are all still necessarily
unreals. That's because all modals are always unreals.
Unreals via were
This occurs only with unreal were, normally the real plural past of be.
It is therefore morphologically distinct from the real past plural only when
it takes a singular subject.

*

*Imagine it wereunreal (were) so.

*He acted as if she wereunreal (were) here.

*If only she wereunreal (were) here.

*I wish this wereunreal (were) easier.

*She would have left us a note if she wereunreal (were) ready to leave.

*Unless she wereunreal (were) ready, she would leave us no note.


text:
Q: Is there a way to run experiment when it's located outside of folder containing main config? So I have the following structure:

project_config.yaml is the main config file:
@hydra.main(config_path="configs/project_config", config_name="project_config.yaml")
def my_app(cfg: DictConfig) -> None:
    print(OmegaConf.to_yaml(cfg))

Hovewer, when I try to run some_experiment.yaml like this:
python test.py +experiment_configs=some_experiments

it does't get found. The problem doesn't exist if I place experiment_configs folder inside project_config folder, however, I'd like the folder with experiments to be outside.
Is there a way to run experiment when it's located outside of project_config folder?

A: You can use --config-dir to add an additional directory to the config search path.
See --hydra-help or check the docs here.


text:
Q: Grep --line-buffered, can I search the same buffer with the results of the first grep? I'm searching a log file in the following format
<date> <connection from: ip> <new connection ID> <info>
<date> <connection ID> <info>

I'm using the following to get my IP but then searching for my connection ID takes a few minutes in this log file.
tail -f logfile | grep ip --line-buffered

Is it possible to first grep for the IP then continue searching based off the connection ID?
The connection ID is not predictable and the following lines in the log after my match are not necessarily my connection ID tied to my IP.

A: No.
When you do
tail -f logfile | grep "ip-address" --line-buffered

you will only get the lines matching the ip-address pattern. Further grep invocations to the pipeline after this would not be able to see any other lines from the original logfile.
Without seeing a few examples of how the logfile may look, it would be really difficult to (blindly) find a working solution.

A: You can use several patterns in your grep command, for example to grep both lines with 'ip' and 'connection ID':
tail -f logfile | grep -E 'ip|connection ID' --line-buffered


text:
Q: place a file permanently on cluster launched through dag First of all I want to create a folder named as ".ssh" in the cluster and after the creation of it I want it to be there permanently, this folder will be created in the directory i.e. "/home/ssm-user/" and then I want to place a private key in this folder which also needs to be permanent.
Currently I have to do this task manually every time I launch the cluster.
I have to open the aws-cli through session manager and then navigate to the directory mentioned above, then I create a folder ".ssh" with command "mkdir", once the folder has been created then I put my file in it in order to use that file.
But as already mentioned I only want to do this procedure once and after that it must be there whenever I launch my cluster.
Or, if there is any other process to craft that folder and place the file in it with the launch then it will really very helpful.


text:
Q: django - how do i access the child's Meta from the parent? I have the following forms, and I wish to know the child's Meta.model attribute from the parent. How do I do that?
class Profile_form(forms.ModelForm):

    @property
    def user_type(self):
        #access child meta here

    class Meta:
        abstract = True

class Form_A(Profile_form):
    class Meta:
        model = Some_model

A: Try using self._meta for accessing Meta class for self.


text:
Q: Testing subsequent function call on an Async function from React function component I'm trying to test that navigate function is called.  I've mocked the component with a jest, but due to the async / promise function it doesn't call the function in time for the test
Component
import React, { useEffect, useState } from 'react';
...
import { Dialog } from '../../../../common/components/Dialog';

const Component = () => {

  ...

  const handleSave= async (value) => {
    const { id } = await newRecord(value);
    navigate(APP_ROUTES.SOMELOCATION(id));
  };

  return (
    <button onClick={() => handleSave(someValue)} />
  );
};

Test
import { navigate } form '@reach/router';
jest.mock('@reach/router');

it('should call navigate when button is clicked', () => {
  wrapper.find('button').simulate('click');
  expect(navigate).toHaveBeenCalled();
});

It does however work if you do:
setTimeout(() => { expect(navigate).toHaveBeenCalled() }, 100)

A: After coming across: Stackoverflow: Flush all promises
I added this to my test and it appears to be passing now.  So now my test looks like this:
const flushPromises = () => new Promise(setImmediate);

it('should call navigate when button is clicked', async () => {
  wrapper.find('button').simulate('click');
  await flushPromises();
  expect(navigate).toHaveBeenCalled();
});

A: I think this happend because mouse click is asynchronous, so you should wait until it ends, try this:
it('should call navigate when button is clicked', async () => {
  await wrapper.find('button').simulate('click');
  expect(navigate).toHaveBeenCalled();
});


text:
Q: Android ListView click set all Checkboxs to enabled i am facing a strange behavior in my android ListView: I have disabled checkboxes in each row. When I click on a row it seems that the checkboxes go back to enable for a short time before launching the next activity (the result of a click).
Here are the previous click and the after click :

stationsfavoritesadapter.xml:
    <?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:descendantFocusability="blocksDescendants">

    <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:orientation="horizontal" android:layout_width="fill_parent"
        android:layout_height="50dp"
        android:background="@drawable/listviewborder">

        <CheckBox
            android:id="@+id/favorite_checkbox"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            style="?android:attr/starStyle"
            android:layout_alignParentLeft="true"
            android:layout_centerVertical="true"
            android:enabled="false"

            />

        <ImageView
            android:id="@+id/weatherimage"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_toRightOf="@id/favorite_checkbox"
            />

        <TextView
            android:id="@+id/StationNameText"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_toRightOf="@id/weatherimage"
            android:layout_alignTop="@id/weatherimage"
            android:textStyle="bold"
            />

        <TextView
            android:id="@+id/temperatureText"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_toRightOf="@id/weatherimage"
            android:layout_below="@id/StationNameText"
            />

        <TextView
            android:id="@+id/trailsText"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_below="@id/StationNameText"
            android:layout_alignParentRight="true"
            android:layout_marginRight="5dp"
            />

    </RelativeLayout>

</RelativeLayout>

Here is the adapter class with the getView() method :
    public class StationsFavoritesAdapter extends StationsAdapter{

    public StationsFavoritesAdapter(StationsManager stations)
    {
        _stationManager = stations;
        _data = new ArrayList<Map.Entry<String, Station>>();
        _data.addAll(_stationManager.GetFavorites().entrySet());

        _stationFilterList = _data;

    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent)
    {
        final View result;
        if (convertView == null)
        {
            result = LayoutInflater.from(parent.getContext()).inflate(R.layout.stationsfavoritesadapter, parent, false);
        }
        else
        {
            result = convertView;
        }

        final Map.Entry<String, Station> station = getItem(position);

        ((TextView) result.findViewById(R.id.temperatureText)).setText(station.getValue().get_temperature() + "°C");
        ((TextView) result.findViewById(R.id.StationNameText)).setText(station.getKey());
        ((TextView) result.findViewById(R.id.trailsText)).setText(station.getValue().get_trails().first + "/" + station.getValue().get_trails().second);

        CheckBox favoriteBox = (CheckBox)result.findViewById(R.id.favorite_checkbox);

        favoriteBox.setChecked(true);

        ImageView image = (ImageView)result.findViewById(R.id.weatherimage);

        if(station.getValue().get_weather().equals("sunny"))
        {
            image.setImageResource(R.mipmap.sunnyicon);
        }
        else if(station.getValue().get_weather().equals("storm-clouds"))
        {
            image.setImageResource(R.mipmap.snowicon);
        }
        else
        {
            image.setImageResource(R.mipmap.cloudyicon);
        }

        return result;
    }

}

And the ListView click event :
    @Override
public void onListItemClick(ListView parent, View w, int position, long id)
{
    String stationName = adapter.getItem(position).getKey();
    Intent intent = new Intent(this, StationActivity.class);
    Bundle b = new Bundle();
    b.putString("Station name", stationName);
    intent.putExtras(b);

    startActivity(intent);
}

Thanks for your time.

A: Your getView functions gets called eveytime  the app is draws the list view.  I think what you want to do is do a onclicklistener on your list view then set the check box to true there, not in the getview
Use this code in your activity or fragment
listView1.setOnItemClickListener(new. OnItemClickListener() {
                @Override
                public void onItemClick(AdapterView<?> parent, View view, int position,
                        long id) {

                }
            });

A: You could try setting the checkbox to disabled from within your getView method in the adapter, after you have checked the box:
@Override
    public View getView(int position, View convertView, ViewGroup parent){

    CheckBox favoriteBox =(CheckBox)result.findViewById(R.id.favorite_checkbox);

    favoriteBox.setChecked(true);
    favoriteBox.setEnabled(false);


text:
Q: Azure search API - search filter syntax I'm using the azure search api trying to filter by a certain field value:  businesstype = store.   It always returns 3 stores, even though I should have thousands.  I can't tell for sure what's inside the index. In the Azure search web portal I type businessType eq 'store' and it gives me two stores, then starts returning businesstype = restaurant.  Not sure what is going on.  We have other implementations in other projects where filters are working.    Here's code that I'm executing as it is invoked by using ASP.NET Web API
  var indexClient = new SearchIndexClient(GlobalSettings.SearchServiceName, $"businesses{GlobalSettings.Environment}", new SearchCredentials(GlobalSettings.SearchServiceAdminApiKey));

        if (latitude == null && longitude == null)
        {
            //chicago
            latitude = 41.8333925;
            longitude = -88.0121478;
        }

        // get all attributes and camel case them
        var attributes = typeof(BusinessSearchItem).GetProperties().Select(x => char.ToLowerInvariant(x.Name[0]) + x.Name.Substring(1)).ToList();
        var parameters = new SearchParameters
        {
            Select = attributes,
            QueryType = QueryType.Full,
            Top = take,
            Skip = skip,
            IncludeTotalResultCount = true,
            OrderBy = new List<string>() { $"geo.distance(location, geography'POINT({longitude} {latitude})')" }
        };

        // filters
        string filter = "";
        if (!string.IsNullOrEmpty(businessType))
        {
            switch (businessType.ToLower())
            {
                case "restaurant":
                    filter += "businessType eq 'Restaurant'";
                    break;

                case "store":
                    filter += "businessType eq 'Store'";
                    break;
            }// end switch on business type
        }

        parameters.Filter = filter;

        try
        {
            // run the search
            var results = indexClient.Documents.Search<BusinessSearchItem>(q, parameters);
            Logger.Log.Info($"Search conducted. Query: {q} Business Type: {businessType} Lat: {latitude} Long: {longitude} User: {username}");
            var businessDTOs = results.Results.Select(x => new BusinessDTO
            {
             .........
            ).ToList()
            }).ToList();

the model BusinessSearchItem has a field BusinessType of string that has the attribute searchable. The skip is 0 and take 40.

A: The problem wasn't the search at all, it was that the data was not in the index


text:
Q: How to sort item in java combobox I have a java form using JCombobox. There is a "text field", "combobox" and "add" button. When I enter text in the text field, then click Add button, the text in the text field will fill into combobox, but it doesn't sort by a-z.
form screenshot
Below is my code in Add button.
private void cmdAddActionPerformed(java.awt.event.ActionEvent evt) {
    if(MyInput.checkText(txtField)){   //MyInput is my own method code to check if the text is entered.
        String st=txtField.getText();
        combox.addItem(st);
        String st1="";
        String st2="";
        int com=st1.compareTo(st2);
        if(com<0){     //I create this string comparison
                       //I need to add the "sort" code here
        }else{

        }
    }else
        JOptionPane.showMessageDialog(this, "Please enter text.");  //When no text is entered, this message appears.
}

Full source code:
import PlugIn.MyInput;
import javax.swing.JOptionPane;

public class JCombo extends javax.swing.JFrame {

    /**
     * Creates new form JCombo
     */
    public JCombo() {
        initComponents();
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">
    private void initComponents() {

        txt = new javax.swing.JTextField();
        combo = new javax.swing.JComboBox();
        cmdAdd = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        txt.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                txtActionPerformed(evt);
            }
        });

        combo.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                comboActionPerformed(evt);
            }
        });

        cmdAdd.setText("Add");
        cmdAdd.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                cmdAddActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(88, 88, 88)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addComponent(txt)
                    .addComponent(combo, 0, 188, Short.MAX_VALUE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(cmdAdd)
                .addContainerGap(63, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(40, 40, 40)
                .addComponent(txt, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(combo, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(cmdAdd))
                .addContainerGap(206, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>

    private void txtActionPerformed(java.awt.event.ActionEvent evt) {
        // TODO add your handling code here:
    }

    private void cmdAddActionPerformed(java.awt.event.ActionEvent evt) {
        if(MyInput.checkText(txtField)){   //MyInput is my own method code to check if the text is entered.
            String st=txtField.getText();
            combox.addItem(st);
            String st1="";
            String st2="";
            int com=st1.compareTo(st2);
            if(com<0){     //I create this string comparison
                           //I need to add the "sort" code here
            }else{

            }
        }else
            JOptionPane.showMessageDialog(this, "Please enter text.");  //When no text is entered, this message appears.
    }

    private void comboActionPerformed(java.awt.event.ActionEvent evt) {
        // TODO add your handling code here:
    }

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(JCombo.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(JCombo.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(JCombo.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(JCombo.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new JCombo().setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify
    private javax.swing.JButton cmdAdd;
    private javax.swing.JComboBox combo;
    private javax.swing.JTextField txt;
    // End of variables declaration
}

A: Use a SortedComboBoxModel: (How to sort the jComboBox elements in java swing?)
String[] items = { "one", "two", "three" };
SortedComboBoxModel<String> model = new SortedComboBoxModel<String>(items);
JComboBox<String> comboBox = new JComboBox<String>(model);
comboBox.addItem("four");
comboBox.addItem("five");
comboBox.setSelectedItem("one");

A: You have to take care of the order yourself.

*

*Use getModel() for getting the current list

*Figure out where the item should go

*Use insertItemAt(E item, int index) to place the item int the correct position.


text:
Q: Open file manager error android Hi there all developers:
I am using this code snippet
Intent intent = new Intent(Intent.ACTION_PICK);
intent.setAction(Intent.ACTION_GET_CONTENT);
intent.setType("file/*");
startActivityForResult(Intent.createChooser(intent, "Select File"), SELECT_FILE);`

There exists a file manager, but its giving a messege<< No apps can perform this action. Why?? Can anyone tell me?
I have also tried without Intent.ACTION_PICK

A: Please put my code.
it is working.
* CODE *
Intent intent = new Intent();
intent.setAction(Intent.ACTION_GET_CONTENT);
intent.setType("file/*");
startActivity(intent);


text:
Q: Radius of convergence of complex series $\sum^\infty_{n=10}\frac{n}{2}(z-1)^{n}$ I'm trying to find the radius of convergence of the following complex series:
$$\sum^\infty_{n=10}n(z-1)^{2n}$$

I've started by rewriting the above series as follows : $$\sum^\infty_{n=20}\frac{n}{2}(z-1)^{n}$$
This makes it a bit clearer that the radius of convergence $R$  can be found using :
$$\frac{1}{R} = \lim_{n \to \infty }\sup{\sqrt[n]{a_n}} = \lim_{n \to \infty }{\sup \left ({\frac{n}{2}}\right)^\frac{1}{n}} $$
So, the problem is reduced to evaluating the above limit superior. How do I proceed to evaluate this limit?

Some thoughts

*

*I'm under the impression that squeeze theorem could be useful
here.

*Aiming for the above, could I use some inequality between $\lim\sup{\sqrt[n]{a_n}}$ and $\lim{\sqrt[n]{a_n}}?$


text:
Q: Error 1004 Looping through range to get max date I am currently learning VBA and cant figure this one out. I'm trying to look at the max date in a range (W:AC) of each row and place the result in cell "BU" of the same row. I'm getting a 1004 error on the line defining which cell to place the result. Am I getting the error because I have defined the range as W:AC?

Sub Max_Date()
Dim MaxDate As Date
Dim CellRange As Range
Dim Source As Worksheet: Set Source = ActiveWorkbook.Sheets("Sheet1")
Dim row As Variant
row = Source.Rows.Count

Set CellRange = Source.Range("W:AC")

For Each row In CellRange

 MaxDate = Application.WorksheetFunction.Max(CellRange)
 Range("BU").Value = MaxDate

Next row

End Sub

A: As SJR mentioned you cannot paste a value in a row.
But also, you are looking at a max in the entire range, not only the row.
Use an integer (here i) to go through each row.
This should to the trick
Sub Max_Date()
Dim MaxDate As Date
Dim i As Double
Dim Source As Worksheet: Set Source = ActiveWorkbook.Sheets("Sheet1")
Dim row As Variant
row = Source.Rows.Count

For i = 1 To row

 MaxDate = Application.WorksheetFunction.Max(Source.Range("W" & i & ":AC" & i))
 Range("BU" & i).Value = MaxDate

Next

End Sub


text:
Q: jqgrid validation when editing a record I have now a problem with validation of a record that is being edited.
The edit form (and the add form) has a field called "email". That field should be unique in database, so I use ajax to validate it, by mean of this function:
function check_email(value, colname) {
    $.ajax({
        url: '@Url.Action("CheckEmail")',
        data: { email: value },
        type: 'POST',
        async: false,
        datatype: 'text',
        success: function (data) {
            if (!data) result = [true, ""];
            else result = [false, colname + ": ya existe en el sistema"];
        }
    })
    return result;
}

This works, but the problem is when I am editing the record. Of course e-mail exists in this case, so it is not allowing me to save the record.
The algorithm might be: it should validate only if id is > 0 and the entered e-mail is different from the existing value. In other words, validation must occur if the user is changing e-mail.
I spent a lot of time trying to figure out how to know if the editform is for adding or for editing, and even more, I was trying to find the value of the primary key of the record being edited, without any success.
Any help will be appreciated,
EDIT:
This is the code of the grid:
    $("#personal").jqGrid({
        url: "@Url.Action("List")",
        datatype: "json",
        mtype: "GET",
        colNames: ["Departamento",
                   "Nombres",
                   "Apellido Paterno",
                   "Apellido Materno",
                   "RUT",
                   "Contraseña",
                   "Fecha Nacimiento",
                   "Fotografía",
                   "Estado Civil",
                   "Género",
                   "Dirección",
                   "Cargo",
                   "E-mail",
                   "Fecha Ingreso",
                   "Creación",
                   "Modificación"],
        colModel: [
            { name: "dep_id", index: "dep_nombre", editable: true, edittype: "select", formatter: 'select', editoptions: { width: 100, value: "@ViewData["Departamentos"]" }, width: 250, editrules: { required: true }, formoptions: { elmsuffix: '*' }, stype: 'select', searchoptions: { sopt: ['eq'], value: "@ViewData["Departamentos"]" } },
            { name: "per_nombres", index: "per_nombres", editable: true, width: 250, editoptions: { maxlength: 80, size: 32 }, editrules: { required: true }, formoptions: { elmsuffix: '*' } },
            { name: "per_apellido_paterno", index: "per_apellido_paterno", editable: true, width: 250, editoptions: { maxlength: 80, size: 32 }, editrules: { required: true }, formoptions: { elmsuffix: '*' } },
            { name: "per_apellido_materno", index: "per_apellido_materno", editable: true, width: 250, editoptions: { maxlength: 80, size: 32 } },
            { name: "per_dni", index: "per_dni", editable: true, width: 100, editoptions: { maxlength: 20, size: 17, dataInit: function (el) { $.mask.definitions['~'] = '[0-9kK]'; $(el).mask("?99.999.999-~"); } }, editrules: { required: true, custom: true, custom_func: is_rut }, formoptions: { elmsuffix: '*' }, searchoptions: { dataInit: function (el) { $.mask.definitions['~'] = '[0-9kK]'; $(el).mask("?99.999.999-~"); } } },
            { name: "per_contrasena", editable: true, edittype: "password", hidden: true, width: 100, editoptions: { maxlength: 50, size: 17 }, editrules: { required: false, edithidden: true } },
            { name: "per_fecha_nacimiento", index: "per_fecha_nacimiento", editable: true, width: 100, editrules: { date: true, required: false }, formatter: 'date', formatoptions: { srcformat: 'SortableDateTime', newformat: 'd-m-Y' }, editoptions: { size: 17, dataInit: function (el) { $(el).datepicker({ dateFormat: 'dd-mm-yy' }); $(el).mask("?99-99-9999"); } }, searchoptions: { dataInit: function (el) { $(el).datepicker({ dateFormat: 'dd-mm-yy' }); $(el).mask("?99-99-9999"); } } },
            { name: "per_fotografia", index: "per_fotografia", editable: true, width: 250, edittype: "file", editoptions: { maxlength: 255, size: 32 } },
            { name: "per_estado_civil", index: "per_estado_civil", editable: true, edittype: "select", editoptions: { value: ":;S:Soltero;C:Casado;V:Viudo;D:Divorciado" }, width: 100, stype: 'select', searchoptions: { sopt: ['eq'], value: ":;S:Soltero;C:Casado;V:Viudo;D:Divorciado" } },
            { name: "per_sexo", index: "per_sexo", editable: true, edittype: "select", editoptions: { value: ":;M:Masculino;F:Femenino" }, width: 100, stype: 'select', searchoptions: { sopt: ['eq'], value: ":;M:Masculino;F:Femenino" } },
            { name: "per_direccion", index: "per_direccion", editable: true, width: 250, editoptions: { maxlength: 512, size: 32 } },
            { name: "per_cargo", index: "per_cargo", editable: true, width: 100, editoptions: { maxlength: 50, size: 32 } },
            { name: "per_email", index: "per_email", editable: true, width: 100, editoptions: { maxlength: 80, size: 32 }, editrules: { email: true, required: false, custom: true, custom_func: check_email } },
            { name: "per_fecha_ingreso", index: "per_fecha_ingreso", editable: true, width: 100, editrules: { date: true, required: false }, formatter: 'date', formatoptions: { srcformat: 'SortableDateTime', newformat: 'd-m-Y' }, editoptions: { size: 17, dataInit: function (el) { $(el).datepicker({ dateFormat: 'dd-mm-yy' }); $(el).mask("?99-99-9999"); } }, searchoptions: { dataInit: function (el) { $(el).datepicker({ dateFormat: 'dd-mm-yy' }); $(el).mask("?99-99-9999"); } } },
            { name: "per_creado_el", index: "per_creado_el", editable:false, search:false, width: 100, align: "center", formatter: "date" },
            { name: "per_modificado_el", index: "per_modificado_el", editable:false, search:false, width: 100, align: "center", formatter: "date" },
        ],
        jsonReader: {
            repeatitems: false,
            id: "per_id"
        },
        pager: "#pager",
        rowNum: 10,
        rowList: [10, 20, 30],
        sortname: "per_apellido_paterno",
        sortorder: "asc",
        viewrecords: true,
        gridview: true,
        autoencode: true,
        multiselect: true,
        shrinkToFit: false,
        caption: "Funcionarios",
        editurl: "@Url.Action("AjaxEdit")",
        height: '100%',
        width: 935,
        rownumbers: true,
        rownumWidth: 40
    });

    $("#personal").jqGrid('hideCol', ["per_fotografia", "per_direccion"]);
    $("#personal").jqGrid('navGrid', '#pager', { edit: true, add: true, del: true, search: false }, { width: 500 }, { width: 500 }, {}, { multipleSearch: false, multipleGroup: false });
    $("#personal").jqGrid('filterToolbar', { searchOperators: false });

    $.jgrid.edit.addCaption = "Agregar Funcionario";
    $.jgrid.edit.editCaption = "Modificar Funcionario";
    $.jgrid.edit.saveData = "¡El funcionario fue modificado! ¿Almacena los cambios?";

    $.jgrid.formatter.date.newformat = 'd-m-Y H:i';

Thanks
Jaime

A: I think you should send the record ID for verification.
function check_email(value, colname) {

    var rowid = jQuery('#personal').jqGrid('getGridParam', 'selrow');

    $.ajax({
        url: '@Url.Action("CheckEmail")',
        data: { email: value, rowid: rowid },
        type: 'POST',
        async: false,
        datatype: 'text',
        success: function (data) {
            if (!data) result = [true, ""];
            else result = [false, colname + ": ya existe en el sistema"];
        }
    })
    return result;
}

and so the server has any record can be checked with the ID does not match with the rowid.


text:
Q: Math contest geometry proof problem 2 Could someone help me with this?
Let A, B, C, D, L, M, N be distinct points in the plane such that A, B, C, D are the vertices of a square with sides AB, BC, CD, DA and L, M, N lie on the sides AB, CD, BC respectively. If M is the mid-point of CD, then show that △LMN is not an equilateral triangle.


text:
Q: Backup with local manifest I use rsync to backup files to a remote server in a UNIX environment. As my local machine is the only one with write access to the backup files, I know the status of the backup files on the remote machine will not change between my backup cycles.
Can I use this knowledge to avoid comparing the files over the network each time I run my backup? Like storing a local manifest after each backup and comparing the local file system to that manifest instead of the remote filesystem? If rsync can't do this, is there another piece of software, that can?
I am looking for something similar to the --listed-incremental option for tar.
Note: The same question applies to one of my deployment scripts, where I know that the remote files won't change between deployments.
Edit to clarify the difference to #481295:
Question #481295 asks whether the rsync scan speed can somehow be improved. My question is more specific as it states that the remote server files will not change if I do not run my backup. Can I use this piece of information to make the comparing of the file list a local process. (Manifest, …?)


text:
Q: Does the norm of a normed linear space determine the form of its dual spaces elements? Hello everybody,
As an introductory example, suppose $U \subset R^n$ is open and bounded, let $p = 2$. Then there is a constant $c>0$ s.t. $\forall u \in W^{1,p}_0 : \Vert u \Vert _ {W^{1,p}_0} \le c \Vert \vert \nabla u \vert\Vert_{L^p(U)}$. This implies that the latter expression defines an equivalent norm on ${W^{1,p}_0}$.
Let $f \in L^2(U), g \in C^1(\bar{U})$. Then there exists an unique solution $u \in W^{1,p}$ to the system $ \triangle u = f $ over $U$, $u = g$ over $\partial U$ - or equivalently, there exists an unique solution $u \in W^{1,p}_0$ to the system $ \triangle u = f - \triangle g$ over $U$, (in the distributional sense).
Proof: $W^{1,2}_0$ is a Hilbert space, hence self-dual. The rhs $f - \triangle g$, defines an element of $D'$, which by density can extended to $W^{1,2}_0$. On the other side, the equivalent norm as introduced above is defined the inner product $(u,v) = \int \nabla u \cdot \nabla v$, by riesz' representation theorem, there is an $u \in W^{1,2}_0$ s.t. the induced form $(u, \cdot)$ coincides with the form defined by the rhs. But then this $u$ is a weak solution to $ \triangle u = f - \triangle g$.
So far, so good. I would like to ask some questions on this.
i) Can this be extended to other dual exponents $p$, $q$ ?
ii) The equivalent norm that regards first derivatives only is not only an equivalent norm for $p=2$, but also for $1 \leq p < \infty$. In the above case, it seems the norm imposes a form the dual vectors are subject to. I wonder whether in general - not only in the case of $L^p$ and its friends - there is some way how the form of linear functionals on some normed space $X$ are determined by the norm attached to the vector space $X$.
I hope this questions ain't too vacuous and there are interesting answers. In either case, thanks.

A: The argument you have presented is an adaptation of the Lax-Milgram theorem which is essentially equivalent to the Riesz representation theorem (and generally speaking both of these results hold only in the Hilbert space framework). The Lax-Milgram theorem fails for the Laplace equation in $L^p$-spaces with $p\neq2$. Instead, some analogous results based on the ideas of coercivity, duality and monotonicity can be obtained in any reflexive Banach space.
The Dirichlet problem for the $p$-Laplace operator
$$-\nabla(|\nabla u|^{p-2}\nabla u)=f,\quad x\in\Omega,\qquad (*)$$
$$u=0,\qquad x\in\partial\Omega,$$
might be a "correct" $L^p$-analogue of the problem described in the question.
The right hand side of $(*)$ gives rise to the mapping $A: W_{0}^{1,p}\to(W_{0}^{1,p})^{*}$
defined by the identity
$$\langle Au,v\rangle=\int_{\Omega}|\nabla u|^{p-2}\nabla u\cdot\nabla v\ dx\quad \mbox{for all }  v\in W_{0}^{1,p}.$$
A straightforward check shows that $A$ satisfies the conditions of the following theorem
(which might be viewed as an $L^p$-analogue of the Lax-Milgram theorem).

Theorem. Let $A$ be a strictly monotone, coercive operator from a reflexive Banach space $E$ to its dual $E^{* }$.   If $A$ is continuous on finite-dimensional subspaces of $E$ then for every $f\in E^{*}$ there exists a unique solution to the problem
  $$Au=f.$$

Have a look at the textbook by Chipot or  the free monograph by Showalter where the approach is explained in detail.


text:
Q: Custom Field Filter by Role - Wordpress I've created a custom field and selected "Filter by role" to "Subscriber" and assigned the custom field to the post type. Now when I add a new post and assigned the subscriber (ie: created a Test Post and assigned the subscriber to "grade 1") after I click on the update again I changed the subscriber "grade 1" to "grade 2", after that when I viewed the page by login as grade 1 that particular post is viewed. This Happens only if I edit the post and change the subscriber again.
$args_events = array(
    'post_type' => 'parents_login',
    'post_status' => 'publish',
    'paged' => $page_num,
    'posts_per_page' => CUSTOM_ROWS_PER_PAGE,
    'cat' => get_cat_id( single_cat_title("",false) ),
    'meta_query' => array(
        'relation' => 'OR',
        array(
            'key' => 'select_grade',
            'value' => $current_user->ID,
            'compare' => 'LIKE',
        ),
    ),
);

A: $args_events = array(
        'post_type' => 'parents_login',
        'post_status' => 'publish',
        'posts_per_page' => CUSTOM_ROWS_PER_PAGE,
        'cat' => get_cat_id( single_cat_title("",false) ),
        'meta_query' => array(
           array(
               'key' => 'select_grade',
               'value' => serialize( strval( $current_user->ID ) ),
               'compare' => 'LIKE'
            ),
         ),
);

Using this I attained result. Thanks

A: Change OR to AND
Where is your $current_user; variable?
I see it in your code, but not the value that it has.
Please update code


text:
Q: Who put the seals on Lucifer's cage? I've just read the supernatural wiki on Lucifer's Cage, and it mentions both the cage and the seals are created by God.
That's all well and good but i see no reference to it in the show. I know it was god that cast him out of heaven but I have no reason to believe he caged him too.

A: It was referenced in the show on multiple occasions; as the wiki also points out:

This Cage was designed as a prison immediately after Lucifer's rebellion. After being banished from Heaven for defying God, Lucifer decided to anger God by twisting a Human soul into the first demon. After this, God sent Michael to imprison Lucifer.

(emphasis mine)

A: I am not sure but I would guess Death? Since they say Death is even more powerful the God.