text:
Q: Sequencing render in React Native I would like to create a simple quiz app.
When I run the following, line 77 in Quiz.tsx
<Text style={styles.text}>{question.question}</Text>

Below is showing the error :

TypeError: TypeError: undefined is not an object (evaluating
  'question.question')

probably because render() is done faster than nextQuestion() after the last question.
How can I solve this ?
Quiz.tsx
import React from "react";
import { View, StyleSheet, StatusBar, Text, SafeAreaView } from "react-native";
import { StackActions, NavigationScreenProp } from 'react-navigation';

const styles = StyleSheet.create({
// some styles
});

export interface Props {
  navigation: NavigationScreenProp<any, any>;
}

export interface State {
  correctCount: number;
  totalCount: number;
  activeQuestionIndex: number;
  answered: boolean;
  answerCorrect: boolean;
}

class Quiz extends React.Component<Props, State> {

  state:State = {
    correctCount: 0,
    totalCount: this.props.navigation.getParam("questions", []).length,
    activeQuestionIndex: 0,
    answered: false,
    answerCorrect: false,
  };

  answer = (correct) => {
    this.setState(
      (state) => {
        const nextState = {
          answered: true,
          answerCorrect: true
          };

        if (correct) {
          this.state.correctCount = state.correctCount + 1;
          nextState.answerCorrect = true;
        } else {
          nextState.answerCorrect = false;
        }
          return nextState;
        },
      () => {
        setTimeout(() => this.nextQuestion(), 1000);
      }
    );
  }

  nextQuestion = () => {
    this.setState(state => {
      const nextIndex = this.state.activeQuestionIndex + 1;

      if ( nextIndex >= this.state.totalCount) {
        this.props.navigation.dispatch(StackActions.popToTop());
      }

      return {
        activeQuestionIndex: nextIndex,
        answered: false
      };
    });
  };

  render() {
    const questions = this.props.navigation.getParam("questions", []);
    const question = questions[this.state.activeQuestionIndex];

    return (
      <View>
        <StatusBar barStyle="light-content" />
        <SafeAreaView>
          <View>
            <Text style={styles.text}>{question.question}</Text>
          </View>
        </SafeAreaView>
      </View>
    );
  }
};

export default Quiz ;

error message
TypeError: TypeError: undefined is not an object (evaluating 'question.question')
* App/screens/Quiz.tsx:101:48 in render
- node_modules/react-native/Libraries/Renderer/oss/ReactNativeRenderer-dev.js:11581:21 in finishClassComponent
- node_modules/react-native/Libraries/Renderer/oss/ReactNativeRenderer-dev.js:11509:4 in updateClassComponent
- node_modules/react-native/Libraries/Renderer/oss/ReactNativeRenderer-dev.js:17276:21 in performUnitOfWork
- node_modules/react-native/Libraries/Renderer/oss/ReactNativeRenderer-dev.js:17316:41 in workLoop
- node_modules/react-native/Libraries/Renderer/oss/ReactNativeRenderer-dev.js:17417:15 in renderRoot
- node_modules/react-native/Libraries/Renderer/oss/ReactNativeRenderer-dev.js:18423:17 in performWorkOnRoot
- node_modules/react-native/Libraries/Renderer/oss/ReactNativeRenderer-dev.js:18324:24 in performWork
- node_modules/react-native/Libraries/Renderer/oss/ReactNativeRenderer-dev.js:18285:14 in performSyncWork
- node_modules/react-native/Libraries/Renderer/oss/ReactNativeRenderer-dev.js:18169:19 in requestWork
- node_modules/react-native/Libraries/Renderer/oss/ReactNativeRenderer-dev.js:17969:16 in scheduleWork
- node_modules/react-native/Libraries/Renderer/oss/ReactNativeRenderer-dev.js:6934:17 in enqueueSetState
- node_modules/react/cjs/react.development.js:335:31 in setState
* App/screens/Quiz.tsx:73:18 in nextQuestion
* App/screens/Quiz.tsx:67:25 in <unknown>
- node_modules/react-native/Libraries/Core/Timers/JSTimers.js:152:14 in _callTimer
- node_modules/react-native/Libraries/Core/Timers/JSTimers.js:414:17 in callTimers
- ... 5 more stack frames from framework internals

A: Here instead of,
const questions = this.props.navigation.getParam("questions", []);

you can try,
const questions = this.props.navigation.state.params.questions;


text:
Q: Using a custom format to parse numeric strings I want to know how to take numbers that are 12 digits long 123456789012 and have them display as 123 456 789 012. I apologize If that is explained in the Microsoft custom formats article but I couldn't make sense of it and would really appreciate it if someone could explain to me how to do it. Thank you.

A: The format string is ### ### ### ### ###

redpajama_set_name: RedPajamaStackExchange


text:
Q: Get rows whose value isn't found on another sheet I'm trying to do the following.
I have Sheet 1 and Sheet 2.
On a third sheet I need to get the rows in sheet 1 where the INSTRUMENT of sheet 1 aren't found in the FIM of sheet 2  (e.g. since none of the INSTRUMENTS of sheet 1 are in the FIM of sheet 2, sheet 3 would contain the rows of sheet 1).
How can I do this?
Thanks

A: Lookup functions like VLOOKUP() can be used to either find the lookup value and therefore return some result, or not find it and therefore return an #ERROR!. Obviously, this is usually used in a "positive" sense, looking FOR some result, but one can also use it in a "negative" sense, looking NOT for some result, but rather for the #ERROR!.
One can also then test for the existence of an #ERROR! with the ISERROR() function. Sometimes IFERROR() can be used, but many situations do not lend themselves to IFERROR()'s mechanism and this is one of them. ISERROR() will be used here as a more sophisticated NOT(). Then, if the INSTRUMENT is not found, the IF() test will succeed since it is looking for such a failure. The TRUE result in that case is the value of the lookup cell. If the test fails (INSTRUMENT exists there), "" is returned.
The following formula does this:
=IF(ISERROR(VLOOKUP(A2:A9,$F$2:$F$5,1,FALSE)),A2:A9,"")

If you have SPILL functionality, just the first cell needs the formula. If not, paste it in the first cell and use {CSE} to do the older method for making an array.
Notice that the formula will have results spotted throughout the output range. To group them, you need to sort them with the empty ones ending up at the bottom of the list so they don't interfere with either the easy use of the list, or simply its appearance, whichever might matter more to you.
However, pretty much anything you use for those that exist, like the "" in the formula above, of even a much higher character, like UNICODE(160) which owuld be a blank space, will still sort to the start of the list. You could approach that many ways, including copying, then pasting as values, then sorting, but to do it with a formula so you don't need to interact, you can try something like the following:
=SUBSTITUTE(SORT(IF(ISERROR(VLOOKUP(A2:A9,$F$2:$F$5,1,FALSE)),A2:A9,"ZZZZZZZZZZ")),"ZZZZZZZZZZ","")

You use a character string that should always sort to the end of your list. "ZZZZZZZZZZ" is used in this formula. Then you SORT() to force all those to the end and the ones you want to see first at the top. Then you SUBSTITUTE() for that string with a blank, like "", and all those "go away"... Not really of course, but in appearance.
(Obviously, you need to use real references in the formula you choose or adapt.)


text:
Q: How to install Nvidia drivers version 440 on Ubuntu 20.04? I'd like to ask how to install nvidia-driver-440 properly on Ubuntu 20.04. I have an old GTX 760 graphics card, and I want to use CUDA 10.2 which is not possible with the default nvidia-driver-450.
But when I try to downgrade the driver with first removing the old one and then $ sudo apt-get install nvidia-driver-440, it doesn't work so well. After rebooting, my screen is weirdly distorted and on a much lower resolution. nvidia-smi fails with:
Error: failed to initialize. NVML driver/library version mismatch.

When I go back to 450, everything is normal again. I repeated this a few times and when looking closer at the command outputs during installation, I noticed it said that some modules failed to initialize because their version is not bigger as the ones in the kernel (which is 450). They suggest to override this with --force, which I tried ($ sudo apt-get --force install nvidia-driver-440) but it also fails.
My question is: What can I do now? Do I really have to downgrade to Ubuntu 18 or is there a way to get version 440 working on Ubuntu 20?


text:
Q: UIPageControl outer dots do not respond when selected (inner dots do) For my iPad App, I have a main ViewController which contains two UIScrollviews and a UIPageControl. This works well except when I have more than the default three pages in the UIPageControl, in which case I set the number of pages manually in my VC using the call:
[self.pageControl setNumberOfPages:totalPages];

In such a case where the pageControl is set to say 10 pages (i.e. more than the default 3 pages) the dots outside of the 3 middle dots do not respond (i.e. the target action changePage function is not called when a user manually selects any of the dots outside the middle three)
see the picture shown:
Any help on how to resolve this would be most appreciated. Should I try addTarget to the 'changePage' function in code? (currently the target action is set in IB)
Thanks!

A: I resolved this. The trick was to resize the UIPageControl in IB to the expected width (I did this in IB Size Inspector). I now see the changePage function getting called when I pick even the extreme end dots.


text:
Q: Android SMS App Opens Within My App In my Android app I need to write a function that will open up the Device's SMS app if it exists.  I have the code below.
String smsText = "Some text for the sms";
Intent sendIntent = new Intent(Intent.ACTION_VIEW);
sendIntent.setData(Uri.parse("sms:"));
sendIntent.putExtra("sms_body", smsText);
this.startActivity(sendIntent);

This code will open up the SMS app however it opens the Compose UI within my app. This means that the user will have to back out of the SMS UI in order to continue using my app. If the user goes to the App Launcher from the Home screen or the App list, it also opens in the same state as it is simply resuming where the app left off.
This was tested on a Samsung Galaxy S4 running Android 4.3
Is there any way to either Completely change contexts and open the SMS app, leaving my app? Or is there a way to close the SMS app after the SMS has been sent?
Any help would be appreciated. This behavior is not what I expected but maybe that is how Android works.
** EDIT **
"It opens the Compose UI within my app" - What I mean by this is that The SMS app's Compose screen is opened. But from any other context it looks like it's my app. So if I hit the home button and go back to the device home screen, then click the app icon, it does not go back to the last place my app was in, but rather it goes to the the SMS Screen again. If I view all open applications, the image of the SMS screen is under my apps name, rather then the SMS app's name.  So from every available resource, it looks as if the SMS app is opening under the name of my app.

A: If you don't want the Compose Message UI to be opened as part of your application's task, just start it in a new task, like this:
String smsText = "Some text for the sms";
Intent sendIntent = new Intent(Intent.ACTION_VIEW);
sendIntent.setData(Uri.parse("sms:"));
sendIntent.putExtra("sms_body", smsText);
sendIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
this.startActivity(sendIntent);


text:
Q: access to xml of fragments in Tablayout I created an app on AS and I use Tab Layout with View Pager, Fragment in it from  this site!
and I want to access each fragment layout (I have 3 fragment) to apply some changes on them. I searched about it in the Internet but I could not find anything about it.

A: Without seeing any code or errors.. I'll try to give the best answer I can.. In the class you set up the tab layout you can create the page fragments like so:
public class TabLayoutActivity extends MainActivity{

@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.tab_layout);

    ViewPager vp = (ViewPager) findViewById(R.id.view_pager);
    this.addPages(vp);

    TabLayout tabLayout = (TabLayout) findViewById(R.id.tab_layout);
    tabLayout.setupWithViewPager(vp);
    tabLayout.setOnTabSelectedListener(listener(vp));
}

//ADD ALL PAGES
private void addPages(ViewPager pager) {
    MyFragPagerAdapter adapter = new MyFragPagerAdapter(getSupportFragmentManager());

    Tab1Fragment tab1Fragment = new Tab1Fragment();
    adapter.addPage(mondayFragment);
    Tab2Fragment tab2Fragment = new Tab2Fragment();
    adapter.addPage(tab2Fragment);
    Tab3Fragment tab3Fragment = new Tab3Fragment();
    adapter.addPage(tab3Fragment);
    pager.setAdapter(adapter);
}

private TabLayout.OnTabSelectedListener listener(final ViewPager pager) {
    return new TabLayout.OnTabSelectedListener() {
        @Override
        public void onTabSelected(TabLayout.Tab tab) {
            pager.setCurrentItem(tab.getPosition());
        }

        @Override
        public void onTabUnselected(TabLayout.Tab tab) {

        }

        @Override
        public void onTabReselected(TabLayout.Tab tab) {

        }
    };
}
}

You then create 3 classes, Tab1Fragment, Tab2Fragment, and Tab3Fragment, aswell as the xml layouts for each. Here is an example of one of the tab fragment classes:
public class Tab1Fragment extends Fragment{
    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {

          View view = inflater.inflate(R.layout.tab1_fragment, null);

          }
@Override
public String toString() {
    return "Tab 1";
}
}

This is a very simple example to give you an idea. You can then change the xml layout in the corresponding fragment class. Let me know if you have any questions


text:
Q: Passing parameter to Java Method then using that parameter in SQL Query Statement So the idea is that i can send an amount of bedrooms(int) as a parameter to a Java method which will use that int parameter in an SQL statement that returns all houses in the database with X amount of bedrooms.
public void displayProperty(int bedrooms) throws SQLException{

ResultSet rs = Stmt.executeQuery("select * from PropertySale where bedroomsAmount = 'bedrooms' ;");

How exactly do i pass that parameter straight through to the statement?

A: ResultSet rs = Stmt.executeQuery("select * from PropertySale where bedroomsAmount =" + bedrooms + ";");


text:
Q: Why some? returns true when it takes false as a parameter in Clojure? I couldn't understand the intent of some? function in Clojure.
I need some function(built-in) that returns false when it takes (nil or false).
Here is the example:
(some? "1")
=> true

(some? nil)
=> false

(some? false) ;;Which is odd!!
=> true

A: Check the documentation of some?:

(some? x)

Returns true if x is not nil, false otherwise.

false is definitely not nil thus (some? false) returns true.
It is a complement of nil?
(= (some? x) (not (nil? x))

As @delta suggested, you can use boolean to check if something is not nil or false.

A: Don't know why some? is like that. But what you are looking for is boolean.

*

*https://clojuredocs.org/clojure.core/boolean

A: Even simpler, use IF:
user=> (if "1" true false)
true
user=> (if nil true false)
false
user=> (if false true false)
false

A: While there is more than one way to do what you are asking, I think the easiest is to use the truthy? & falsey? functions from the Tupelo library:

The Truth Is Not Ambiguous
Clojure marries the worlds of Java and Lisp. Unfortunately, these two
  worlds have different ideas of truth, so Clojure accepts both false
  and nil as false. Sometimes, however, you want to coerce logical
  values into literal true or false values, so we provide a simple way
  to do that:

(truthy? arg)
  Returns true if arg is logical true (neither nil nor false);
  otherwise returns false.

(falsey? arg)
  Returns true if arg is logical false (either nil or false);
  otherwise returns false. Equivalent to (not (truthy? arg)).

Since truthy? and falsey? are functions (instead of special forms or macros), we can use them as an argument to filter or any other place that a higher-order-function is required:
(def data [true :a 'my-symbol 1 "hello" \x false nil] )

(filter truthy? data)
;=> [true :a my-symbol 1 "hello" \x]
(filter falsey? data)
;=> [false nil]

(is (every? truthy? [true :a 'my-symbol 1 "hello" \x] ))
(is (every? falsey? [false nil] ))

(let [count-if (comp count keep-if) ]
  (let [num-true    (count-if truthy? data)   ; <= better than (count-if boolean data)
        num-false   (count-if falsey? data) ] ; <= better than (count-if not     data)
    (is (and  (= 6 num-true)
              (= 2 num-false) )))))

A: The effective source for some? is
(defn some? [x] (not (nil? x)))

It would be better called not-nil?, which Tupelo offers as an alias.
As others have said, the function you are looking for is boolean.


text:
Q: Derivation of the electric field induced in a solenoid with time-varying current Consider an ideal solenoid that is infinitely long.  As the current flowing through the solenoid varies over time, I am taught that an electric field will be induced and the field lines will be circles that are concentric with the axis of the solenoid.
Why does this have to be the case?  Why can't there be a component of the electric field that is parallel to the solenoid?
It would be helpful for somebody to explain this directly from Maxwell's equations.
My own guess (if you know the answer please tell me if I am right or wrong):
Focusing on Maxwell's equations in vacuum.  The rate of change of B-field is equal to the negative of the curl of E-field.  This implies that, when the B-field's strength is changed with it's direction being kept constant (which is the case here), the E-field created must be normal to the B-field's direction.  We also know that, in vacuum, the divergence of the E-field is 0.  The only possibility is for the E-field to be circles that are concentric with the axis of the solenoid.

A: Inside the solenoid the magnetic field is uniform and parallel to the axis, so we may write$$\vec{B}=B\ \vec{\hat{z}}.$$
So, using the Faraday-Maxwell equation anywhere in the solenoid,$$\text{curl}| \vec{E}=-\frac{\partial{\vec{B}}}{dt}$$We now use the curl in cylindrical polars, to suit the symmetry of the set-up. Since $\vec{B}$ has no components in the $\vec {\hat{r}}$ or $\vec {\hat{\theta}}$ directions, we need only equate $-\frac{\partial{{B}}}{dt}$ to the $\vec {\hat{z}}$ component of curl in cylindrical polars, so
$$-\frac{\partial{{B}}}{dt}=\frac{1}{r} \left(\frac{\partial (r E_{\theta})}{\partial r}\ -\frac{\partial E_{r}}{\partial \theta}\right).$$ Because the magnetic field is uniform, symmetry shows us that the second term in the bracket disappears. We can now integrate up wrt r, remembering that $-\frac{\partial{{B}}}{dt}$ is a constant from the point of view of this integration. So $$\int_{0}^{R}-\frac{\partial{B}}{dt} r\ dr =\int_{r=0}^R d(rE_\theta).$$ Thus $$R E_{\theta}=-\frac{R^2}{2} \frac{\partial{B}}{dt}.$$ Strictly we should add arbitrary functions of $\theta$ and $z$, since these would disappear in a partial differentiation wrt $r$, but symmetry considerations make it unnecessary to do so. Finally we note that the emf in a loop of radius $R$ is simply $E_{\theta}$ times the loop circumference, so,$$\mathscr{E}=(-)2\pi R \times \frac{R}{2} \frac{\partial{B}}{dt}=(-)\pi R^2 \frac{\partial{B}}{dt}.$$This result should be familiar!


text:
Q: .NET Core service stalling under load due to HttpWebRequest I had a ASP.NET (.NET Framework 4.8) web service running on a Windows Server, that made lots of outgoing HTTP requests using HttpWebRequest (synchronous). It was handling thousands of concurrent requests without any trouble.
Recently, I migrated the service/middleware to ASP.NET Core (runtime 3.1) running on Ubuntu Server, using the updated HttpWebRequest (synchronous).
Now this service is stalling under a load test with just a few hundred concurrent requests. System journal/logs indicate that health check (heartbeat) cannot reach the service after a few minutes. It starts out fine, but after a few minutes it slows down and eventually halts (no response but it doesn't crash dotnet though), and then starts working again after 5-10 minutes without any intervention, and repeats this same behavior every few minutes.
I'm not sure if this is due to port exhaustion or a deadlock. If I load test the service by skipping all HttpWebRequest calls, then it works fine, so I'm suspecting it has to do something with HttpWebRequest causing an issue under stress of traffic.
Looking at the .NET Core codebase, it seems like HttpWebRequest (synchronous) creates a new HttpClient for each request (client is not cached due to parameters in my case), and executes HttpClient synchronously like:
public override WebResponse GetResponse()
{
    :
    :
    return SendRequest(async: false).GetAwaiter().GetResult();
    :
    :
}

private async Task<WebResponse> SendRequest(bool async)
{
    :
    :
    _sendRequestTask = async ?
        client.SendAsync(...) :
        Task.FromResult(client.Send(...));

    HttpResponseMessage responseMessage = await _sendRequestTask.ConfigureAwait(false);
    :
    :
}

Official suggestion from Microsoft is to use IHttpClientFactory or SocketsHttpHandler for better performance. I can make our service use a singleton SocketsHttpHandler and new HttpClient's per outgoing request (with the shared handler) to reuse & close sockets better, but my main concern is (below):
The service is based on synchronous code, so I'll have to use asynchronous HttpClient synchronously, probably using the same method.GetAwaiter().GetResult() technique as official .NET Core code above. While a singleton SocketsHttpHandler may help avoid port exhaustion, could concurrent synchronous execution still result in the stalling problem due to deadlocks like the native HttpWebRequest?
Also, is there an approach (another synchronous HTTP client for .NET Core, setting 'Connection: close' header etc.) to smoothly making lots of concurrent HTTP requests synchronously without port exhaustion or deadlocks, just like it worked smoothly earlier with HttpWebRequest in .NET Framework 4.8?
Just to clarify, all WebRequest related objects are closed/disposed properly in the code, ServicePointManager.DefaultConnectionLimit is set to int.MaxValue, nginx (proxy to dotnet) has been tuned, sysctl has been tuned as well.

A:
I'm not sure if this is due to port exhaustion or a deadlock.

Sounds more like thread pool exhaustion to me.

The service is based on synchronous code, so I'll have to use asynchronous HttpClient synchronously

Why?
The best solution to thread pool exhaustion is to rewrite blocking code to be asynchronous. There were places in ASP.NET pre-Core that required synchronous code (e.g., MVC action filters and child actions), but ASP.NET Core is fully asynchronous, including the middleware pipeline.
If you absolutely cannot make the code properly asynchronous for some reason, the only other workaround is to increase the minimum number of threads in the thread pool on startup.


text:
Q: Как у jquery узнать какой код повесили на событие, при инспекции элемента На странице есть модальное окно, нажимаю на "крестик", окно закрывается. Мне нужно узнать где тот самый код который исполняется после нажатия на "крестик".
Как я делаю:

*

*Открываю Developer Tools.

*Во вкладке "элементы" выделяю нужный "крестик".

*В Event Listeners фильтрую по выбранному элементу, и вижу событие click.

Это событие ссылается на jQuery.event.add.
И все бы хорошо, но на этом я не знаю что дальше делать, в объекте jQuery не нахожу где же тот калбэк который повесили на это событие с помощью jQuery.
P. S. Грепать я могу и, наверное, пока получу тут ответ, я уже найду нужный мне калбэк, но в целях образования хочу узнать.
P. P. S. Увидел что такой вопрос уже задавали и ответа не дали, только попросили поставить брейкпоинт в никуда :)

A: Есть плагин для Chrome называется jQuery Audit.
Думаю, что должен помочь.


text:
Q: How to beautify binary dict files? I've opened /System/Library/Frameworks/AppKit.framework/Resources/StandardKeyBinding.dict in vim, and it looks like jibberish. Is there a way to convert it to human readable just to see what it contains?

A: If you have plutil installed
You can run this Applescript which will create a text version of the dictionary for you to read.
   property copyScriptPath : "~/Documents/" (* path dir for text version*)

tell application "Finder"
    set selectFiles to (get selection) (* get the finder selection*)
end tell
repeat with i from 1 to number of items in selectFiles
    (* convert to POSIX path*)
    set this_item to quoted form of POSIX path of (item i of selectFiles as alias)

    (* get the file name , add it to an alias, then use plutil to read and write atext version out using the original name*)
    do shell script "name=`basename " & this_item & "`;/usr/bin/plutil -convert xml1  " & this_item & " -o  " & copyScriptPath & "\"$name\".txt"
end repeat

OR
There is an old hint on macosxhints - 10.4: Edit binary (and normal) plist files with vim
The post also has the link to the vim script that does all this.
Which may do what you want. ( don't use vim myself )
Quote from the post ( But please go and read it as there are comments and notes that you will need:

What does it do? It reads a plist file, checks and memorizes if it is
  binary, converts it to plain text if necessary and turns on syntax
  highlinghting for XML. When you save the file again, it is converted
  to binary again for writing if it was binary in the beginning. If the
  file was not binary or if the conversion to binary fails (which can
  happen if you have syntax errors in your file), the file is stored in
  text format. If an originally-binary plist is saved as plain text due
  to syntax errors and you fix the errors and save the file again, it is
  written in binary format. If you open a binary file and just view it
  without making any changes, you can still exit from vim using the
  normal :q (no need for :q!) and the file is left untouched (still in
  binary format). All this should work even when working with several
  buffers (files), when reading a file into an existing buffer, or when
  only writing parts of a buffer to file

A: Copy the file to some other directory. Move to that directory and run
plutil -convert xml1 StandardKeyBinding.dict

in terminal. (You may convert it to json format by replacing xml1 with json.)
Then run
cat -v StandardKeyBinding.dict

and you can see the file in a readable manner now, like below.
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
    <key>^C</key>
    <string>insertNewline:</string>
    <key>^H</key>
    <string>deleteBackward:</string>
    <key>  </kev>
    <string>insertTab:</string>
    <key>
</key>
    <string>insertNewline:</string>
    <key>^M</key>
    <string>insertNewline:</string>
    <key>^Y</key>
    <string>insertBacktab:</string>
    <key>^[</key>
    <string>cancelOperation:</string>
    <key>$?M-^\M-^@</key>
    <string>moveUpAndModifySelection:</string>
    <key>$?M-^\M-^A</key>
    <string>moveDownAndModifySelection:</string>
    <key>$?M-^\M-^B</keV>
    <string>moveLeftAndModifySelection:</string>

Tips: Run man cat to see what cat -v does.

A: Here is the method to make StandardKeyBinding.dict file correctly readable:
plutil -convert xml1 StandardKeyBinding.dict

No use to convert it back.

A: Try also
/usr/libexec/PlistBuddy -c print /System/Library/Frameworks/AppKit.framework/Resources/StandardKeyBinding.dict


text:
Q: how to make scrolling scroll 100% of ViewHight each the user scroll I have a wordpress website.
i like to make that site kind of similar to Reels / Tiktok.
when we scroll, instead of scroll step be slowly, each time the user interact with scrolling
it will scroll a whole Section or 100% of the view Hight. both ways will work fine.
what ever method works for me :)
edit: an idea i had, make the smoothweel scroll steps for anchors. then set anchors through the page. each scroll will scroll to the next anchor.

A: I wouldn't waste much time with this. Make sure your other elements are as intended and just use something like this:
https://webdevtrick.com/demos/full-page-scrolling/


text:
Q: Incorrect parameter type for function 'not()' in VF email template I'm trying to get information to conditionally render based on if the field is populated or not. All my fields except for Media_Kit_Comment__c are boolean. Media_Kit_Comment__c is a string and I'm having a hard time getting it to work.
When I try to save the email template I get the error:
Error: Incorrect parameter type for function 'not()'. Expected Boolean, received Text
<messaging:emailTemplate subject="You have a new lead: {!relatedto.FirstName} {!relatedto.LastName}, {!relatedto.Company}" recipientType="User" relatedToType="Lead">
<messaging:htmlEmailBody >

            Hey {!$User.FirstName},

            You've been assigned a new lead from {!relatedto.Site__c}. Here are the details:

           Name: {!relatedto.FirstName} {!relatedto.LastName}

           Company: {!relatedto.Company}

           Title: {!relatedto.Title}

           Email: {!relatedto.Email}

           <apex:outputText value="{!IF(NOT(!relatedto.Agency__c),"Agency:",NULL)}" /> <apex:outputText value="{!IF(NOT(!relatedto.Agency__c),"Yes",NULL)}"/>

           <apex:outputText value="{!IF(NOT(!relatedto.Food_bev_manufacturers__c),"Food & bev manufacturers:",NULL)}" /> <apex:outputText value="{!IF(NOT(!relatedto.Food_bev_manufacturers__c),"Yes",NULL)}"/>

           <apex:outputText value="{!IF(NOT(!relatedto.Grocery_retailers__c),"Grocery retailers:",NULL)}" /> <apex:outputText value="{!IF(NOT(!relatedto.Grocery_retailers__c),"Yes",NULL)}"/>

           <apex:outputText value="{!IF(NOT(!relatedto.Restaurants__c),"Restaurant:",NULL)}" /> <apex:outputText value="{!IF(NOT(!relatedto.Restaurants__c),"Yes",NULL)}"/>

           <apex:outputText value="{!IF(NOT(!relatedto.Higher_ed_admins__c),"Higher Ed Admins:",NULL)}" /> <apex:outputText value="{!IF(NOT(!relatedto.Higher_ed_admins__c),"Yes",NULL)}"/>

           <apex:outputText value="{!IF(NOT(!relatedto.K12_admins__c),"K-12 Admins:",NULL)}" /> <apex:outputText value="{!IF(NOT(!relatedto.K12_admins__c),"Yes",NULL)}"/>

          <apex:outputText value="{!relatedto.Media_Kit_Comment__c}" rendered="{!ISBLANK(!relatedto.Media_Kit_Comment__c)}"/>

           Click link to go to the record in Salesforce:  <apex:outputlink value="{!LEFT($Api.Partner_Server_URL_140,FIND('.com',$Api.Partner_Server_URL_140)+4)+relatedTo.Id}">https://na39.salesforce.com/{!relatedto.Id}</apex:outputlink>

           P.S. If this lead was assigned to you by mistake, please let your Sales Ops team know!

</messaging:htmlEmailBody>

Below is an example of how the email works. See how Agency is visible because the Agency checkbox was checked on the record. I'd like the Media Kit Comment to render conditionally as well, but the fact that it is a string is throwing me.

The specific line that is giving me grief is:
  <apex:outputText value="{!relatedto.Media_Kit_Comment__c}" rendered="{!ISBLANK(!relatedto.Media_Kit_Comment__c)}"/>

Thanks!

A: You are using bind expression(!) again and again. Bind expression should be used only once. Using it again makes it a NOT(!)
Thus this
<apex:outputText value="{!relatedto.Media_Kit_Comment__c}" rendered="{!ISBLANK(!relatedto.Media_Kit_Comment__c)}"/>

is trying to use NOT(!) operator on text field Media_Kit_Comment__c which not possible.
Solution: Use Bind expression only once.
<apex:outputText value="{!relatedto.Media_Kit_Comment__c}"
rendered="{!!ISBLANK(relatedto.Media_Kit_Comment__c)}"/>

Also I would like to add, You have done same for other fields as well, which would provide you wrong results.


text:
Q: Get the images dimension from html I have two images in two different section and div.I want to get the original  dimension at same time and send to my java script file to do some calculation. How do I get the images dimension at the same time.
html file

js
function OnImageLoad(evt) {

    var img = evt.currentTarget;

    // what's the size of this image
    var w = $(img).width();
    var h = $(img).height();

In this code I am able to get the images dimension of images,But they return dimension of only one images.I want to get the dimension of both images at same time.
Something like this:
 function OnImageLoad(evt) {

        var img1 = evt.currentTarget;
        var img2 = evt.currentTarget;

        // what's the size of this image
        var w1 = $(img1).width();
        var h1 = $(img1).height();

        var w2 = $(img2).width();
        var h2 = $(img2).height();

A: function OnImageLoad() {

        var img1 = document.getElementById("Image1");
        var img2 = document.getElementById("Image2");

        // what's the size of this image
        var w1 = img1.width;
        var h1 = img1.height;

        var w2 = img2.width;
        var h2 = img2.height;
}

Html:

Call this function on window.onload=OnImageLoad();

A: You can not do that, they are async tasks. You can only calculate the size of the image only when they are completely loaded, so If first image is of higher size then the second image, it will take more time to calculate the first image size then the second.
What you can do is, fetch both the image sizes aynchronously, and when both of them are done you can do the calculations.
var sizes = [];
var counter = 0;

function OnImageLoad(evt) {

    var img = evt.currentTarget;
    // what's the size of this image
    var w = $(img).width();
    var h = $(img).height();
    counter++;
    sizes.push({
        height: h,
        width: w
    });

    if (counter == 2) {
        callAnotherFunction(sizes)
    }
}

A: prepending the variables with a custom value should make it possible.
HTML

JS
function OnImageLoad(evt, pre) {

var img = evt.currentTarget;

// what's the size of this image
eval("var w" + pre + " = $(img).width()");
eval("var h" + pre + " = $(img).height()");

Ive not tested this though.

A:

function OnImageLoad(evt) {
  //This function will be called on each image load and will iterate all the image inside this dom
  var images = $('img');
  for(var i =0 ;i<images.length; i++) {
        // what's the size of this image
        var w = $(images[i]).width();
        var h = $(images[i]).height();
    //For each file you will have width and height of the image
    console.log('width of image-'+i+': ',w);
    console.log('height of image-'+i+': ',h);
  }
}
<!DOCTYPE html>

  <meta charset="utf-8">
  <title>JS Bin</title>

enter link description here


text:
Q: Windows allow user to run commands On windows xp I can run many commands form PHP with shell_exec() function.
I need to use OfficeToPDF on windows 10 with PHP.
My php script is:
<?php
$command = 'OfficeToPDF input.docx output.pdf';
$exec = shell_exec($command);
echo $exec;
?>

This script works on windows XP Professional, but not on windows 7, 8, 10.
OfficeToPdf simply opens Microsoft Word and saves file as PDF.
What changed on win7, win8, win10? Why I couldn't execute this command from PHP on new OS's?
I have apache service automaticly starts from SYSTEM user.
UPDATE: But I can run OfficeToPDF input.docx output.pdf command when I open cmd window manually.

A: I suspect that some environment variables are missing that are required. You should try running from within a command window instance, that will setup the default env vars:

    $command = 'cmd /c OfficeToPDF input.docx output.pdf';
    $exec = shell_exec($command);
    echo $exec;

You might want to use the full path to OfficeToPDF, input.docx and output.pdf in case your default directory is incorrect, or call chdir() first.
The meaning of /C is:
/C      Carries out the command specified by string and then terminates


text:
Q: Java Actionlistener on Button import java.awt.*;

public class TestButton {
  private Frame f;
  protected Button b;

  public TestButton() {
    f = new Frame("Test");
    b = new Button("Press Me!");
    b.setActionCommand("ButtonPressed");
  }

  public void launchFrame() {
    b.addActionListener(new ButtonHandler());
    f.add(b, BorderLayout.CENTER);
    f.pack();
    f.setVisible(true);
  }

  public static void main(String args[]) {
    TestButton guiApp = new TestButton();
    guiApp.launchFrame();
  }
}

import java.awt.*;
import java.awt.event.*;

public class ButtonHandler extends TestButton implements ActionListener {
  public void actionPerformed(ActionEvent e) {
      Object source = e.getSource();
      if(source==b)
      {
            System.out.println("Action occurred");
            System.out.println("Button's command is: "
                               + e.getActionCommand());
      }
  }
}

I'm trying to invoke a ActionEvent when the button b is pressed but not working with getSource.

A: You're misusing inheritance. The ButtonHandler class should not extend the TestButton class, since the b variable in the handler class refers to a completely different Button object from the one displayed. I suggest:

*

*Use the Swing library, not the AWT library

*You can get the JButton pressed from the ActionEvent's getSource() method and use it directly.

*If you need a reference to the GUI in the handler, pass in a reference in the handler's constructor.

*Don't misuse inheritance to solve problems that don't involve inheritance issues.

For example:
import java.awt.event.ActionEvent;

import javax.swing.*;

@SuppressWarnings("serial")
public class TestButton extends JPanel {
   private JButton btn = new JButton(new ButtonAction("Press Me!", "ButtonPressed"));

   public TestButton() {
      add(btn);
   }

   private static void createAndShowGUI() {
      TestButton testButton = new TestButton();

      JFrame frame = new JFrame("TestButton");
      frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      frame.getContentPane().add(testButton  );
      frame.pack();
      frame.setLocationRelativeTo(null);
      frame.setVisible(true);
   }

   public static void main(String[] args) {
      SwingUtilities.invokeLater(new Runnable() {
         public void run() {
            createAndShowGUI();
         }
      });
   }
}

@SuppressWarnings("serial")
class ButtonAction extends AbstractAction {
   public ButtonAction(String name, String actionCommand) {
      super(name);
      putValue(ACTION_COMMAND_KEY, actionCommand);
   }

   @Override
   public void actionPerformed(ActionEvent evt) {
      System.out.println("Button's actionCommand is: " + evt.getActionCommand());
   }
}

A: That happens because you extends TestButton in your ButtonHandler, because of you have 2 different instances of your Button and thea are not equals.
To fix that you can remove extends TestButton and make ButtonHandler as inner class of TestButton
or you can compare action commands instead of Button's like next:
  if(((Button)source).getActionCommand().equals("ButtonPressed"))

A: I think you need to remove extends TestButton as the 2 different instances of the buttons are not equal. You should go for a ButtonHandler as inner class or anonymous class to implement this.
Check this question:
Java Button Handler


text:
Q: RxJava-> Making API request based on a Condition My requirement is like this.

*

*Hit the First API get the response. In the response, I have a field defining the status, if that flag is set, make another API call and merge with the first result.

*If the flag is not set, return the actual response(First Response).

If I use the filter, it will ignore the false items, if the flag is not set, I don't want to ignore the current response.
How can we achieve this using RxJava, FlatMap and Filter ?

A: You don't need filter. Just check the status in flatMap. If it's set, fire the request and call startWith to concat it with the original one (You can replace startWith with any codes to combine the results as you want); if not, use just to wrap the response. Here is an example:
class MyResponse {

    boolean status;

    public MyResponse(boolean status) {
        this.status = status;
    }

    public static Observable<MyResponse> request() {
        return Observable.just(new MyResponse(false));
    }
}

Observable<MyResponse> response = Observable.just(new MyResponse(false));

response.first().flatMap(r -> {
        if (r.status) {
            return MyResponse.request().startWith(r);
        } else {
            return Observable.just(r);
        }
});

A: Just use filter
  RxHelper.toObservable(request1)
         .filter(response1 -> response1.status == "200")
         .flatMap(response1-> RxHelper.toObservable(request2))
         .map(response2 -> //Bla)
  });


text:
Q: How to auto-center jQuery UI dialog when resizing browser? When you use jquery UI dialog, all works well, except for one thing.
When the browser is resized, the dialog just stays in it's initial position which can be really annoying.
You can test it out on:
http://jqueryui.com/demos/dialog/
Click on the "modal dialog" example and resize your browser.
I'd love to be able to let dialogs auto-center when the browser resizes.
Can this be done in an efficient way for all my dialogs in my app?

A: Alternatively jQuery ui position can be used,
$(window).resize(function ()
{
    $(".ui-dialog").position({
        my: "center", at: "center", of: window
    });
});

A: Alternatively to Ellesedil's answer,
That solution did not work for me straight away, So I did the following which is also dynamical  but shortened version:
$( window ).resize(function() {
    $(".ui-dialog-content:visible").each(function () {
        $( this ).dialog("option","position",$(this).dialog("option","position"));
    });
});

+1 for Ellesedil though
EDIT:
Much shorter version which works great for single dialogs:
$(window).resize(function(){
    $(".ui-dialog-content").dialog("option","position","center");
});

It is not necessary for .each() to be used perhaps if you have some unique dialogs which you dont want to touch.

A: Another CSS-only option which works is this. The negative margins should equal half your height and half your width. So in this case, my dialog is 720px wide by 400px tall. This centers it vertically and horizontally.
.ui-dialog {
  top:50% !important;
  margin-top:-200px !important;
  left:50% !important;
  margin-left:-360px !important
}

A: Setting the position option will force this, so just use the same selector covering all your dialogs where I use #dialog here (if it doesn't find them no action is taken, like all jQuery):
jQuery UI before 1.10
$(window).resize(function() {
    $("#dialog").dialog("option", "position", "center");
});

jQuery UI 1.10 or higher
$(window).resize(function() {
    $("#dialog").dialog("option", "position", {my: "center", at: "center", of: window});
});

Here's that same jQuery UI demo page adding only the code above, we're just adding a handler to the window's resize event with .resize(), so it triggers the re-center at the appropriate time.

A: A more comprehensive answer, which uses Nick's answer in a more flexible way can be found here.
An adaption of the code of relevance from that thread is below. This extension essentially creates a new dialog setting called autoReposition which accepts a true or false. The code as written defaults the option to true. Put this into a .js file in your project so that your pages can leverage it.
    $.ui.dialog.prototype.options.autoReposition = true;
    $(window).resize(function () {
        $(".ui-dialog-content:visible").each(function () {
            if ($(this).dialog('option', 'autoReposition')) {
                $(this).dialog('option', 'position', $(this).dialog('option', 'position'));
            }
        });
    });

This allows you to supply a "true" or "false" for this new setting when you create your dialog on your page.
$(function() {
    $('#divModalDialog').dialog({
        autoOpen: false,
        modal: true,
        draggable: false,
        resizable: false,
        width: 435,
        height: 200,
        dialogClass: "loadingDialog",
        autoReposition: true,    //This is the new autoReposition setting
        buttons: {
            "Ok": function() {
                $(this).dialog("close");
            }
        }
    });
});

Now this dialog will always reposition itself. AutoReposition (or whatever you call the setting) can handle any dialogs that do not have a default position and automatically reposition them when the window resizes. Since you're setting this when you create the dialog, you don't need to identify a dialog somehow because the repositioning functionality becomes built into the dialog itself. And the best part is that since this is set per dialog, you can have some dialogs reposition themselves and others remain where they are.
Credit to user scott.gonzalez on the jQuery forums for the complete solution.

A: Hello everyone!
Vanilla JS solution:
(function() {
  window.addEventListener("resize", resizeThrottler, false);

  var resizeTimeout;

  function resizeThrottler() {
    if (!resizeTimeout) {
      resizeTimeout = setTimeout(function() {
        resizeTimeout = null;
        actualResizeHandler();
      }, 66);
    }
  }

  function actualResizeHandler() {
    $(".ui-dialog-content").dialog("option", "position", { my: "center", at: "center", of: window });
  }
}());


text:
Q: Kendo Angular 2 Grid Filter not available I am using the Kendo Grid with Angular 2 using this http://www.telerik.com/kendo-angular-ui/components/grid/data-binding/ tutorial but I didn't find filtering in the grid. How can I filter my Kendo Grid with Angular 2?

A: Filters are not available in current Beta.0 version of kendo-angular2-grid.
At present, you can use limited API which are listed here
Issue is already reported on telerik's kendo-angular2. Refer this
Comment from Telerik member on this filter issue-

We don't have a concrete timeline for the grid filtering feature.
  There are a number of prerequisites of this feature, the most
  significant one being the date pickers. You can review our roadmap for
  further details - http://www.telerik.com/kendo-angular-ui/roadmap/

This idea is already posted on newly opened feedback portal Refer this

A: I created this plunker where you can filter your grid by product Name. It's a very basic example:
import { Component } from '@angular/core';

import {
  GridDataResult,
  SortDescriptor,
  orderBy
} from '@progress/kendo-angular-grid';

@Component({
  selector: 'my-app',
  template: `
      <input type="text" [(ngModel)]="filter" (ngModelChange)="change()">
      <kendo-grid
          [data]="gridView"
          [sortable]="{ mode: 'multiple' }"
          [sort]="sort"
          (sortChange)="sortChange($event)"
        >
        <kendo-grid-column field="ProductID" title="Product ID" width="120">
        </kendo-grid-column>
        <kendo-grid-column field="ProductName" title="Product Name">
        </kendo-grid-column>
        <kendo-grid-column field="UnitPrice" title="Unit Price" width="230">
        </kendo-grid-column>
      </kendo-grid>
  `
})
export class AppComponent {
    private filter: string;
    private sort: SortDescriptor[] = [];
    private gridView: GridDataResult;
    private products: any[] = [
      {
        "ProductID": 1,
        "ProductName": "Chai",
        "UnitPrice": 18.0000,
        "Discontinued": false
    },
       {
        "ProductID": 3,
        "ProductName": "Chai",
        "UnitPrice": 122.0000,
        "Discontinued": true
    }
                               ,{
        "ProductID": 2,
        "ProductName": "Chang",
        "UnitPrice": 19.0000,
        "Discontinued": false
    }];

    constructor() {
        this.loadProducts();
    }

    protected sortChange(sort: SortDescriptor[]): void {
        this.sort = sort;
        this.loadProducts();
    }

    private loadProducts(prods): void {
      const products = prods || this.products;
        this.gridView = {
            data: orderBy(products, this.sort),
            total: products.length
        };
    }

   private change(){
      this.loadProducts(this.products.filter(product => product.ProductName === this.filter));
   }

}

A: I was just checking possible ways to enable filter in Kendo Angular 2 Grid and found that Telerik has enabled it. Please check following link.
http://www.telerik.com/kendo-angular-ui/components/grid/filtering/

A: i added to the Fabio Antunes solution
Import compileFilter from '@progress/kendo-data-query';
and change the change() method to the following.  This will allow you to filter by multiple columns.  Again not exactly what i want, but this will do for now.
const predicate = compileFilter({
            logic: "and",
            filters: [
                { field: "fildname1", operator: "contains", value: this.filterValue },
                { field: "fildname2", operator: "contains", value: this.filterValue },
                { field: "fildname3", operator: "eq", value: this.filterValue },
                { field: "fildname4", operator: "eq", value: this.filterValue },
            ]
        });
        const result = this.data.filter(predicate);
        this.gridView = {
            data: result,
            total: result.length
        };

A: Update on the Kendo filter - Very similar to Nonik's solution.
Replace "compileFilter" with "filterBy".  This is part of the dataquery set of helper functions.
import { filterBy } from '@progress/kendo-data-query'

Kendo Data Query

A: For your information Kendo Grid has add filter feature in latest version. Please look at their website.
If you stll required some custome filter with kendo grid in angular 2 then look at here or search in google : Angular-2 + Kendo Grid Custom Filter


text:
Q: Error message when defining struct I am writing a struct in Swift:
struct LevelDictionary {
    let kNumberOfSegments: Int = 10

    static func loadLevelData() -> NSDictionary {
        for var segmentNumber = 0; segmentNumber < kNumberOfSegments; ++segmentNumber {
       //My code here
        }
    return dictionary
    }
}

For some reason I get an error on compiling: Instance member 'kNumberOfSegments' cannot be used on type 'LevelDictionary'. What am I missing? I get the same error when I set up LevelDictionary as a Class.

A: loadLevelData() is a static function which is called on "class" level
LevelDictionary.loadLevelData()

To use kNumberOfSegments in the static function it must be static as well
static let kNumberOfSegments: Int = 10

A: The direct answer to your question is that you can't use a property in class scope.
A different answer is that you seem to want a static function that returns a dictionary after doing something a certain number of times; which is why you have kNumberOfSegments in the first place. But do you really need to have a variable for something that you aren't going to use again. Another way to do this is to have a default variable in your class method:
struct LevelDictionary {

    static func loadLevelData(numberOfSegments: Int = 10) -> NSDictionary {
        for segment in 0 ..< numberOfSegments {
            // your code here
        }
        return dictionary
    }
}

Now you can call the method without an argument to use the default
let dictionary = LevelDictionary.loadLevelData() // Will use 10 segments

Or you can use a parameter to override the default
let dictianary = LevelDictionary.loadLevelData(20) // Will use 20 segments

A: You can't use instance member variables/constants inside the static function. (In terms of Objective C you can't use instance member objects inside class function)
Either you should declare the kNumberOfSegments as static or make that function as non-static. I prefer the first option,
struct LevelDictionary
{
    static let kNumberOfSegments: Int = 10

    static func loadLevelData() -> NSDictionary
    {
        for var segmentNumber = 0; segmentNumber < kNumberOfSegments; ++segmentNumber
        {
            //My code here
        }
        return dictionary
    }
}


text:
Q: simple example for the creation of a custom directory namer I have read the main idea of how Create a custom directory namer on github. But, I did not manage to know how to start. So, I am wondering if there is simple example for it.
Thank you very much.

A: You can find a sample DirectoryNamer here:https://github.com/dustin10/VichUploaderBundle/issues/242#issuecomment-44566041


text:
Q: Horizontal Line in Table Cell Why do the horizontal lines not appear in the first column?
\documentclass[a4paper,11pt,fleqn]{scrartcl}
\usepackage[utf8]{inputenc}
\usepackage[T1]{fontenc}
\usepackage[ngerman]{babel}

\usepackage{tabularx}
\newcolumntype{L}[1]{>{\raggedright\arraybackslash}p{#1}} % linksbündig mit Breitenangabe
\newcolumntype{C}[1]{>{\centering\arraybackslash}p{#1}} % zentriert mit Breitenangabe
\newcolumntype{R}[1]{>{\raggedleft\arraybackslash}p{#1}} % rechtsbündig mit Breitenangabe
\newcolumntype{N}{@{}m{0pt}@{}}

\def\Vrulefill#1#2{
\leavevmode%
\hskip-.2in%
\leaders%
\vtop{\hsize=.0025in\vskip#1#2}%
\hfill%
\hskip.3in%
}

\begin{document}
\begin{center}
\begin{tabular}{C{2cm}cccclcr}
 Source                  & SS                    & df                           & MS                    & \hphantom{Nu}   & Number of obs & = & 250 \\
 \Vrulefill{-.12in}{.}   & \Vrulefill{-.12in}{.} & \Vrulefill{-.12in}{.}       & \Vrulefill{-.12in}{.} & \hphantom{Nu}   & F(5,94)       & = & 75.04\\
 Model                   & 7955693.156           & 4                        & 1988923.289           & \hphantom{Nu}   & Prob $>$ F      & = & 0.0000 \\
 Residual                & 6493440.8             & 245                          & 26503.84              & \hphantom{Nu}   & R-squared     & = & 0.5506\\
 \Vrulefill{-.12in}{.}   & \Vrulefill{-.12in}{.} &    \Vrulefill{-.12in}{.} &\Vrulefill{-.12in}{.}  & \hphantom{Nu}   & Adj R-squared & = & 0.5433\\
 Total                   & 14449133.96           & 249                      & 58028.6504            & \hphantom{Nu}   & Root MSE      & = & 162.8\\
\end{tabular}
\end{center}

\end{document}

A: I don't know why, but the xhfill package does the job very simply:
\documentclass[a4paper, 11pt, fleqn]{scrartcl}
\usepackage[utf8]{inputenc}
\usepackage[T1]{fontenc}
\usepackage[ngerman]{babel}

\usepackage{tabularx}
\newcolumntype{L}[1]{>{\raggedright\arraybackslash}p{#1}} % linksbündig mit Breitenangabe
\newcolumntype{C}[1]{>{\centering\arraybackslash}p{#1}} % zentriert mit Breitenangabe
\newcolumntype{R}[1]{>{\raggedleft\arraybackslash}p{#1}} % rechtsbündig mit Breitenangabe
\newcolumntype{N}{@{}m{0pt}@{}}

\usepackage{xhfill}

\begin{document}

\begin{center}
\begin{tabular}{@{}C{2cm}cccclcr}
 Source & SS & df & MS & \hphantom{Nu} & Number of obs & = & 250 \\
 \multicolumn{4}{c}{\xrfill[1.6ex]{1.2pt}} & \hphantom{Nu} & F(5,94) & = & 75.04\\
 Model & 7955693.156 & 4 & 1988923.289 & \hphantom{Nu} & Prob $>$ F & = & 0.0000 \\
 Residual & 6493440.8 & 245 & 26503.84 & \hphantom{Nu} & R-squared & = & 0.5506\\
 \multicolumn{4}{c}{\xrfill[1.6ex]{1.2pt}} & \hphantom{Nu} & Adj R-squared & = & 0.5433\\
 Total & 14449133.96 & 249 & 58028.6504 & \hphantom{Nu} & Root MSE & = & 162.8\\
\end{tabular}
\end{center}

\end{document}


text:
Q: fast list subtraction for big list with o(n) order in python I have two big string list in python. I want to subtract these two list fast with the order of o(n). I found some way like remove second list elements in a loop from first list, or converting list to set() (problem:change order of list)and use minus(-) operator, but these methods are not efficient. Is there any way for doing this operation?
a=['1','2','3',...,'500000']
b=['1','2','3',...,'200000']

c=a-b

c=['200001','200002',...,'500000']

A: Your problem, as formulated, is:

*

*Go through A

*For each element, search it in B and take it if it's not found

*No assumptions about elements is made

For arbitrary data, list search is O(N), set search is O(1), converting to set is O(N). Going through A is O(N).
So it's O(N^2) with only lists and O(N) if converting B to a set.
The only way you can speed it up is to make either iterating or searching more efficient -- which is impossible without using some additional knowledge about your data. E.g.

*

*In your example, your data are sequential numbers, so you can take A[len(B):].

*If you are going to use the same B multiple times, you can cache the set

*You can make B a set right off the bat (if order needs to be preserved, you can use an ordered set)

*If all data are of the same type and are short, you can use numpy arrays and its fast setdiff1d

*etc


text:
Q: Env stopped working correctly after calling openDexFile function in JNI case I have application that encrypt classes.dex file in android apps for reverse protection. After decryption classes.dex dynamically loading from memory, but I've trouble with android 4.4 KitKat (api level 19). After launching encrypted apk on emulator (AVD from Android studio) it crashes.
Problem is in this piece of code:
jint mCookie = mem_loadDex_dvm(env, (char *)szDexPath);
// error appears in line below
jclass DexFileClass = env->FindClass("dalvik/system/DexFile");

line in github
exactly if to jump in mem_loadDex_dvm function, problem appear after this line
openDexFile(args, &pResult);

line in github
Error text:
W/dalvikvm: JNI WARNING: JNI function FindClass called with exception pending
W/dalvikvm:              in Lcom/storm/fengyue/Native;.attachBaseContext:(Landroid/content/Context;)V (FindClass)
W/dalvikvm: Pending exception is:
I/dalvikvm: java.lang.RuntimeException: unable to open in-memory DEX file
I/dalvikvm:     at com.storm.fengyue.Native.attachBaseContext(Native Method)
I/dalvikvm:     at com.storm.fengyue.StubApplication.attachBaseContext(StubApplication.java:105)
I/dalvikvm:     at android.app.Application.attach(Application.java:181)
I/dalvikvm:     at android.app.Instrumentation.newApplication(Instrumentation.java:991)
I/dalvikvm:     at android.app.Instrumentation.newApplication(Instrumentation.java:975)
I/dalvikvm:     at android.app.LoadedApk.makeApplication(LoadedApk.java:511)
I/dalvikvm:     at android.app.ActivityThread.handleBindApplication(ActivityThread.java:4317)
I/dalvikvm:     at android.app.ActivityThread.access$1500(ActivityThread.java:135)
I/dalvikvm:     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1256)
I/dalvikvm:     at android.os.Handler.dispatchMessage(Handler.java:102)
I/dalvikvm:     at android.os.Looper.loop(Looper.java:136)
I/dalvikvm:     at android.app.ActivityThread.main(ActivityThread.java:5017)
I/dalvikvm:     at java.lang.reflect.Method.invokeNative(Native Method)
I/dalvikvm:     at java.lang.reflect.Method.invoke(Method.java:515)
I/dalvikvm:     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
I/dalvikvm:     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
I/dalvikvm:     at dalvik.system.NativeStart.main(Native Method)
I/dalvikvm: "main" prio=5 tid=1 NATIVE
I/dalvikvm:   | group="main" sCount=0 dsCount=0 obj=0x9cd62bd8 self=0xb8d0e4a0
I/dalvikvm:   | sysTid=2388 nice=0 sched=0/0 cgrp=[fopen-error:2] handle=-1216544672
I/dalvikvm:   | state=R schedstat=( 0 0 0 ) utm=16 stm=0 core=3
I/dalvikvm:   #00  pc 000bd4b6  /system/lib/libdvm.so (dvmDumpNativeStack(DebugOutputTarget const*, int)+86)
I/dalvikvm:   #01  pc 00098093  /system/lib/libdvm.so (dvmDumpThreadEx(DebugOutputTarget const*, Thread*, bool)+1155)
I/dalvikvm:   #02  pc 00098386  /system/lib/libdvm.so (dvmDumpThread(Thread*, bool)+86)
I/dalvikvm:   #03  pc 0004ce17  /system/lib/libdvm.so (ScopedCheck::checkThread(int)+455)
I/dalvikvm:   #04  pc 000601e5  /system/lib/libdvm.so
I/dalvikvm:   #05  pc 00008a26  /data/data/home.blank/files/.jiagu/libdexload.so (mem_loadDex(_JNIEnv*, _jobject*, char const*)+1334)
I/dalvikvm:   #06  pc 00009158  /data/data/home.blank/files/.jiagu/libdexload.so (native_attachBaseContext(_JNIEnv*, _jobject*, _jobject*)+1096)
I/dalvikvm:   #07  pc 0002a0eb  /system/lib/libdvm.so (dvmPlatformInvoke+79)
I/dalvikvm:     at com.storm.fengyue.Native.attachBaseContext(Native Method)
I/dalvikvm:     at com.storm.fengyue.StubApplication.attachBaseContext(StubApplication.java:105)
I/dalvikvm:     at android.app.Application.attach(Application.java:181)
I/dalvikvm:     at android.app.Instrumentation.newApplication(Instrumentation.java:991)
I/dalvikvm:     at android.app.Instrumentation.newApplication(Instrumentation.java:975)
I/dalvikvm:     at android.app.LoadedApk.makeApplication(LoadedApk.java:511)
I/dalvikvm:     at android.app.ActivityThread.handleBindApplication(ActivityThread.java:4317)
I/dalvikvm:     at android.app.ActivityThread.access$1500(ActivityThread.java:135)
I/dalvikvm:     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1256)
I/dalvikvm:     at android.os.Handler.dispatchMessage(Handler.java:102)
I/dalvikvm:     at android.os.Looper.loop(Looper.java:136)
I/dalvikvm:     at android.app.ActivityThread.main(ActivityThread.java:5017)
I/dalvikvm:     at java.lang.reflect.Method.invokeNative(Native Method)
I/dalvikvm:     at java.lang.reflect.Method.invoke(Method.java:515)
I/dalvikvm:     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
I/dalvikvm:     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
I/dalvikvm:     at dalvik.system.NativeStart.main(Native Method)
E/dalvikvm: VM aborting

It's no depend of FindClass, other functions give same error (env->GetFieldID or env->SetFieldID).
Tried to display env hex value, it similar before and after problem line.
Checked that JNI is attached of current thread.
All code are in github


text:
Q: java.lang.ClassCircularityError while deploying artifact on server when I run tomcat server, while deploying the artifact, I am getting two errors.
First error is:
ERROR in ch.qos.logback.core.rolling.RollingFileAppender[FILE] - openFile(LogisticsServices.log,true) call failed. java.io.FileNotFoundException: LogisticsServices.log (Access is denied)
        at java.io.FileNotFoundException: LogisticsServices.log (Access is denied)

Second error is :
Exception in thread "RMI TCP Connection(idle)" java.lang.ClassCircularityError: java/util/logging/LogRecord

I checked the permission of the LogisticsServices.log file and changed permission to full control for users.Still same error is occuring.
And when I search for the ClassCircularityError, I could not get any relevant info. I am not sure what is actual error in both these and what should I do to fix this.I am attaching full stack trace of the error
Any help would be great
15:32:13,126 |-ERROR in ch.qos.logback.core.rolling.RollingFileAppender[FILE] - openFile(LogisticsServices.log,true) call failed. java.io.FileNotFoundException: LogisticsServices.log (Access is denied)
    at java.io.FileNotFoundException: LogisticsServices.log (Access is denied)
    at  at java.io.FileOutputStream.open(Native Method)
    at  at java.io.FileOutputStream.<init>(FileOutputStream.java:221)
    at  at ch.qos.logback.core.recovery.ResilientFileOutputStream.<init>(ResilientFileOutputStream.java:28)
    at  at ch.qos.logback.core.FileAppender.openFile(FileAppender.java:148)
    at  at ch.qos.logback.core.FileAppender.start(FileAppender.java:108)
    at  at ch.qos.logback.core.rolling.RollingFileAppender.start(RollingFileAppender.java:86)
    at  at ch.qos.logback.core.joran.action.AppenderAction.end(AppenderAction.java:96)
    at  at ch.qos.logback.core.joran.spi.Interpreter.callEndAction(Interpreter.java:317)
    at  at ch.qos.logback.core.joran.spi.Interpreter.endElement(Interpreter.java:196)
    at  at ch.qos.logback.core.joran.spi.Interpreter.endElement(Interpreter.java:182)
    at  at ch.qos.logback.core.joran.spi.EventPlayer.play(EventPlayer.java:62)
    at  at ch.qos.logback.core.joran.GenericConfigurator.doConfigure(GenericConfigurator.java:149)
    at  at ch.qos.logback.core.joran.GenericConfigurator.doConfigure(GenericConfigurator.java:135)
    at  at ch.qos.logback.core.joran.GenericConfigurator.doConfigure(GenericConfigurator.java:99)
    at  at ch.qos.logback.core.joran.GenericConfigurator.doConfigure(GenericConfigurator.java:49)
    at  at ch.qos.logback.classic.util.ContextInitializer.configureByResource(ContextInitializer.java:77)
    at  at ch.qos.logback.classic.util.ContextInitializer.autoConfig(ContextInitializer.java:152)
    at  at org.slf4j.impl.StaticLoggerBinder.init(StaticLoggerBinder.java:85)
    at  at org.slf4j.impl.StaticLoggerBinder.<clinit>(StaticLoggerBinder.java:55)
    at  at org.slf4j.LoggerFactory.bind(LoggerFactory.java:141)
    at  at org.slf4j.LoggerFactory.performInitialization(LoggerFactory.java:120)
    at  at org.slf4j.LoggerFactory.getILoggerFactory(LoggerFactory.java:331)
    at  at org.slf4j.LoggerFactory.getLogger(LoggerFactory.java:283)
    at  at org.apache.commons.logging.impl.SLF4JLogFactory.getInstance(SLF4JLogFactory.java:155)
    at  at org.apache.commons.logging.impl.SLF4JLogFactory.getInstance(SLF4JLogFactory.java:132)
    at  at org.apache.commons.logging.LogFactory.getLog(LogFactory.java:657)
    at  at org.springframework.web.context.ContextLoader.initWebApplicationContext(ContextLoader.java:282)
    at  at org.springframework.web.context.ContextLoaderListener.contextInitialized(ContextLoaderListener.java:112)
    at  at org.apache.catalina.core.StandardContext.listenerStart(StandardContext.java:4779)
    at  at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5273)
    at  at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
    at  at org.apache.catalina.core.ContainerBase.addChildInternal(ContainerBase.java:895)
    at  at org.apache.catalina.core.ContainerBase.addChild(ContainerBase.java:871)
    at  at org.apache.catalina.core.StandardHost.addChild(StandardHost.java:615)
    at  at org.apache.catalina.startup.HostConfig.manageApp(HostConfig.java:1501)
    at  at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at  at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
    at  at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at  at java.lang.reflect.Method.invoke(Method.java:606)
    at  at org.apache.tomcat.util.modeler.BaseModelMBean.invoke(BaseModelMBean.java:301)
    at  at com.sun.jmx.interceptor.DefaultMBeanServerInterceptor.invoke(DefaultMBeanServerInterceptor.java:819)
    at  at com.sun.jmx.mbeanserver.JmxMBeanServer.invoke(JmxMBeanServer.java:801)
    at  at org.apache.catalina.mbeans.MBeanFactory.createStandardContext(MBeanFactory.java:619)
    at  at org.apache.catalina.mbeans.MBeanFactory.createStandardContext(MBeanFactory.java:566)
    at  at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at  at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
    at  at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at  at java.lang.reflect.Method.invoke(Method.java:606)
    at  at org.apache.tomcat.util.modeler.BaseModelMBean.invoke(BaseModelMBean.java:301)
    at  at com.sun.jmx.interceptor.DefaultMBeanServerInterceptor.invoke(DefaultMBeanServerInterceptor.java:819)
    at  at com.sun.jmx.mbeanserver.JmxMBeanServer.invoke(JmxMBeanServer.java:801)
    at  at javax.management.remote.rmi.RMIConnectionImpl.doOperation(RMIConnectionImpl.java:1487)
    at  at javax.management.remote.rmi.RMIConnectionImpl.access$300(RMIConnectionImpl.java:97)
    at  at javax.management.remote.rmi.RMIConnectionImpl$PrivilegedOperation.run(RMIConnectionImpl.java:1328)
    at  at javax.management.remote.rmi.RMIConnectionImpl.doPrivilegedOperation(RMIConnectionImpl.java:1420)
    at  at javax.management.remote.rmi.RMIConnectionImpl.invoke(RMIConnectionImpl.java:848)
    at  at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at  at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
    at  at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at  at java.lang.reflect.Method.invoke(Method.java:606)
    at  at sun.rmi.server.UnicastServerRef.dispatch(UnicastServerRef.java:322)
    at  at sun.rmi.transport.Transport$2.run(Transport.java:202)
    at  at sun.rmi.transport.Transport$2.run(Transport.java:199)
    at  at java.security.AccessController.doPrivileged(Native Method)
    at  at sun.rmi.transport.Transport.serviceCall(Transport.java:198)
    at  at sun.rmi.transport.tcp.TCPTransport.handleMessages(TCPTransport.java:567)
    at  at sun.rmi.transport.tcp.TCPTransport$ConnectionHandler.run0(TCPTransport.java:828)
    at  at sun.rmi.transport.tcp.TCPTransport$ConnectionHandler.access$400(TCPTransport.java:619)
    at  at sun.rmi.transport.tcp.TCPTransport$ConnectionHandler$1.run(TCPTransport.java:684)
    at  at sun.rmi.transport.tcp.TCPTransport$ConnectionHandler$1.run(TCPTransport.java:681)
    at  at java.security.AccessController.doPrivileged(Native Method)
    at  at sun.rmi.transport.tcp.TCPTransport$ConnectionHandler.run(TCPTransport.java:681)
    at  at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
    at  at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
    at  at java.lang.Thread.run(Thread.java:745)
15:32:13,126 |-INFO in ch.qos.logback.classic.joran.action.RootLoggerAction - Setting level of ROOT logger to INFO
15:32:13,126 |-INFO in ch.qos.logback.core.joran.action.AppenderRefAction - Attaching appender named [FILE] to Logger[ROOT]
15:32:13,127 |-INFO in ch.qos.logback.classic.joran.action.ConfigurationAction - End of configuration.
15:32:13,128 |-INFO in ch.qos.logback.classic.joran.JoranConfigurator@71b653af - Registering current configuration as safe fallback point

Jun 21, 2015 3:32:13 PM org.apache.catalina.core.ApplicationContext log
INFO: Initializing Spring root WebApplicationContext
Jun 21, 2015 3:32:17 PM org.apache.catalina.startup.HostConfig deployDirectory
INFO: Deploying web application directory C:\Program Files\Apache Software Foundation\Tomcat 7.0\webapps\manager
Exception in thread "RMI TCP Connection(idle)" java.lang.ClassCircularityError: java/util/logging/LogRecord
    at org.slf4j.bridge.SLF4JBridgeHandler.getSLF4JLogger(SLF4JBridgeHandler.java:198)
    at org.slf4j.bridge.SLF4JBridgeHandler.publish(SLF4JBridgeHandler.java:287)
    at java.util.logging.Logger.log(Logger.java:616)
    at java.util.logging.Logger.doLog(Logger.java:641)
    at java.util.logging.Logger.logp(Logger.java:757)
    at sun.rmi.runtime.Log$LoggerLog.log(Log.java:228)
    at sun.rmi.transport.tcp.TCPConnection.close(TCPConnection.java:219)
    at sun.rmi.transport.tcp.TCPTransport.handleMessages(TCPTransport.java:596)
    at sun.rmi.transport.tcp.TCPTransport$ConnectionHandler.run0(TCPTransport.java:828)
    at sun.rmi.transport.tcp.TCPTransport$ConnectionHandler.access$400(TCPTransport.java:619)
    at sun.rmi.transport.tcp.TCPTransport$ConnectionHandler$1.run(TCPTransport.java:684)
    at sun.rmi.transport.tcp.TCPTransport$ConnectionHandler$1.run(TCPTransport.java:681)
    at java.security.AccessController.doPrivileged(Native Method)
    at sun.rmi.transport.tcp.TCPTransport$ConnectionHandler.run(TCPTransport.java:681)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
    at java.lang.Thread.run(Thread.java:745)
Exception in thread "RMI TCP Connection(idle)" java.lang.ClassCircularityError: java/util/logging/LogRecord
    at org.slf4j.bridge.SLF4JBridgeHandler.getSLF4JLogger(SLF4JBridgeHandler.java:198)
    at org.slf4j.bridge.SLF4JBridgeHandler.publish(SLF4JBridgeHandler.java:287)
    at java.util.logging.Logger.log(Logger.java:616)
    at java.util.logging.Logger.doLog(Logger.java:641)
    at java.util.logging.Logger.logp(Logger.java:757)
    at sun.rmi.runtime.Log$LoggerLog.log(Log.java:228)
    at sun.rmi.transport.tcp.TCPTransport$ConnectionHandler.run0(TCPTransport.java:770)
    at sun.rmi.transport.tcp.TCPTransport$ConnectionHandler.access$400(TCPTransport.java:619)
    at sun.rmi.transport.tcp.TCPTransport$ConnectionHandler$1.run(TCPTransport.java:684)
    at sun.rmi.transport.tcp.TCPTransport$ConnectionHandler$1.run(TCPTransport.java:681)
    at java.security.AccessController.doPrivileged(Native Method)
    at sun.rmi.transport.tcp.TCPTransport$ConnectionHandler.run(TCPTransport.java:681)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
    at java.lang.Thread.run(Thread.java:745)
Exception in thread "RMI TCP Connection(idle)" java.lang.ClassCircularityError: java/util/logging/LogRecord
    at org.slf4j.bridge.SLF4JBridgeHandler.getSLF4JLogger(SLF4JBridgeHandler.java:198)
    at org.slf4j.bridge.SLF4JBridgeHandler.publish(SLF4JBridgeHandler.java:287)
    at java.util.logging.Logger.log(Logger.java:616)
    at java.util.logging.Logger.doLog(Logger.java:641)
    at java.util.logging.Logger.logp(Logger.java:757)
    at sun.rmi.runtime.Log$LoggerLog.log(Log.java:228)
    at sun.rmi.transport.tcp.TCPTransport$ConnectionHandler.run0(TCPTransport.java:770)
    at sun.rmi.transport.tcp.TCPTransport$ConnectionHandler.access$400(TCPTransport.java:619)
    at sun.rmi.transport.tcp.TCPTransport$ConnectionHandler$1.run(TCPTransport.java:684)
    at sun.rmi.transport.tcp.TCPTransport$ConnectionHandler$1.run(TCPTransport.java:681)
    at java.security.AccessController.doPrivileged(Native Method)
    at sun.rmi.transport.tcp.TCPTransport$ConnectionHandler.run(TCPTransport.java:681)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
    at java.lang.Thread.run(Thread.java:745)
[2015-06-21 03:32:23,596] Artifact logistics-services:war exploded: Error during artifact deployment. See server log for details.
Exception in thread "RMI TCP Connection(idle)" java.lang.ClassCircularityError: java/util/logging/LogRecord
    at org.slf4j.bridge.SLF4JBridgeHandler.getSLF4JLogger(SLF4JBridgeHandler.java:198)
    at org.slf4j.bridge.SLF4JBridgeHandler.publish(SLF4JBridgeHandler.java:287)
    at java.util.logging.Logger.log(Logger.java:616)
    at java.util.logging.Logger.doLog(Logger.java:641)
    at java.util.logging.Logger.logp(Logger.java:757)
    at sun.rmi.runtime.Log$LoggerLog.log(Log.java:228)
    at sun.rmi.transport.tcp.TCPTransport$ConnectionHandler.run0(TCPTransport.java:770)
    at sun.rmi.transport.tcp.TCPTransport$ConnectionHandler.access$400(TCPTransport.java:619)
    at sun.rmi.transport.tcp.TCPTransport$ConnectionHandler$1.run(TCPTransport.java:684)
    at sun.rmi.transport.tcp.TCPTransport$ConnectionHandler$1.run(TCPTransport.java:681)
    at java.security.AccessController.doPrivileged(Native Method)
    at sun.rmi.transport.tcp.TCPTransport$ConnectionHandler.run(TCPTransport.java:681)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
    at java.lang.Thread.run(Thread.java:745)


text:
Q: Problems with clipboard in C# I used to write a lot of Visual Basic 6.0, and recently I've dabbled in VB.NET.  I've been working with a startup friend of mine on some general bits of programming, and found that C# is pretty straightforward.
The application I've written works fine 99% of the time, but occasionally, I can't write to the clipboard without the application crashing out to the "Windows has detected a problem".
This is what was in the Event Log:
Application: SLicenseTool.exe
Framework Version: v4.0.30319
Description: The process was terminated due to an unhandled exception.
Exception Info: System.Runtime.InteropServices.COMException
Stack:
   at System.Runtime.InteropServices.Marshal.ThrowExceptionForHRInternal(Int32, IntPtr)
   at System.Runtime.InteropServices.Marshal.ThrowExceptionForHR(Int32, IntPtr)
   at System.Windows.Clipboard.Flush()
   at System.Windows.Clipboard.CriticalSetDataObject(System.Object, Boolean)
   at System.Windows.Clipboard.SetDataInternal(System.String, System.Object)
   at System.Windows.Clipboard.SetText(System.String, System.Windows.TextDataFormat)
   at System.Windows.Clipboard.SetText(System.String)
   at SLicenseTool.MainWindow.GenerateLicense_Click(System.Object, System.Windows.RoutedEventArgs)
   at System.Windows.RoutedEventHandlerInfo.InvokeHandler(System.Object, System.Windows.RoutedEventArgs)
   at System.Windows.EventRoute.InvokeHandlersImpl(System.Object, System.Windows.RoutedEventArgs, Boolean)
   at System.Windows.UIElement.RaiseEventImpl(System.Windows.DependencyObject, System.Windows.RoutedEventArgs)
   at System.Windows.UIElement.RaiseEvent(System.Windows.RoutedEventArgs)
   at System.Windows.Controls.Primitives.ButtonBase.OnClick()
   at System.Windows.Controls.Button.OnClick()
   at System.Windows.Controls.Primitives.ButtonBase.OnMouseLeftButtonUp(System.Windows.Input.MouseButtonEventArgs)
   at System.Windows.UIElement.OnMouseLeftButtonUpThunk(System.Object, System.Windows.Input.MouseButtonEventArgs)
   at System.Windows.Input.MouseButtonEventArgs.InvokeEventHandler(System.Delegate, System.Object)
   at System.Windows.RoutedEventArgs.InvokeHandler(System.Delegate, System.Object)
   at System.Windows.RoutedEventHandlerInfo.InvokeHandler(System.Object, System.Windows.RoutedEventArgs)
   at System.Windows.EventRoute.InvokeHandlersImpl(System.Object, System.Windows.RoutedEventArgs, Boolean)
   at System.Windows.UIElement.ReRaiseEventAs(System.Windows.DependencyObject, System.Windows.RoutedEventArgs, System.Windows.RoutedEvent)
   at System.Windows.UIElement.OnMouseUpThunk(System.Object, System.Windows.Input.MouseButtonEventArgs)
   at System.Windows.Input.MouseButtonEventArgs.InvokeEventHandler(System.Delegate, System.Object)
   at System.Windows.RoutedEventArgs.InvokeHandler(System.Delegate, System.Object)
   at System.Windows.RoutedEventHandlerInfo.InvokeHandler(System.Object, System.Windows.RoutedEventArgs)
   at System.Windows.EventRoute.InvokeHandlersImpl(System.Object, System.Windows.RoutedEventArgs, Boolean)
   at System.Windows.UIElement.RaiseEventImpl(System.Windows.DependencyObject, System.Windows.RoutedEventArgs)
   at System.Windows.UIElement.RaiseTrustedEvent(System.Windows.RoutedEventArgs)
   at System.Windows.UIElement.RaiseEvent(System.Windows.RoutedEventArgs, Boolean)
   at System.Windows.Input.InputManager.ProcessStagingArea()
   at System.Windows.Input.InputManager.ProcessInput(System.Windows.Input.InputEventArgs)
   at System.Windows.Input.InputProviderSite.ReportInput(System.Windows.Input.InputReport)
   at System.Windows.Interop.HwndMouseInputProvider.ReportInput(IntPtr, System.Windows.Input.InputMode, Int32, System.Windows.Input.RawMouseActions, Int32, Int32, Int32)
   at System.Windows.Interop.HwndMouseInputProvider.FilterMessage(IntPtr, MS.Internal.Interop.WindowMessage, IntPtr, IntPtr, Boolean ByRef)
   at System.Windows.Interop.HwndSource.InputFilterMessage(IntPtr, Int32, IntPtr, IntPtr, Boolean ByRef)
   at MS.Win32.HwndWrapper.WndProc(IntPtr, Int32, IntPtr, IntPtr, Boolean ByRef)
   at MS.Win32.HwndSubclass.DispatcherCallbackOperation(System.Object)
   at System.Windows.Threading.ExceptionWrapper.InternalRealCall(System.Delegate, System.Object, Int32)
   at MS.Internal.Threading.ExceptionFilterHelper.TryCatchWhen(System.Object, System.Delegate, System.Object, Int32, System.Delegate)
   at System.Windows.Threading.Dispatcher.LegacyInvokeImpl(System.Windows.Threading.DispatcherPriority, System.TimeSpan, System.Delegate, System.Object, Int32)
   at MS.Win32.HwndSubclass.SubclassWndProc(IntPtr, Int32, IntPtr, IntPtr)
   at MS.Win32.UnsafeNativeMethods.DispatchMessage(System.Windows.Interop.MSG ByRef)
   at System.Windows.Threading.Dispatcher.PushFrameImpl(System.Windows.Threading.DispatcherFrame)
   at System.Windows.Threading.Dispatcher.PushFrame(System.Windows.Threading.DispatcherFrame)
   at System.Windows.Threading.Dispatcher.Run()
   at System.Windows.Application.RunDispatcher(System.Object)
   at System.Windows.Application.RunInternal(System.Windows.Window)
   at System.Windows.Application.Run(System.Windows.Window)
   at System.Windows.Application.Run()
   at SLicenseTool.App.Main()

I'm using the rhino-licensing library.
This is the code that is in GenerateLicense_Click:
var license = generator.Generate(txtName.Text, id, expirationDate, attribs, licenseType);
Clipboard.SetText(license);

What I'm not sure about is why it would work on my PC, and a few times on my friend's PC, but it randomly fails. It seems that there's some problem accessing the clipboard, but I'm unsure what the next steps are with debugging/ fixing it.
I'm going to rewrite the application to stop using the clipboard, and instead use regular save file / open file dialogs. It seems more reliable.


text:
Q: Joomla giving blank screen after http error 500 I had Joomla site giving an HTTP error 500 on both the frontend and backend.
I changed the permissions on index.php to 755 but no luck.
I noticed it was running PHP 5.6 so I upgraded to PHP 7 and now it's just giving me a blank screen. I checked the error log and I'm receiving the following error:
PHP Warning:  PHP Startup: Unable to load dynamic library
'/usr/php/54/usr/lib64/php/modules/uploadprogress.so' -
/usr/php/54/usr/lib64/php/modules/uploadprogress.so: undefined symbol:
zend_ini_string_ex in Unknown on line 0

I was also getting this error beforehand. Any ideas on what module I can / should disable to fix this?

A: The warning that you're seeing has likely nothing to do with the blank page. Assuming you already set the $error_reporting to maximum in your configuration.php file and you didn't see the error, then try disabling system plugins one by one (disable the last ones installed first) until the problem is fixed.
Now, if you still see the error, then it is possible that you didn't install the PHP MySQL module when you updated to PHP 7. This issue is common when you have WHM, essentially, you will need to install the module through EasyApache. See this post about this.


text: Q: Windows: How to add a custom file property When you right select a file in file explorer, you can see many properties like creation date, modified date, date taken(for photos) etc, How do i add a custom value to that list?


text:
Q: Finding Probabilities from moment generating functions
If
$$M_X(t) = (1 - p + pe^t)^5,$$
find $P(X \le 1.23).$

I seem not to understand the connection between cdf and mgf. Can I find the $E(X)$ and then use the formula for $E(X)$ to derive the probability? I am so confused.

A: We recognize $(1 - p + pe^t)^5$ as the moment generating function for a binomial random variable, so $ X \sim Binomial(5,p)$.
Since X takes on integer values,
$$ P(X<1.23) = P(X=0) + P(X=1) = (1-p)^5+5p(1-p)^4$$


text:
Q: How to call anonymous functions from HTML components' events using JQuery? I have a button. I registered a function to treat the click event. However, I want to call it if another event happens. How do I call it from another asynchronous (or synchronous) event?
My first idea was to write the function with a name. That way, I can bind it to the click event to my button and also call it whenever I want to. However, in the case I wrote an anonymous function, what are my options?
Example (pseudo-code):
create button b;
assign some function f to b to execute on click;
b.invoke(args); //invoke runs f without the need to click

A: You can fire the "click" event on the element.
$('#MyButton').trigger('click');

EDIT: sorry, I misunderstood the question. But, you can still trigger the event and let the function to use some global variable so you can access everywhere.


text:
Q: Magento2: How to get Bestseller products collection by category ids(subcategories) I need to get Bestseller products collection by category ids(subcategories)
Thanks

A: Step 1: Create a block file
<?php
namespace QaisarSatti\HelloWorld\Block;
class BestSeller extends \Magento\Framework\View\Element\Template
{

protected $_collectionFactory;

public function __construct(
    \Magento\Backend\Block\Template\Context $context,
    \Magento\Sales\Model\ResourceModel\Report\Bestsellers\CollectionFactory $collectionFactory,
    array $data = []
)
{

    $this->_collectionFactory = $collectionFactory;
    parent::__construct($context, $data);
}

public function getBestSellerData($category_ids)
{
    $bestSellerProdcutCollection = $this->_collectionFactory->create()
        ->setModel('Magento\Catalog\Model\Product')
        ->setPeriod('month')
        ->join(['secondTable' => 'catalog_category_product'], 'sales_bestsellers_aggregated_monthly.product_id = secondTable.product_id', ['category_id' => 'secondTable.category_id'])
        ->addFieldToFilter('category_id', $category_ids);

    return $bestSellerProdcutCollection;
}
}

Step 2: Show Output
Getting collection in phtml file from block.
<?php $category_ids = [1,2,3,4]; ?>
<?php $bestSeller = $block->getBestSellerData($category_ids); ?>

Best Seller Collection.....

    <?php foreach ($bestSeller as $product): ?>

<?php echo $product->getProductName(); ?>--<?php echo $product->getQtyOrdered(); ?>

    <?php endforeach; ?>


text:
Q: Network unreachable while tftp on a virtual machine. What config should I add? I'm trying to build a minimal kernel where tftp works.
I'm using busybox for initramfs and I'll be running the kernel on an arm64 virtual machine.
The command for getting file is tftp -g -r axpu_ldd_kc.ko my_ip_addr(of course my tftp server is working).
But the response is :
tftp: sendto: Network is unreachable
So I added some network stuff in the kernel configuration (linux-5.10.0-rc5) but still doesn't work.
I can't figure out what more to add just to make tftp work
Could anyone tell me what is missing from the defconfig below? (using e1000 in qemu virtual machine).
(As you can see, I added CONFIG_NF_CONNTRACK_TFTP for which the menuconfig says it's TFTP support. And the .config file has CONFIG_NF_NAT_TFTP set to =y. I show the defconfig because .config is too long)
# CONFIG_SWAP is not set
# CONFIG_CROSS_MEMORY_ATTACH is not set
CONFIG_PREEMPT=y
# CONFIG_CPU_ISOLATION is not set
CONFIG_LOG_BUF_SHIFT=12
CONFIG_LOG_CPU_MAX_BUF_SHIFT=10
CONFIG_PRINTK_SAFE_LOG_BUF_SHIFT=10
CONFIG_USER_NS=y
CONFIG_BLK_DEV_INITRD=y
CONFIG_INITRAMFS_SOURCE="../../../../ab21sim/ab21tsim/busybox-1.32.1/initramfs.cpio.gz"
# CONFIG_RD_BZIP2 is not set
# CONFIG_RD_LZMA is not set
# CONFIG_RD_XZ is not set
# CONFIG_RD_LZO is not set
# CONFIG_RD_LZ4 is not set
# CONFIG_RD_ZSTD is not set
CONFIG_PERF_EVENTS=y
CONFIG_SLAB=y
CONFIG_NR_CPUS=2
# CONFIG_RODATA_FULL_DEFAULT_ENABLED is not set
# CONFIG_ARM64_TAGGED_ADDR_ABI is not set
# CONFIG_ARM64_UAO is not set
# CONFIG_ARM64_RAS_EXTN is not set
# CONFIG_ARM64_CNP is not set
# CONFIG_ARM64_PTR_AUTH is not set
# CONFIG_ARM64_AMU_EXTN is not set
# CONFIG_ARM64_TLB_RANGE is not set
# CONFIG_ARM64_BTI is not set
# CONFIG_ARM64_E0PD is not set
# CONFIG_ARCH_RANDOM is not set
# CONFIG_ARM64_SVE is not set
# CONFIG_EFI is not set
# CONFIG_SECCOMP is not set
# CONFIG_BLK_DEV_BSG is not set
# CONFIG_MQ_IOSCHED_DEADLINE is not set
# CONFIG_MQ_IOSCHED_KYBER is not set
CONFIG_BINFMT_MISC=y
CONFIG_FLATMEM_MANUAL=y
# CONFIG_COMPACTION is not set
CONFIG_NET=y
CONFIG_INET=y
CONFIG_NETFILTER=y
CONFIG_NF_CONNTRACK=y
CONFIG_NF_CONNTRACK_TFTP=y
CONFIG_NF_NAT=y
CONFIG_DEVTMPFS=y
CONFIG_BLK_DEV_RAM=y
CONFIG_BLK_DEV_RAM_COUNT=1
CONFIG_BLK_DEV_RAM_SIZE=65536
CONFIG_NETDEVICES=y
# CONFIG_KEYBOARD_ATKBD is not set
# CONFIG_INPUT_MOUSE is not set
CONFIG_SERIO_LIBPS2=y
CONFIG_VT_HW_CONSOLE_BINDING=y
# CONFIG_LEGACY_PTYS is not set
CONFIG_SERIAL_AMBA_PL011=y
CONFIG_SERIAL_AMBA_PL011_CONSOLE=y
# CONFIG_HWMON is not set
# CONFIG_USB_SUPPORT is not set
CONFIG_RTC_CLASS=y
# CONFIG_RTC_HCTOSYS is not set
# CONFIG_RTC_INTF_SYSFS is not set
# CONFIG_RTC_INTF_PROC is not set
# CONFIG_RTC_INTF_DEV is not set
CONFIG_RTC_DRV_M48T59=y
# CONFIG_VHOST_MENU is not set
# CONFIG_IOMMU_SUPPORT is not set
# CONFIG_NVMEM_SYSFS is not set
CONFIG_EXT2_FS=y
CONFIG_EXT2_FS_XATTR=y
CONFIG_EXT2_FS_POSIX_ACL=y
CONFIG_EXT2_FS_SECURITY=y
# CONFIG_DNOTIFY is not set
# CONFIG_INOTIFY_USER is not set
CONFIG_AUTOFS4_FS=y
CONFIG_ISO9660_FS=y
CONFIG_PROC_KCORE=y
# CONFIG_MISC_FILESYSTEMS is not set
CONFIG_LSM="lockdown,yama,loadpin,safesetid,integrity"
CONFIG_DEBUG_INFO=y
CONFIG_FRAME_WARN=1024
CONFIG_MAGIC_SYSRQ=y
CONFIG_DEBUG_FS=y
CONFIG_DEBUG_KERNEL=y
CONFIG_DETECT_HUNG_TASK=y
# CONFIG_SCHED_DEBUG is not set
# CONFIG_RCU_TRACE is not set

By the way, the qemu command is this :

/home/ckim/ProjX/QEMU/qemu-6.2.0/build-baremetal/aarch64-softmmu/qemu-system-aarch64
-machine ab21q,gic-version=max,secure=off,virtualization=true -cpu max -kernel /home/ckim/ProjX/LinuxDevDrv/kernel-release-RD-INFRA-2020.11.30/arch/arm64/boot/Image
-m 2048M -nographic -netdev user,id=net0,tftp=/opt/tftp -device e1000,netdev=net0  -machine iommu=smmuv3 --append "root=/dev/ram
init=/init nokaslr earlycon ip=dhcp hugepages=16"

And by the -netdev and -device e1000 options, the user mode network backend is implemented in the qemu that makes us communicate with outside world. The virtual machine has the IP address 10.0.2.15. I've used this user networking mode many times before. (with full kernel default configuration, this tftp runs ok. but I wanted to reduce the kernel Image size from almost 36MB to about 6MB for fast running the test). Please see qemu network modes here : https://wiki.qemu.org/Documentation/Networking
ADD : (as requested by dirkt) I have DHCP server inside the VM (see above Networking document), my VM has static IP address. and my host too. I believe DHCP client on VM works and DHCP server runs by the qemu program (so qemu program makes the network environment for the VM). I can login to the VM and I can do debug. (but I'm doing other task today). Here is the ip addr command response.
/ # tftp -g -r axpu_ldd_kc.ko 129.254.32.30
tftp: sendto: Network is unreachable
/ # ip addr
1: lo: <LOOPBACK> mtu 65536 qdisc noop qlen 1000
    link/loopback 00:00:00:00:00:00 brd 00:00:00:00:00:00
2: sit0@NONE: <NOARP> mtu 1480 qdisc noop qlen 1000
    link/sit 0.0.0.0 brd 0.0.0.0

ADD2 : (for dirkt's comment)
I added PCI and PCIE and e1000 (Intel Etheret card) hoping this could be it. But it was not. Below is the result in the shell.
ifconfig: SIOCSIFADDR: No such device
route: SIOCADDRT: Network is unreachable
/bin/sh: can't access tty; job control turned off
/ # tftp -g -r axpu_ldd_kc.ko 129.254.32.30
tftp: sendto: Network is unreachable


text:
Q: Magento mod_rewrite redirecting page.asp?query to index.php/product/ We're moving a client from an ASP based shop, to Magento and would like to rewrite the old shop links to the new format. We're changing DNS for the domain, so links that Google has already indexed will turn up as 404 in the new shop obviously.
Format on the old shop is: page.asp?objectid=8&dataowner=webshopproduct&dataaction=showproduct&dataactionitem=1698&zcs=2
Format on the new shop is: index.php/catalog/product/view/id/0000/import-
I've tried something like:
RewriteCond %{QUERY_STRING} .showproduct.
RewriteRule ^index.php/catalog/product/view/id/0000/imported-([^/]*)$ page.asp?objectid=8&dataowner=webshopproduct&dataaction=showproduct&dataactionitem=$1&zcs=2
And variants of above, but I can't get it working.
Any ideas? Thanks

A: try following ( you can extend if you wish )
Options +FollowSymlinks
RewriteEngine On
RewriteCond %{QUERY_STRING} objectid=(.*)
RewriteRule ^grab(.*) /index.php/catalog/product/view/id/%1

Htaccess Tricks


text:
Q: How do I use file_get_contents() when the filename contains a single quote? I have to read the contents of a file with a single quote (') in the file name. I have no influence on the file name, so renaming is not an option. Unfortunately, simply escaping it doesn't work, as in:
    $myFile = 'John\\\'s file';
    $text = file_get_contents($myFile);

What would be the correct way to access this file in PHP 5 on a Linux system?

A: You don't need to double-escape your string:
$myFile = 'John\'s file'; // This works fine.
$text = file_get_contents($myFile);

I've just tried a similar command on my terminal:
php -r "chdir('te\'st');"

It works.


text:
Q: Are these both the abstract factory pattern? I think the original use of the abstract factory pattern is when you want to create a family of related objects. This is what is described in Gang of Four (GoF) and this tutorial: http://www.oodesign.com/abstract-factory-pattern.html
I keep also seeing posts that the abstract factory pattern can be used for dependency injection, particulary for injecting values that are worked out at runtime. All the uses of abstract factory pattern given here seem to be referring to this method: Why do we need Abstract factory design pattern?
Are these two actually the same pattern, implemented exactly the same, or do they both just have the same name because an abstract factory gets used in them both? Even if they are both implemented in the same way, there are other patterns that have a similar implementation (eg. state and strategy) but different names because they have different motivations, should that be the case here too since the reason for creating the abstract factory in the two cases are completely different?


text:
Q: Static object's constructor not being called I have a header file which defines two objects:
// header.h
static A object1("param1", "param2");
static A object2("param1", "param2");

This is how A looks like:
class A {
    public:
    int random;
    A(char* p1, char* p2){
        printf("Called constructor for %s | %s\n", p1, p2);
    }
};

However, the constructor is never getting called. I'm doing this:
#include "header.h"

int main(){
    // to prevent optimization issues
    object1.random = rand();
    if (object1.random != 3) { printf("\n"); }
    return 0;
}

And I never see the messages on the console, it just remains empty.
I've read about the static initialization order fiasco, but I believe it's not the problem here, because neither of those objects is relying on the other one, so order doesn't really matter...
I'm using MSVC++ 2013 on Windows 7 x64

A: When are static C++ class members initialized? contains a great answer about this topic.
In short there are 3 guarantees (citing the original Tadeusz Kopec answer in the above mentioned question):

*

*Objects defined in the same translation unit (usually it means .cpp file) are initialized in order of their definitions

*Initialization of static objects from a translation unit will be done before use of any object or function from this translation unit

*They will be initialized before main is entered.

If in your specific case static variables object1 and object2 were not initialized this could be related to a compiler optimization omitting the initialization of unused variables. You can verify this easily by adding a usage of these variables inside main and observe whether these got initialized and when.