text:
Q: LibreOffice Draw: text on a connector In LibreOffice Draw, I have some connectors connecting boxes, and I have put text on the connectors.  The connector line goes through the text.  Is there any way to have the connector line disappear around the text, so that the text looks nicer/legible?
Also, the text is in the center of the connector.  Is there any way to move the text to a different position on the connector?

A: I usually just enter the text and press return, to add an extra empty line of text below, this makes the text go right on top of the line.

A: Add Text to connector

Select and right click on connector -> click Edit Style

Click on tab "Text"

If text is required to be on TOP of connector line change Spacing to borders -> Bottom (increase the number) 0.30 works for me. You can play with these numbers and Text anchor for required result

Result should look good :)

As an alternative to this procedure:
You can as well use generic Text (F2 key) block and put text anywhere in drawing.

A: Right click on arrow and select Edit styles -> Highlighting
Pick color same as background - or any other color of choosing. This will appear as the text's background color

A: Also you can "rotate" the text, adding the tooldbar "Txt formatting" and selecting the connector text and clicking on button on the screenshot
Screenshot: toolbar button: text direction top to bottom

A: When I edit text at a connector, the "Paragraph" panel appears in the right side bar. If the text is at the horizontal part of a connector and I just click "Align Bottom" in the top right corner of the "Paragraph" panel, the text appears above the connector. I find this approach faster than in the wisemonkey's answer. Using "Align Top" to make the text appear below the line is also possible, but with some letters (e.g. "i"), the text appear touching the line for some reason, so it might be not the best option.

If the line is not horizontal, the above approach does not work. Instead, I found most easy increasing "Before Text Indent" in the same "Paragraph" panel. This moves the text to the right and away from the connector line. Having several lines of text, it is possible to Shift+Enter to insert line break, so that to have only one paragraph to format.

To rotate the text to position it along the connector line, whatever the shape of the connector line is, it is possible to use "Insert Fontwork Text" button to get the "Fontwork" dialog box. To add it to the toolbar, go "View" → "Toolbars" → "Customize", type "Fontwork" in the search box, and add the "Fontwork" ("Ефекти" with Ukrainian display language) button to a target toolbar. When editing text, click this new button (with "Insert Fontwork Text" tooltip, which is "Вставити текстовий ефект" with Ukrainian interface language) and click "Rotate" to make the text rotate along the connector line. If the text appears on the wrong side, click "Orientation". (See video.)

Working in LibreOffice 6.1.5.2.
Personally, I would prefer the part of the line under the text to disappear automatically, but maybe it is just my Visio background speaking.

A: I'm new to LibreOffice as of v7.5 (2023) and it turns out there are now TWO Fontwork commands that do very different things. "Insert Fontwork Text" is an imitation of WordArt in MS Word. It has an outline of an F for an icon. Unfortunately, perhaps in its attempt to compete with MS Word, LO makes this one much easier to find, it has its own menu item.
But the older Fontwork, as described above and in various older sources for adding label text to connectors, is still there and will align the connector label along the length and curve of the connector. It has an icon of a T inside a keystone shape. It is not findable through the menus or with the Help command. I was able to find it by searching through the All Commands in Customizing a Toolbar. The different icon was a clue. I added it to my Drawing Toolbar and discovered that it still works the same, although the dialog is layed out a little different.


text:
Q: why react native project is creating in typescript ? i want app.js I'm beginner for react native i'm creating a React Native Project using React native CLI but project is creating with app.ts i want to create project in javascript version.
i have tried react native official docs to create React native Project

A: TypeScript is a language which extends JavaScript by adding type definitions. New React Native projects target TypeScript by default, but also support JavaScript and Flow.
Files with a .jsx / .js extension are treated as JavaScript instead of TypeScript, and will not be type checked.
So you can simply use JavaScript instead of TypeScript by changing extension from .tsx/.ts to .jsx/.js and also you may remove type annotations if any is there in your JavaScript files.
Ref : Using JavaScript Instead of TypeScript

A: There was an update recently and all new React Native projects are going to be created with TypeScript by default, but they also support JavaScript.
Project files with a .jsx .js extension are treated as JavaScript instead of TypeScript, and will not be typechecked. This means, you can create projects files as .jsx or .js and your project is going to work as expected.
If you want to create project with TypeScript files, but skip the typechecking, you can add // @ts-nocheck onto the top of each TypeScript files. However, this is not advised, it just gets rid of red lines in your IDE, without checking types in the project file.

A: Unless I'm wrong, npx react-native init your-project-name creates a JS project by default.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How do I make command blocks that imitate a note block? I would like to know the command that is required and the possible combinations for the variable that changes the pitch.

A: Yes, this is possible using this command:
/playsound (sound) @a X Y Z (Volume) (pitch)

Note: Pitch has to be 0-2. 0 is the lowest pitch, and 2 is the highest. You can use decimals such as 0.2 or 1.8.
Here is a list of all the sounds in minecraft:
http://minecraft.gamepedia.com/Sounds.json
You can play custom sounds that are in resource packs in the same manner.
Sounds of Noteblocks:
note.snare
A Note Block that is on top of a "sand" block is clicked or powered by redstone.
note.pling
None
note.hat
A Note Block that is on top of a "glass" block is clicked or powered by redstone.
note.harp
A Note Block that is on top of an "other" block is clicked or powered by redstone.
note.bd
A Note Block that is on top of a "stone" block is clicked or powered by redstone.
note.bassattack
A Note Block that is on top of a "wood" block is clicked or powered by redstone.
note.bass
None

A: Yes you can the command to make a music note use /playsound (sound file name).ogg


text:
Q: Python CGI With Data Return I'm trying to accomplish the following:

*

*Pull information from a module through Python. [Accomplished]

*Constantly pull information from Python for use in HTML.

*Avoid writing the entire HTML/CSS/JS document in print statements.

I've seen the term CGI thrown around, but don't really understand how it works. Simply put, I want to run the Python script which returns an integer value. I then would like to take that integer value into JavaScript so that it may update the designated tag. It should be able to execute the Python script every two seconds, receive the output, then apply it to the page. I do not want to write out the entire HTML document in Python by doing one line at a time, as I've seen some people doing on sites I've found.
It seems like doing something like this is far more complicated than it should be. The page should run, call the script for its output, then give me the output to use.

A: Well if you don't know what CGI is and find that what you ask for is "far more complicated than it should be", you first have to learn the HTTP protocol, obviously, and that's way to broad for a SO answer.
Basically what you want requires:

*

*an html document

*some javascript code, either linked from the document or embedded into it

*a web server to serve the document (and the javascript)

*a web server (can of course be the same as the previous one) that knows how to invoke your python script and return the result as an HTTP response (you'll probably want a json content type) - this can be done with plain CGI or with a wsgi or fcgi connector, in your case CGI might well be enough.

Then in the browser your javascript code will have to issue a GET request (ajax) every x seconds to the web server hosting the Python script and update the DOM accordingly.
This is all ordinary web programming, and as I said, a basic understanding of the HTTP protocol is the starting point.

A: Trying to write anything from scratch, if you don't know anything about the subject, is always going to be complicated.
That is why there is a whole world of tools to help you. I don't think you want CGI at all; look into one of the Python micro frameworks, in particular Flask. The tutorial there should give you the introduction you need.


text:
Q: What is the meaning of the term "town hottie"? I know I heard this term several times before, but when I look it up, I can't find anything on it. Thanks in advance.

A: The generalized "town [description]" effectively means "the person who is the biggest/best [description] in their/my town". Examples:

*

*Town drunk, i.e. the person in a town who is known to be a drunkard.

*Village idiot, i.e. the biggest (well-known) idiot in the village.

Hottie simply means "an attractive person" (most commonly a woman, but not exclusively so).
"Town hottie" therefore means:

The most attractive person in their/my town.


text:
Q: How do you extract a string that is in between a char/string in C++? Let's say I have a simple string:
string example = "phone number: XXXXXXX,"

where X are random values given to me, so they are always different.
How do I extract only the X's?
 "phone number: " doesn't change.
what I have now (using Thomas Matthews technique below)
const char search_text[] = "phone number: ";
std::string::size_type start_posn = example.find(search_text);
std::string::size_type end_posn = example.find(",", start_posn);
const unsigned int length = end_posn - start_posn - sizeof(search_text) - 1;
cout << "length: " << length << endl;
std::string data = example.substr(start_posn, length);
cout << data << endl;

what if I had string example = "phone number: XXXXXXX, Date: XXXXXXXX,"?

A: Hmmm, looks like you would search for "phone number: " and then determine the index or position after the phrase.  Your requirements infer that there is a "," after the data you want.
So, you want the substring between the ": " and before the ",".  In the olden days, we would search for the "," and get its position.  The number of characters to extract is obtained by subtracting the two indices:
Edit 1
const char search_text[] = "phone number: ";
std::string::size_type start_posn = example.find(search_text);
if (start_posn != std::string::npos)
{
   start_posn += sizeof(search_text) - 1;
}
std::string::size_type end_posn   = example.find(",", start_posn);
const unsigned int length = end_posn - start_posn;
std::string data = example.substr(start_posn, length);

Note:  the above code does not handle error cases where the find method returns std::string::npos.
Using the above technique, how would you extract the data after "Date: "?


text:
Q: Get value between character using preg_match_all PHP This is my code:
$str = 'auto_load[>=]';
$result = get_value($str);

function get_value($s) {
   if (preg_match_all('/[(=|>=|<=|~|!~|~!)]/', $str, $m)) {
       //return here...
   }
}

I want it return: ">="
(accept the return value: "=", ">=", "<=", "~", "!~" or "~!")

Somebody can help me?

A: [ is a special character used to open a character class. if you want to write a literal [ you must escape it (no need to escape ], it isn't a special character even if it can be used to close a character class, the regex engine is smart enough to know when it is the case):
/\[([><]?=|~!?|!~)]/


text:
Q: Resistor for high power but low energy (pulsed operation) I need to make a pi attenuator which must support voltages of about 100 V and 20A but only on a pulse of 250ns.
But I do not know what resistor to use because it creates a power of about 2kW but only 500uJ.
All the power resistors that I see are sized according to the power and not the energy so I do not know how to choose.

A: @AndyAka got to me first on this part: this is a common issue, and many power resistors are specified for this.
What you need to do is get on the net and start slogging through resistor data sheets.  Start with power resistors, and possibly with ones that are rated for pulsed power.  You're looking for a chart in the data sheet that relates either average power to pulse time, or that gives you the energy of the allowable pulse vs. time.
Not every manufacturer will help you out with this, and it's not something that is put front and center in marketing material.  So you gotta dig.  And absolutely positively don't assume that once you choose a resistor you can just let your purchasing department buy any old resistor with the same size and power rating -- you'll need to specify that resistor.

A: A big wirewound resistor won't have any trouble handling your pulse power requirements, but it would be quite inductive, even the "non-inductive ones" and that may interfere with your short pulse duration.
You can also use a carbon composition resistor, these have huge pulse power handling capabilities, but they're not very stable or accurate.
I'll assume you need low inductance, therefore I'll go with SMD chip resistors.
Go to DigiKey, and make sure to check "Pulse withstanding" in the "features" box. Then select value, power, etc like any other resistor.
Here's an example resistor datasheet with the specs you're looking for.
Now go to page 5...

According to the text below the graph, this gives pulse power for a continuous pulse application as long as dissipated power is within spec (this is the case here). Your pulse duration is below 1µs, so one of these 2512 resistors should be enough (barely).
However, the datasheet guarantees a "permissible resistance change" of +/- 4% which may be too much for your application, especially if you're making a precision attenuator.
Solution:
1) Use higher precision resistors (I selected the cheapest).
2) Use a number of them in parallel or in series to spread voltage and power. They're cheap, if you can use 10 resistors instead of one, they'll get 10x less peak power each, so they'll have an easier time and drift less. Also, lowering the pulse power requirements opens more choices of more accurate resistors.


text:
Q: How do I stream video and play it? How can I stream video data from the network and play it on an iPhone?

A: First, are you developing a Web app optimized for iPhone or a native application ?
In the first case, your only option is to transcode your video files to Quicktime H.264 (m4v or mp4 extension). You can use Quicktime Pro (use the export menu) or VLC (as a free alternative). Then simply add a hyperlink to the video file on your HTTP server. Make sure it presents the right content-type and stuff (read Safari Web Content Guide for iPhone OS: Configuring Your Server). That'll work for web and native apps (in a native app you would use the MPMoviePlayerController view). So can "stream" (technically called progressive download of a Quicktime movie file).
If you're talking about streaming live content (i.e. content that you produce live or transcode a live feed) there is currently no official way of doing it (as of iPhone OS 2.2). iPhone OS does not support RTSP/RTP streaming. A number of native iPhone applications (such as UStream.tv and Orb Live) have created their custom live streaming solution (most of them transfer a delayed streams with many seconds of latency over HTTP then somehow decode it on the phone using FFmpeg or other libraries).

A: Are you trying to stream video in your app or just streaming on your iPhone? For streaming video through an app, use the MPMoviePlayerController and pass the URL of your video to it. The MPMoviePlayerController will itself stream the video and play it for you.

A: If you're looking for a server based solution (with a very affordable Amazon EC2 option), be sure to check out Wowza at http://www.wowzamedia.com/advanced.php
It streams directly to iPhone/iPod Touch without a custom app.
note: I'm not affiliated with them at all... just a fan/customer.
edit: Just noticed how old this question was. :)


text:
Q: New Strong Probable Prime testing method Prove that if $n$ is a strong probable to base $a$, then assuming $n$ is not a multiple $2$ or $3$:
$n$ $=$ $1$ $\mod 3$, then:
$a^{(n-1)/3}$ = $y$ $\mod n$
and
$y^3$ = $1$ $\mod n$
or
$n$ $=$ $2$ $\mod 3$, then:
$a^{(n+1)/3}$ = $y$ $\mod n$
and
$y^3$ = $a^2$ $\mod n$
and that this is true for all primes $>$ $3$.

A: Note that $\left(a^{(n-1)/3}\right)^3=a^{n-1}$ and $\left(a^{(n+1)/3}\right)^3=a^{n+1}$ and use the fact that $\gcd(a,n)=1.$


text:
Q: How to assign a state after a delay Is it possible to assign a change in state after a delay?
I am doing a traffic light controller and I want to transition from the yellow state after 4 sec
always @(next_state, EW, Count)
begin
    case (next_state)
    s0: if (EW&Count) next_state = s1; else next_state = s0;
    s1: #4 next_state = s2;
    s2: if ((~EW&~Count)|(~EW&Count)|(EW&Count)) next_state = s3; else next_state = s2;
    s3: #4 next_state = s0;

    endcase
end

A: Create two machines. Lights machine and timer.
When Lights machine enters a state, it sets its outputs connected to lights and sends delay length to timer. Timer starts counting and after given delay it sends tick to the lights machine. Then you can test lights machine quickly without waiting for a timer (when you disconnect it).
Timer is not exactly the finite automata, but it can paritally emulate it and have the same interface, so you can pass messagess between them easily.
I guess the traffic lights is only simplification of your real problem. The separation may look like a overkill for such simple problem, but it is easier to handle multiple simpler machines than one big complex machine. So if your real machine is non-trivial, separation will help.
You can also look at individual lights as separate simple machines, so they can be tested alone. And various state machine verification tools, like Uppaal, can visualize them.
You may also be interrested in Timed Automata theory.


text:
Q: Possibilities for passwords with at least one lowercase and one uppercase letter
Fred needs to choose a password for a certain website. Assume that he will choose an
  8-character password, and that the legal characters are the lowercase letters a, b, c, . . . , z, the uppercase letters A, B, C, . . . , Z, and the numbers 0, 1, . . . , 9.
  (a) How many possibilities are there if he is required to have at least one lowercase letter
  in his password?
  (b) How many possibilities are there if he is required to have at least one lowercase
  letter and at least one uppercase letter in his password?
  (c) How many possibilities are there if he is required to have at least one lowercase
  letter, at least one uppercase letter, and at least one number in his password? (Introduction to Probability, Blitzstein and Nwang, p.38)

Part a) is no problem, but I don't know how to define the events for b) and c). Any hint for defining the events to be able to use inclusion-exclusion?
EDIT1
Here is how I did part a).
The question is how many ways are there to choose a password having at least one lowercase letter.

*

*Define $A_i$ as the set of all passwords with lowercase letter at the $i^{th}$ position.

*$|A_i| = 26^1 \; 62^{8-1}$

*$|A_i \cap A_j| = 26^2 \; 62^{8-2}$

*$|\cap_{i=1}^8 A_i| = 26^i \; 62^{8-i}$

\begin{equation}
|\cup_{i=1}^8 A_i| = \sum_{i=1}^8 \binom{8}{i} 26^i \; 62^{8-i} (-1)^{i+1}
\end{equation}
I would like to solve the other parts in exactly the same manner, however, I don't know how to define my sets $A_i$ etc. in this case.
EDIT2
I try part c) with @AlexR's approach:
$|C| = |\Omega| - (|\neg U| + |\neg L| + |\neg N|) + (|\neg U \cap \neg L| + |\neg U \cap \neg N| + |\neg L \cap \neg N|) - |\neg U \cap \neg L \cap \neg N| = 62^8 - (36^8 + 36^8 + 52^8) + (10^8 + 26^8 + 26^8) - 0^8$
The probability of this to happen would be $0.7312$.

A: (b): How many passwords are there minus how many passwords are there with no uppercase or no lowercase letter?
(c): How many passwords are there minus how many passwords are there with no uppercase or no lowercase letter or no number?
Notation:
$$\Omega := \{ p\ |\ p\text{ is an } 8 \text{-digit password from the alphabet } [A-Z,a-z, 0-9]\}\\
U := \{p \in\Omega\ |\ p\text{ contains an uppercase letter}\} \\
L := \{p \in\Omega\ |\ p\text{ contains a lowercase letter}\} \\
\neg U := \Omega \setminus U = \{p\ |\ p\text{ is an } 8 \text{-digit password from the alphabet } [a-z,0-9]\} \\
\neg L := \Omega \setminus L = \{p\ |\ p\text{ is an } 8 \text{-digit password from the alphabet } [A-Z,0-9]\}$$
We trivially have
$$|\Omega| = 62^8, |\neg U| = |\neg L| = 36^8$$
Example for (a):
$$|A| = |L| = |\Omega| - |\neg L| = 62^8 - 36^8$$
Example for (b):
Now there are $36$ non-uppercase and $36$ non-lowercase characters as well as $10$ non-letters so
$$|B| = |U\cap L| = |\Omega| - |\neg U| - |\neg L| + |\neg U \cap \neg L| = 62^8 - 36^8 - 36^8 + 10^8$$
by inclusion-exclusion.
Can you do (c) now?

A: Suggestion: consider the multinomial coefficients in multi-index notation. I hope what I am doing below is correct!
a) $$\sum_{j\geq 1} {8\choose j}26^j 36^{8-j}=\underset{\alpha_1\geq 1\\|\alpha|=8}{\sum} {8\choose \alpha}26^{\alpha_1} 26^{\alpha_2}10^{\alpha_3},$$
where $\alpha\in\mathbb N_0^3$ ranges over multiindices $\alpha=(\alpha_1,\alpha_2,\alpha_3)$ with $\alpha_1\geq 1$ and $|\alpha|=\alpha_1+\alpha_2+\alpha_3=8$ by definition. Here, the counting goes as follows: there are ${8\choose \alpha}$ ways to pick $\alpha_1$ slots in which to put lowercase letters, $\alpha_2$ slots in which to put upper case letters and $\alpha_3$ slots in which to put numbers. For any single such choice, there is $26^{\alpha_1} 26^{\alpha_2}10^{\alpha_3}$ ways to put $j$ lowercase letters in the $\alpha_1$ chosen lower case slots, $\alpha_2$ upper case case letters in the chosen upper case slots and $\alpha_3$ numbers in the chosen number slots.
The sum can be evaluated by recalling that
$$\underset{|\alpha|=8\\\alpha\in \mathbb N_0^d}{\sum}{8\choose \alpha}x^{\alpha}=(x_1+\ldots+x_d)^8.$$
In particular
$$
\underset{\alpha_1\geq 1\\|\alpha|=8}{\sum} {8\choose \alpha}26^{\alpha_1} 26^{\alpha_2}10^{\alpha_3}=\underset{|\alpha|=8}{\sum} {8\choose \alpha}26^{\alpha_1} 26^{\alpha_2}10^{\alpha_3}-\underset{\alpha_1=0\\|\alpha|=8}{\sum} {8\choose \alpha} 26^{\alpha_2}10^{\alpha_3}=62^8-36^8
$$
b)
\begin{align*}\underset{\alpha_1\geq 1\\\alpha_2\geq 1\\|\alpha|=8}{\sum} {8\choose \alpha}26^{\alpha_1} 26^{\alpha_2} 10^{\alpha_3}&=-\underset{|\alpha|=8}{\sum} {8\choose \alpha}26^{\alpha_1} 26^{\alpha_2} 10^{\alpha_3}+2\underset{\alpha_1\geq 1\\|\alpha|=8}{\sum} {8\choose \alpha}26^{\alpha_1} 26^{\alpha_2} 10^{\alpha_3}\\
&\hspace{2cm}+\underset{\alpha_1=0\\\alpha_2=0\\|\alpha|=8}{\sum} {8\choose \alpha}26^{\alpha_1} 26^{\alpha_2} 10^{\alpha_3}=-62^8+2(62^8-36^8)+10^8.
\end{align*}
c) $$\underset{\alpha_1\geq 1\\\alpha_2\geq 1\\\alpha_3\geq 1\\|\alpha|=8}{\sum} {8\choose \alpha}26^{\alpha_1} 26^{\alpha_2} 10^{\alpha_3}.$$
In order to evaluate the sum, we can evoke the inclusion-exclusion principle for sums. Let $\Omega$ denote those multiindeces in $\mathbb N_0^3$ for which $|\alpha|=8$. Then we have $$\Omega=\{\alpha_1=0\}\cup \{\alpha_2=0\}\cup \{\alpha_3=0\}\cup \{\alpha_1,\alpha_2,\alpha_3\geq 1\}.$$
We have to perform the sum over elements from $\{\alpha_1,\alpha_2,\alpha_3\geq 1\}$. Accordingly, we use the analog of the inclusion-exclusion principle for sums to arrive at
$$
\sum_{|\alpha|=8}=\sum_{\alpha_1=0}+\sum_{\alpha_2=0} + \sum_{\alpha_3=0}+\sum_{\alpha_1,\alpha_2,\alpha_3\geq 1}-\sum_{\alpha_1=\alpha_2=0}-\sum_{\alpha_2=\alpha_3=0}-\sum_{\alpha_3=\alpha_1=0}+\sum_{\alpha_1=\alpha_2=\alpha_3=0}.
$$
A different approach, more akin to what we did in b), would be to use
$$
\Omega=\{\alpha_1\geq 1\}\cup \{\alpha_2\geq 1\}\cup \{\alpha_3\geq 1\}.
$$
The result is the same, but the calculations are more daunting.


text:
Q: ThumbnailUtils.createVideoThumbnail crashing despite valid file path Wasted hours on this so far so looking for some help. I've had this code working before so really stumped now. I'm checking that the file exists and it does, yet still no joy. I have
 var vidIntent = Intent(MediaStore.ACTION_VIDEO_CAPTURE)

    var g1 = UUID.randomUUID()

    var vidFileName = "$g1.mp4"
    _videoFileList.add(vidFileName)

    var videoFileDir = Environment.getExternalStoragePublicDirectory(android.os.Environment.DIRECTORY_MOVIES)

    var vidFile = File(videoFileDir, vidFileName)

    _capturedVideoPath = vidFile.absolutePath

    vidIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(vidFile))
    vidIntent.putExtra(MediaStore.EXTRA_DURATION_LIMIT, 10)

    startActivityForResult(vidIntent, 0)

And then handling the result:
if (!_capturedVideoPath.isBlank()){

        println("video captured at $_capturedVideoPath")

        if (!File(_capturedVideoPath).exists()){
            throw Exception("File at $_capturedVideoPath does not exist")
        }

        var thumbBmp : Bitmap = ThumbnailUtils.createVideoThumbnail(_capturedVideoPath, MediaStore.Video.Thumbnails.MINI_KIND)

Always results in the following crash (testing on a real device):
E/ExceptionHandler: java.lang.RuntimeException: Failure delivering result ResultInfo{who=null, request=0, result=-1, data=Intent { dat=file:///storage/emulated/0/Movies/084ea076-995f-4818-9536-4a9184167ccf.mp4 flg=0x1 (has extras) }} to activity {com.reels.videocapture/com.example.live.videocapture.ShootVideoActivity}: java.lang.IllegalStateException: ThumbnailUtils.createVid…deo.Thumbnails.MINI_KIND) must not be null
                                                                          at android.app.ActivityThread.deliverResults(ActivityThread.java:3730)
                                                                          at android.app.ActivityThread.handleSendResult(ActivityThread.java:3773)
                                                                          at android.app.ActivityThread.access$1400(ActivityThread.java:165)
                                                                          at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1418)
                                                                          at android.os.Handler.dispatchMessage(Handler.java:102)
                                                                          at android.os.Looper.loop(Looper.java:150)
                                                                          at android.app.ActivityThread.main(ActivityThread.java:5546)
                                                                          at java.lang.reflect.Method.invoke(Native Method)
                                                                          at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:792)
                                                                          at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:682)
                                                                       Caused by: java.lang.IllegalStateException: ThumbnailUtils.createVid…deo.Thumbnails.MINI_KIND) must not be null
                                                                          at com.example.live.videocapture.ShootVideoActivity.onActivityResult(ShootVideoActivity.kt:97)
                                                                          at android.app.Activity.dispatchActivityResult(Activity.java:6597)
                                                                          at android.app.ActivityThread.deliverResults(ActivityThread.java:3726)

A: For anyone else who gets here, this was permissions on SDK 23.
I had to request read permissions from external storage for this to work. Not impressed with the cryptic error message on such a mature platform!


text:
Q: How to add a reaction role function with custom emojis? Hello members of the Stack Overflow community,
I have been working on a function that activates when a moderator approves a user using Auttaja's gatekeeper. Basically, the new user gets to choose between two server emoji reactions, which will give him/her the roles. But I have been having difficulties with the role and emoji constants.
Here's my code:
 const ApprovalEmbed = new Discord.MessageEmbed()
.setColor('RED')
.setTitle('Hi there new user!')
.setDescription('Please react to this message with either one of the emojis in order to get a role.')
.addFields(
  { name: '\u200B', value: '\u200B' },
  { name: 'The Boomer emoji gives you the "Les boomers normaux" role, and the rat emoji gives you the "The normal Rat Haven dwellers" role.'},
   { name: '\u200B', value: '\u200B' },
  { name: 'Selecting the Boomer emoji will give you access to only the Boomer Haven compartment, and the rat emoji will give you access to the Rat Haven compartment. '},
  { name: '\u200B', value: '\u200B' },
  {name: 'To get access to both of these compartments, please consider using the command "^AccessToBoth" to receive the "Access to both compartments" role.'},
  )
  .setTimestamp()
  .setFooter('Time to pick a role!');
  const roleOne = guild.roles.cache.find((role) => role.name === "The normal Rat Haven dwellers")
  const roleTwo = guild.roles.cache.find((role) => role.name === "Les boomers normaux")
  const BoomerEmoji = message.guild.emojis.cache.find(emoji => emoji.name === 'boomer');
  const RatEmoji = message.guild.emojis.cache.find(emoji => emoji.name === 'robincutmoment');

client.on('message', async message => {
  let AdminRole = message.member.roles.cache.find(role => role.name === "Server Moderators")
  let RulerRole = message.member.roles.cache.find(role => role.name === "The Supreme Boomers")
  let RatRole = message.member.roles.cache.find(role => role.name === "Rat Majesty Robin")
  if (message.member.roles.cache.has(AdminRole)) {
  } else if (message.member.roles.cache.has(RulerRole)) {
  } else if (message.member.roles.cache.has(RatRole)) {}
  if (message.content === `-approve`) {
    message.channel.send(BoomerEmoji)
    const reactionMessage = await message.channel.send(ApprovalEmbed);
    message.channel.send(ApprovalEmbed).then(reactionMessage.react(BoomerEmoji), reactionMessage.react(RatEmoji))

  }
  const filter = (reaction, user) => {
      return [(BoomerEmoji), (RatEmoji)].includes(reaction.emoji.name) && user.id === message.author.id;
  };
  message.awaitReactions(filter, { max: 1, time: 60000, errors: ['time'] })
    .then(collected => {
      const reaction = collected.first();

      if (reaction.emoji.name === (BoomerEmoji)) {
        message.member.roles.add(roleOne)
      } else if (reaction.emoji.name === (RatEmoji)) {
              message.member.roles.add(roleTwo)
      }
  })

});

A: Your first problem is occurring in this snippet:
if (message.member.roles.cache.has(AdminRole)) {
 // ...
} else if (message.member.roles.cache.has(RulerRole)) {
 // ...
} else if (message.member.roles.cache.has(RatRole)) {
 // ...
}

Collection.prototype.has() checks if an element exists in the collection. It takes one parameter: the key of the element you wish to check the existence of. Since roles are mapped by snowflakes, you should be passing the role ID, not the entire object.

// `Collection.prototype.has()` is identical to `Map.prototype.has()`
// here's how it works:
const map = new Map();

// 'foo' is the key,
// 'bar' is the value
map.set('foo', 'bar');

console.log(map.has('foo')); // true
console.log(map.has('bar')); // 'bar' is not the key; false

if (message.member.roles.cache.has(AdminRole.id)) {
 // ...
} else if (message.member.roles.cache.has(RulerRole.id)) {
 // ...
} else if (message.member.roles.cache.has(RatRole.id)) {
 // ...
}

If you'd like to be fancy, you could use Collection.prototype.findKey() instead of the normal Collection.prototype.find(). This method is almost the same, except it returns the key of the found element instead of the value. Again, it makes almost no difference; just another option.
let AdminRole = message.member.roles.cache.findKey(
 (role) => role.name === 'Server Moderators'
);
let RulerRole = message.member.roles.cache.findKey(
 (role) => role.name === 'The Supreme Boomers'
);
let RatRole = message.member.roles.cache.findKey(
 (role) => role.name === 'Rat Majesty Robin'
);
if (message.member.roles.cache.has(AdminRole)) {
 // ...
} else if (message.member.roles.cache.has(RulerRole)) {
 // ...
} else if (message.member.roles.cache.has(RatRole)) {
 // ...
}

Your second problem is somewhat along the same lines. BoomerEmoji and RatEmoji are complete GuildEmoji objects. However, in this line:
return (
 [BoomerEmoji, RatEmoji].includes(reaction.emoji.name) &&
 user.id === message.author.id
);

And these lines:
if (reaction.emoji.name === BoomerEmoji) {
 message.member.roles.add(roleOne);
} else if (reaction.emoji.name === RatEmoji) {
 message.member.roles.add(roleTwo);
}

You're comparing it to the name property of another emoji. This fix is fairly simple, just clarify you only need the name properties when declaring each variable:
const BoomerEmoji = message.guild.emojis.cache.find(
 (emoji) => emoji.name === 'boomer'
).name;
const RatEmoji = message.guild.emojis.cache.find(
 (emoji) => emoji.name === 'robincutmoment'
).name;


text:
Q: how to get the modified column name in tables if we want to get the changes happened in database we will get through  sys.objects or sys.tables .but  we are only getting it table name . But how to get by table name and what the column added to that table or what column has been modified (datatype or constraint) .
for example if i added employee table column called deptid it should be shown in changes in geiven date
tablename,modified or added column

A: It seems you are looking for Change Tracking.
See http://technet.microsoft.com/en-us/library/cc280462(v=sql.105).aspx

A: As far as I know there is no supported way to do this though system views.
What you can do is to setup DDL audit triggers on the database objects you want to monitor or to try and read transaction log if database was in full recovery mode.
Audit triggers will only be helpful if you want to start auditing now while reading transcation log might give you some historical data about the changes made in the database.
Read the log file (*.LDF) in sql server 2008
How to view transaction logs in sql server 2008


text: Q: I was genereate many times the apk and his don't have a previously code changes but in emulator android, iOS an iOS fiscal device the changes show it "I was genereate many times the apk and his don't have a previously code changes but in emulator android, iOS an iOS fiscal device the changes show it. I don't know what is wrong... it seems with the native code... I did a invalidate cache, rebuild and clean proyect. I reinstalled android studio and I have still the same problem... I removed the build folder /android and /android/app too"


text:
Q: Having issue running JAVA program inside BASH script I have a bash script that look like below. All I am doing here is trying to run a java program passing in classpath and other inputs.
[guest@server1]# cat runJava
#!/bin/bash
JARS=/home/guest/lib/*
CONFIG=/home/guest/AnalyticServer.properties

echo JARS=$JARS
echo CONFIG=$CONFIG
echo "java -cp \"$JARS\" com.test.ASDataSourceClient DELETE -c \"$CONFIG\" -n test_ds"
java -cp "$JARS" com.test.ASDataSourceClient DELETE -c "$CONFIG" -n test_ds

The java program runs perfectly fine when run directly on command line/terminal. I even tested running all the commands from above script on terminal directly(one by one) and verified that java program runs fine. However, when I launch these commands via script, I am having issue. It doesn't even seem to execute echo "java -cp .." command properly.
Could anyone advice what I may be missing.
[guest@server1]# bash runJava
JARS=/home/guest/lib/*
CONFIG=/home/guest/AnalyticServer.properties
" -n test_dsaSourceClient DELETE -c "/home/guest/AnalyticServer.properties
Exception in thread "main" java.lang.NoClassDefFoundError: com/test/ASDataSourceClient
Caused by: java.lang.ClassNotFoundException: com.test.ASDataSourceClient
    at java.net.URLClassLoader$1.run(URLClassLoader.java:202)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.net.URLClassLoader.findClass(URLClassLoader.java:190)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:306)
    at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:301)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:247)
Could not find the main class: com.test.ASDataSourceClient.  Program will exit.

A: Due to the way globbing works, JARS=/home/guest/lib/* won't do what you want.
Instead, you can use either
JARS=(/home/guest/lib/*)  # Put all the jars in an array
IFS=:                     # Set the field separator to :
java -cp "${JARS[*]}" ... # Join all the array elements on the field separator

or less obscurely
JARS=""
for jar in /home/guest/lib/* # Loop through all the jar files
do
    JARS="$JARS:$jar"        # Append the jar file to the variable
done
java -cp "$JARS" ...

This will make the JARS variable contain a colon separated list of jar files.

A: It's not enough to point to the directory containing JARs. You need to name them explicitly, e.g.
JARS="/home/guest/lib/spring-beans-3.0.5.jar:anotherlibrary.jar"

A: I notice this odd line in your script output:
" -n test_dsaSourceClient DELETE -c "/home/guest/AnalyticServer.properties

That indicates $CONFIG ends with a \r character. Are you editing this script in a Windows text editor? Remove carriage returns in your script with dos2unix

A: Try this
#!/bin/bash

JARS=/home/guest/lib
CONFIG=/home/guest/AnalyticServer.properties

echo JARS=$JARS
echo CONFIG=$CONFIG

for file in `ls $JARS/*.jar`;
do
    classpath=$classpath:$file
done

cmd="java -classpath $classpath com.test.ASDataSourceClient DELETE -c $CONFIG -n test_ds"
echo $cmd
exec $cmd


text:
Q: Java - Type variable for nested parametizable type on interface I have the following interface:
public interface Box<T> {
    T get();
}

I'd like to be able to define another interface which is has Box<SomeType> as a parameter but for that interface to "know" what SomeType is.
e.g. I'd like to define the following interface
// this doesn't compile
public interface BiggerBox<B extends Box<H>> {
    H get();
}

The idea being you could do something like this:
BiggerBox<Box<String>> biggerBox = new SomeBiggerBox(new SomeBox("some string"));
String value = biggerBox.get();

The closest thing I can get to is:
public interface BiggerBox<B extends Box> {
    <U> U get();
}

But this has no compile-time type safety.
I think this is not possible in Java, but I would like to know if it is at all (even via mad hacks).
Edit: I don't want to add a second type parameter to the interface, i.e. no BiggerBox<Box<String>, String> (this is why I believe it's not possible)

A: You need to add that as a second type parameter:
public interface BiggerBox<B extends Box<H>, H> {
    H get();
}

A: There isn't anything in the BiggerBox methods that uses "B", so there's no reason to have it in the generic signature. There's also nothing in BiggerBox that forces "get" to come from the Box instance, nor anything to force a constructor to take a Box instance.
The implication is that BiggerBox should simply delegating "get" to a Box instance.
Here's an abstract class for this:
// Could also choose not to have it implement Box interface
public abstract class BiggerBox<T> implements Box<T> {

    private Box<T> box;

    public BiggerBox(Box<T> box) {
        this.box = box;
    }

    public T get() {
        return box.get();
    }
}

Or as an interface:
// Could also choose not to have it extend Box interface
public interface BiggerBox<T> extends Box<T> {

    Box<T> getBox();

    default T get() {
        return getBox().get();
    }
}


text:
Q: Key value in AWSIoTDataManager I am working with a project where I don't get it the value of
 awsiotdatamanager is static string or it generated from AWS. I found it like this in sample code Also I read code  this and this but I am getting more and more confused.
  let AWSIoTDataManager = "MyIotDataManager"
    let iotDataManager = AWSIoTDataManager(forKey: AWSIoTDataManager)

Thanks in advance :)


text:
Q: Relationship between Opportunity, OpportunityLineItems(Opportunity Product), PricebookEntry, Product2 & Pricebookentry in Salesforce? Correct me if am wrong in these relation Ship between Opportunity, OpportunityLineItems(Opportunity Product), PricebookEntry, Product2 & Pricebookentry in Salesforce.

*

*OpportunitylineItem is junction object between opportunity and pricebookentry.
As We need PricebookEntry Id and opportunity Id while creating OpportunityLineItems.

*PricebookEntry is a junction object between Product2 and PriceBook.
As we need Product2 Id and PriceBook2 Id while creating PricebookEntries.
Thanks in advance. :)

A: Opportunity Product  is a Junction Object between Opportunity and Product2 objects. The API name is OpportunityLineItem.
The relationship between Product2 and PriceBookEntry is 1:M(Master Detail) with PriceBookEntry on the child side.
The relationship between PriceBook2 and PriceBookEntry is 1:M(Master Detail) with PriceBookEntry on the child side.
So PriceBookEntry is a Junction object between Product2 and PriceBook2

A: Both points are correct, see here ERD: https://developer.salesforce.com/docs/atlas.en-us.api.meta/api/sforce_api_erd_products.htm


text:
Q: Generate a xml from a html Im trying to generate a xml from a html (url). The html website have a formulary that i want to get into a xml archive, but its too long and im searching a way to do it easier.
There is a method to generate a xml with all the fields, etc, from a html?

A: you can also use an html parser and print out the objects / array as xml
try this: http://sourceforge.net/projects/html2xml/

A: You can try the free dotnet-classlibrary SgmlReader that can load html into a xmldocument. This in turn can be saved as xml.


text:
Q: controlling options in an activity using a switch and displaying summary whether on/off I want to add an option to my preference activity similar to what is seen in chrome "home page"," save passwords " options (android app). This from my understanding launches an activity that holds a switch which controls sub options. This furthermore gives a summary indicating whether on/off. My question is how do I go about implementing some similar with regards to preference activity as I can't find examples to achieve this.
Any pointers?

A: The documentation for PreferenceActivity (http://developer.android.com/reference/android/preference/PreferenceActivity.html) has a pretty good example of usage.
Is there something more that you are looking for?

A: Use Preference:

A Preference object is the building block for a single setting. Each Preference appears as an item in a list and provides the appropriate UI for users to modify the setting. For example, a CheckBoxPreference creates a list item that shows a checkbox, and a ListPreference creates an item that opens a dialog with a list of choices.
Each Preference you add has a corresponding key-value pair that the system uses to save the setting in a default SharedPreferences file for your app's settings. When the user changes a setting, the system updates the corresponding value in the SharedPreferences file for you. The only time you should directly interact with the associated SharedPreferences file is when you need to read the value in order to determine your app's behavior based on the user's setting.
The value saved in SharedPreferences for each setting can be one of the following data types:

*

*Boolean

*Float

*Int

*Long

*String

*String Set
Because your app's settings UI is built using Preference objects instead of View objects, you need to use a specialized Activity or Fragment subclass to display the list settings:

*

*If your app supports versions of Android older than 3.0 (API level 10 and lower), you must build the activity as an extension of the PreferenceActivity class.

*On Android 3.0 and later, you should instead use a traditional Activity that hosts a PreferenceFragment that displays your app settings. However, you can also use PreferenceActivity to create a two-pane layout for large screens when you have multiple groups of settings.

An example of the XML with sub-views like you want:
<PreferenceScreen  xmlns:android="http://schemas.android.com/apk/res/android">
<!-- opens a subscreen of settings -->
<PreferenceScreen
    android:key="button_voicemail_category_key"
    android:title="@string/voicemail"
    android:persistent="false">
    <ListPreference
        android:key="button_voicemail_provider_key"
        android:title="@string/voicemail_provider" ... />
    <!-- opens another nested subscreen -->
    <PreferenceScreen
        android:key="button_voicemail_setting_key"
        android:title="@string/voicemail_settings"
        android:persistent="false">
        ...
    </PreferenceScreen>
    <RingtonePreference
        android:key="button_voicemail_ringtone_key"
        android:title="@string/voicemail_ringtone_title"
        android:ringtoneType="notification" ... />
    ...
</PreferenceScreen>
...
</PreferenceScreen>

You can find all about it in this link


text:
Q: The plugin doesn't activate in VueJS I tried to use vue-authenticate in my app, but I've some problems using the plugins' methods. This plugin has as dependency vue-resource, so the first step is installing both packages.
The in main.js file, I import and activate both packages, including the specific configuration for local authentication:
import Vue from 'vue'
import VueResource from 'vue-resource'
import VueAuthenticate from 'vue-authenticate'
// ...
Vue.use(VueResource)
Vue.use(VueAuthenticate, {
  baseUrl: 'http://sgc-server.dev',
  tokenType: 'Token'
})

Now, in my login component, named Login, create a method, called aLogin to avoid name conflicts:
// ...
methods: {
  aLogin: (_credenciales) => {
    this.$auth.login(_credenciales).then((_carga) => {
      // Ejecutamos la lógica que sigue a un login exitoso
      console.log(_carga)
    })
  }
}
// ..

In this component, credenciales is an object, defined in data() with two properties, username and password. The method aLogin is called in a form on submit event.
<form class="form" @submit.prevent="aLogin(credenciales)">

But nothing happen, and have this in the console.
Login.vue?8031:64 Uncaught TypeError: Cannot read property 'login' of undefined
    at VueComponent.aLogin (eval at <anonymous> (app.js:1987), <anonymous>:18:18)
    at Proxy.boundFn (eval at <anonymous> (app.js:735), <anonymous>:125:14)
    at submit (eval at <anonymous> (app.js:7875), <anonymous>:21:13)
    at HTMLFormElement.invoker (eval at <anonymous> (app.js:735), <anonymous>:1657:18)

Why the this.$auth is undefined if it is already registered in main.js? How can activate it properly?
Thanks in advance.

A: Do not define a method in Vue with a fat arrow function. If you do that, this does not refer to the Vue instance.
Try
methods: {
  aLogin: function(_credenciales){
    this.$auth.login(_credenciales).then((_carga) => {
      // Ejecutamos la lógica que sigue a un login exitoso
      console.log(_carga)
    })
  }
}

See VueJS: why is "this" undefined?


text:
Q: Question about covering spaces extending inverse. If $p$ is a cover map how would I be able to show that $x\rightarrow p^{-1}(x)$ extends to a functor $p^{-1}$ originating from the Fundamental Group of $X$?

A: To explain more about my comment, here is the definition of a covering morphism of groupoids  $q: H \to G$. First one defines the star  at $x \in Ob(H)$ as the set $St_H(x)$  of elements of $H$ which start at $x$.  We say $q$ is a covering morphism if each restriction of $q$ to  $St_H(x) \to St_G(qx)$ is a bijection. One then proves that if $p: X \to Y$ is a covering map of spaces then the induced morphism $q=\pi_1(p)$ of fundamental groupoids is a covering morphism. This gives the transition from topology to algebra, one aim of algebraic topology. In this algebraic setting you should find it easy to prove that an element $g: px \to py$ in $G$ induces a bijection of sets $q^{-1}(px) \to q^{-1}(py)$. See Topology and Groupoids, Chapter 10. The functoriality is also easy.


text:
Q: In ggplot 2, the text size changed when run the same code on anotehr different computer In ggplot2 , the text size of label / axis.text.x is suitable . When I run the same code as below  in another computer ,the font size is so big . How to handle it ? Thanks!

library(tidyverse)
diamonds %>% group_by(cut) %>% summarise(count= n()) %>%
  ggplot(aes(x= cut,y=count))+geom_col()+
  geom_text(vjust = -1,aes(label = count),size=8)+
  scale_y_continuous(expand=expansion(mult=c(0,0.1)))+
  theme(axis.text.x = element_text(size=16))


text:
Q: how to display information by props from an array of objects in a component in React JS I have two files, ListCurses and CardCurses, in the ListCurses a have an array of objects and I'm trying to run it and display the information in another component (CardCurses) by props, but the page returns this error message " TypeError: Cannot read property 'props' of undefined ". If anyone can help me I will be grateful, thanks !
CardCurses.jsx
import React, { Component } from "react";
import { Card } from "antd";

const { Meta } = Card;

function CardCurses() {
   return (
     <Card
        hoverable
        style={{ width: 200, height: 240, padding: "10px" }}
        cover={}
     >
        <Meta
           title={this.props.text.title}
           description={this.props.text.descricao}
        />
     </Card>
  );
}

export default CardCurses;

ListCurses
import React from "react";
import Card from "../CardCurses/CardCurses";

function ListCurses() {
   const cursos = [
    {
      title: "React JS",
      descricao: "React é legal",
      image: "https://pt-br.reactjs.org/logo-og.png"
    },
    {
      title: "React Native",
      descricao: "React Native é legal",
      image: "https://miro.medium.com/max/1000/1*GkR93AAlILkmE_3QQf88Ug.png"
    },
    {
      title: "Antd",
      descricao: "Antd é legal",
      image: "https://gw.alipayobjects.com/zos/rmsportal/KDpgvguMpGfqaHPjicRK.svg"
    }
  ];

  const returnCurses = cursos.map((curse, i) => {
  return (

        <Card text={curse} />

    );
  });
  return
{returnCurses}
;
}

export default ListCurses;

A: You haven't defined any props here:
function CardCurses() { ... }

You need:
function CardCurses(props) { ... }

Also, you are mixing function and class components. Function component have no this. So:
function CardCurses(props) {
   return (
     <Card
        hoverable
        style={{ width: 200, height: 240, padding: "10px" }}
        cover={}
     >
        <Meta
           title={props.text.title}
           description={props.text.descricao}
        />
     </Card>
  );
}

Or:
const CardCurses = ({ text }) => (
  <Card
    hoverable
    style={{ width: 200, height: 240, padding: '10px' }}
    cover={}>
    <Meta title={text.title} description={text.descricao} />
  </Card>
);

Or:
const CardCurses = ({ text: { image, title, descricao} }) => (
  <Card
    hoverable
    style={{ width: 200, height: 240, padding: '10px' }}
    cover={}>
    <Meta title={title} description={descricao} />
  </Card>
);

An unrelated note. This
() => { return whatever }

Is the same as:
() => whatever

So you could:
const returnCurses = cursos.map((curse, i) => (

    <Card text={curse} />

));

Note that index (i) is not a good key and anything but a loose linter will complain about this. If items in your array are added or removed, indices change, so the same key may refer to different items - not good.
Lastly, take cursos out the ListCurses. It's a const and doesn't change, yet you reallocate it on every render.


text:
Q: Failed to start [/bin/bash, --rcfile, /snap/pycharm-professional/127/plugins/terminal/jediterm-bash.in, -i] My Pycharm was working perfectly fine all of a sudden I see the below error message. I have pycharm professional version
Any suggestions on how to fix this issue
Cannot open Local Terminal

Failed to start [/bin/bash, --rcfile, /snap/pycharm-professional/127/plugins/terminal/jediterm-bash.in, -i] in /home/path-to-my-project

See your idea.log (Help | Show Log in Files) for the details.

A: Upon checking the log files it gave the below details. I had Ubuntu running on my host Windows Machine. Restarting both the host and the guest. resolved the issue. Reminds me of the movie. Skyscraper with Dwane Johnson
There is insufficient memory for the Java Runtime Environment to continue.
# Native memory allocation (mmap) failed to map 138412032 bytes for committing reserved memory.
# Possible reasons:
#   The system is out of physical RAM or swap space
#   The process is running with CompressedOops enabled, and the Java Heap may be blocking the growth of the native heap
# Possible solutions:
#   Reduce memory load on the system
#   Increase physical memory or swap space
#   Check if swap backing store is full
#   Decrease Java heap size (-Xmx/-Xms)
#   Decrease number of Java threads
#   Decrease Java thread stack sizes (-Xss)
#   Set larger code cache with -XX:ReservedCodeCacheSize=
# This output file may be truncated or incomplete.
#


text:
Q: c program to find sum of first 1000 prime number I want to print sum of the first 1000 prime numbers. I don't know if the following implementation is right and where it is wrong. Moreover, how can I optimize this implementation, which is required for extra off course?
#include<stdio.h>
#include<math.h>
int prime(int no,int lim)
{
    int i=2,flag=0;
    for(;i<=lim;i++)
    {
        if(no%i==0)
        {
            flag=1;
        }
    }
    return flag ;
}

int main()
{
    int i=4,count=2,j,k,l,n=4;
    double sum=5.0;

    for(;count<=1000;)
    {
        j=sqrt(i);
        k=prime(i,j);
        if(k==0)
        {
            //printf("\n%d",i);
            sum+=(double)i;
            //for(l=0;l<100000;l++);//just to reduce speed of the program

            count++;
        }
    i++;

}
printf("\n%f",sum);
        return 0;
}

A:
I don't know if the following implementation is right and where it is wrong.

The implementation is correct except for an off-by-one error: Since count is the number of primes that were already taken into account, the loop condition count<=1000 causes the loop to be run one more time when 1000 primes have already been summed, adding the 1001. prime. Correct is: count<1000.

A: To optimize your code you better use Sieve of Eratosthenes to generate prime up to your limit, then add these primes. To know how sieve works, read this article.


text:
Q: Resume next after issue on ItemAdd event I have the below macro I wrote to get Outlook to insert every email I get into my database. I am having a lot of trouble understanding how error handling is done. I think this breaks when the email is forwarded or deleted due to a rule before the macro can complete or if there is some unsupported character in it.
I know this code is a mess, but can someone please help me understand how to properly handle errors? The goal is: If there is an error on the initial email event, then insert an error message into a secondary errors table in the database. If that fails, just ignore and wait until the next email message.
   Private Sub Items_ItemAdd(ByVal Item As Object)

    Dim conn As ADODB.Connection
    Dim rs As ADODB.recordset
    Dim SQL As String

    Dim emailSubject, fromSender, senderEmail, emailBody, toList, ccList As String
    Dim dateString, timeString As String
    Dim emailReceivedTime As String
    Dim doubleQuotes As String
    doubleQuotes = Chr(34)

    On Error GoTo ErrorHandler

    Set conn = New ADODB.Connection
    With conn
        .ConnectionString = "Provider=SQLOLEDB; Data Source = 0.0.0.0; Initial Catalog = Database; User Id = user; Password= pw;"
        .Open
    End With

    Dim Msg As Outlook.MailItem

    On Error GoTo ErrorHandler
    If TypeName(Item) = "MailItem" Then
        On Error GoTo ErrorHandler
        Set Msg = Item

        toList = CStr(Msg.To)
        fromSender = CStr(Msg.Sender)
        senderEmail = CStr(Msg.SenderEmailAddress)
        emailSubject = CStr(Msg.Subject)
        emailReceivedTime = CStr(Msg.ReceivedTime)
        emailBody = CStr(Msg.Body)

        Dim cleanedSubject, cleanedBody As String

        cleanedSubject = Replace(emailSubject, "'", " ") 'remove any single quotes because it will break the sql query
        cleanedSubject = Replace(cleanedSubject, doubleQuotes, " ") 'remove double quotes because it will break the vb code below
        cleanedBody = Replace(emailBody, "'", " ")
        cleanedBody = Replace(cleanedBody, doubleQuotes, " ")

        SQL = "INSERT INTO outlook_emails (to_recipients, cc, sender, sender_address, subject_line, body, received_date, received_time) " +
          "SELECT '" + Replace(toList, "'", " ") + "'," +
          "'" + Replace(ccList, "'", " ") + "'," +
          "'" + Replace(fromSender, "'", " ") + "'," +
          "'" + senderEmail + "'," +
          "'" + cleanedSubject + "'," +
          "'" + cleanedBody + "'," +
          "'" + emailReceivedTime + "'," +
          "'" + emailReceivedTime + "'"

    Set rs = conn.Execute(SQL)
End If

ProgramExit:
        Exit Sub
        conn.Close
ErrorHandler:
    'MsgBox Err.Number & " - " & Err.Description
    Dim conn2 As ADODB.Connection
    Dim rs2 As ADODB.recordset
    Dim SQLCode As String

    On Error Resume Next
    If TypeName(Item) = "MailItem" Then
        Set Msg = Item

        toList = Msg.To
        fromSender = Msg.Sender
        senderEmail = Msg.SenderEmailAddress
        emailSubject = Msg.Subject
        emailReceivedTime = Msg.ReceivedTime
        emailBody = Msg.Body

        cleanedSubject = Replace(emailSubject, "'", " ") 'remove any single quotes because it will break the sql query
        cleanedSubject = Replace(cleanedSubject, doubleQuotes, " ") 'remove double quotes because it will break the vb code below
        cleanedBody = Replace(emailBody, "'", " ")
        cleanedBody = Replace(cleanedBody, doubleQuotes, " ")
    End If

    Set conn2 = New ADODB.Connection
    With conn2
        .ConnectionString = "Provider=SQLOLEDB; Data Source = 0.0.0.0; Initial Catalog = Database; User Id = user; Password= pw;"
        .Open
    End With

    Dim myDate As String
    Dim myTime As String

    myDate = Date
    myTime = Time

    SQLCode = "INSERT INTO error_log (my_date, my_time, hostname, app, error, priority_type) " +
      "SELECT '" + myDate + "'," +
      "'" + myTime + "'," +
      "'" + Environ$("computername") + "'," +
      "'Outlook'," +
      "'" + Err.Description + " - SUBJECT: " + cleanedSubject + "'," +
      "'Low'," +
      "'Outlook Macro Error'"

    On Error Resume Next
    Set rs2 = conn2.Execute(SQLCode)

End Sub

A: Do your utmost to avoid On Error Resume Next in all situations.
It should be used on as few lines as possible for expected errors. Zero lines is usually best.
https://stackoverflow.com/a/31753321/1571407
How To:
https://stackoverflow.com/a/59550602/1571407
You have to turn the first error handler off before the second can start.
https://stackoverflow.com/a/30994055/1571407
Option Explicit

Private Sub test()
    Items_ItemAdd ActiveInspector.CurrentItem
End Sub

Private Sub Items_ItemAdd(ByVal Item As Object)

    Dim conn As ADODB.Connection
    Dim rs As ADODB.Recordset
    Dim SQL As String

    Dim emailSubject As String
    Dim fromSender As String
    Dim senderEmail As String
    Dim emailBody As String
    Dim toList As String
    Dim ccList As String

    Dim dateString As String
    Dim timeString As String
    Dim emailReceivedTime As String

    Dim doubleQuotes As String
    doubleQuotes = Chr(34)

    On Error GoTo ErrorHandler

    ' Comment to see a better example
    err.Raise 1     ' Application-defined or object-defined error

    If TypeName(Item) = "MailItem" Then

        Set conn = New ADODB.Connection

        With conn
            ' -2147467259 - [DBNETLIB][ConnectionOpen (Connect()).]SQL Server does not exist or access denied.
            '.ConnectionString = "Provider=SQLOLEDB; Data Source = 0.0.0.0; Initial Catalog = Database; User Id = user; Password= pw;"

            ' -2147467259 - [Microsoft][ODBC Driver Manager] Data source name not found and no default driver specified
            .Open
        End With

        Dim Msg As Outlook.MailItem
        Set Msg = Item

        toList = CStr(Msg.To)
        fromSender = CStr(Msg.Sender)
        senderEmail = CStr(Msg.SenderEmailAddress)
        emailSubject = CStr(Msg.Subject)
        emailReceivedTime = CStr(Msg.ReceivedTime)
        emailBody = CStr(Msg.Body)

        Dim cleanedSubject As String
        Dim cleanedBody As String

        cleanedSubject = Replace(emailSubject, "'", " ") 'remove any single quotes because it will break the sql query
        cleanedSubject = Replace(cleanedSubject, doubleQuotes, " ") 'remove double quotes because it will break the vb code below
        cleanedBody = Replace(emailBody, "'", " ")
        cleanedBody = Replace(cleanedBody, doubleQuotes, " ")

        'SQL = ...
        'Set rs = conn.Execute(SQL)

        conn.Close

    End If

ProgramExit:
    Exit Sub

ErrorHandler:
    Debug.Print "Error updating database."
    Debug.Print " Error number " & err.Number & " - " & err.Description

    'Normally
    ' Resume ProgramExit
    ' End Sub

    'Normally this would be in ProgramExit
    If Not conn Is Nothing Then
        If conn.State = 1 Then conn.Close
    End If

    'Turn off the first error handler
    ' https://stackoverflow.com/a/30994055/1571407
    Resume databaseErrorTable

databaseErrorTable:

    Dim conn2 As ADODB.Connection
    Dim rs2 As ADODB.Recordset
    Dim SQLCode As String

    ' Abandon subsequent invalid processing
    On Error GoTo ErrorHandler2

    ' If OERN
    ' - inefficient at best
    ' - hidden errors with mysterious results at worst

    ' Comment to see a better example
    err.Raise 3     ' Return without GoSub

    If TypeName(Item) = "MailItem" Then

        Set conn2 = New ADODB.Connection

        With conn2
            '.ConnectionString = "Provider=SQLOLEDB; Data Source = 0.0.0.0; Initial Catalog = Database; User Id = user; Password= pw;"
            .Open
        End With

        Set Msg = Item

        toList = Msg.To
        fromSender = Msg.Sender
        senderEmail = Msg.SenderEmailAddress
        emailSubject = Msg.Subject
        emailReceivedTime = Msg.ReceivedTime
        emailBody = Msg.Body

        cleanedSubject = Replace(emailSubject, "'", " ") 'remove any single quotes because it will break the sql query
        cleanedSubject = Replace(cleanedSubject, doubleQuotes, " ") 'remove double quotes because it will break the vb code below
        cleanedBody = Replace(emailBody, "'", " ")
        cleanedBody = Replace(cleanedBody, doubleQuotes, " ")

        Dim myDate As String
        Dim myTime As String

        myDate = Date
        myTime = Time

        'SQLCode = ...
        'Set rs2 = conn2.Execute(SQLCode)

        conn2.Close

    End If

    Exit Sub

ErrorHandler2:
    Debug.Print "Error updating database error table."
    Debug.Print " Error number " & err.Number & " - " & err.Description

    If Not conn2 Is Nothing Then
        If conn2.State = 1 Then conn2.Close
    End If

End Sub


text:
Q: Botframework - Proactive - UnauthorizedAccessException on cold call I have a custom WebApi controller hosted next to my normal bot MessagesController. This custom Controller gets call so often to perform proactive messaging to users for sending out notifications.
public bool Post([FromBody]SchedulerTrigger triggerInfo)
{
    try
    {
        //Initiate background processing of notifications
        Task.Run(() => NotificationTask.NotificationProcessing(triggerInfo));

    }
    catch (Exception ex)
    {

        throw ex;
    }

    return true;
}

The controller does not have the [BotAuthentication] attribute and should not since it is being called from elsewhere.
The NotificationProcessing function does some crunching but in the end it calls a Dialog:
public static async Task Resume(string resumptionCookie)
{
        //Deserialize reference to conversation
        ConversationReference conversationReference = JsonConvert.DeserializeObject<ConversationReference>(resumptionCookie);

        using (var scope = DialogModule.BeginLifetimeScope(Conversation.Container, message))
        {
            var botData = scope.Resolve<IBotData>();

            await botData.LoadAsync(CancellationToken.None);

            //This is our dialog stack
            var task = scope.Resolve<IDialogTask>();

            //interrupt the stack. This means that we're stopping whatever conversation that is currently happening with the user
            //Then adding this stack to run and once it's finished, we will be back to the original conversation
            var dialog = new MyProActiveDialog();

            try
            {
                task.Call(dialog.Void<object, IMessageActivity>(), null);
                await task.PollAsync(CancellationToken.None);
            }
            catch (Exception ex)
            {
                //TODO
            }
            finally
            {
                //flush dialog stack
                await botData.FlushAsync(CancellationToken.None);
            }

        }
}

All works well when the Web Service is up and running and has at least performed once login with https://login.microsoftonline.com/common/oauth2/v2.0/token after any type of chit chat between microsoft bot and my webservice.
However, if I restart my webservice and kick-off the pro-active discussion I get UnauthorizedAccessException.
I tried to perform manual authentication with BotAuthenticator or adding [BotAuthentication] with a passed token but I always endup with  UnauthorizedAccessException.
So I noticed that the Beerer is only present on a none cold start. I found no way to force authentication on cold start...
Image of Fiddler Web Service --> To Bot
Any type of help would be appreciate.

A: I have encountered this error before.  Essentially, the channel that the message is coming from is "trusted".  The workaround is to trust that channel access.
Try this (first parameter should be the service url):
MicrosoftAppCredentials.TrustServiceUrl(@"https://skype.botframework.com", DateTime.MaxValue);


text:
Q: How to change the color of clusters using R? I am using the R for Kmeans Clustering, so I load the library (fpc), and using plotcluster method to plot the data.
clus <- kmeans(data, centers = 5)
plotcluster(data, clus$cluster, pch = clus$cluster)

So 5 groups of particles are plotted, but with default colors for different groups. But how can I change the colors of the particles?
For example, group 1 to some particular color and group 2 to some particular color.
There is a parameter called "col" in the plotcluster function, but I don't know how to change it.

A: A bit late but hey. I had this issue today and found this solution.
clus <- kmeans(x, centers=5)
vcol <- c("blue","green","purple","red","yellow")
plotcluster(x, clus$cluster, col=vcol[clus$cluster])

NB :
If length(vcol) - centers = 1, last color won't be used.
If centers - length(vcol) = 1, points in last cluster won't display.

A: Here is the code that I tested on RStudio running on a Mac OS X 10.10.2 with the latest installation of the fpc package.
By no means am I suggesting you use these colors, but if you add the following two parameters I think you will be able to select the colors you want:

vector of class numbers which can be coerced into integers; length must equal nrow(xd)

clvecd = c(1,2,3,4,5)

vector of colors that correspond to your clusters

col=c("blue","green","purple","red","yellow")
plotcluster(  data
            , clus$cluster
            , pch = clus$cluster
            , clvecd=c(1,2,3,4,5)
            , col=c("blue","green","purple","red","yellow"))


text:
Q: Create/merge an object hashmap from two arrays I'm working on a project that requires me to create a hashmap, it's my first one and after researching I am stuck. I need to create the map from two arrays.
Array 1:
var arrayOne = [ "board", "admin" ]

These would be added to a map Object with a default value of false, I can get to this part:
var myMap = {
    board: false,
    admin: false
}

Array 2:
var arrayTwo = [ "board" ]

Only 'board' exists here, so I want to turn the value to 'true'. I'm stuck on where to go next so I end up with:
var myMap = {
    board: true,
    admin: false
}

Here's my script so far:
var myMap = {};
var arrayOne = [ "board", "admin" ];
for (var i = 0; i < arrayOne.length; i++) {
    var a = arrayOne[i];
    myMap[a] = false; // sets default value
}

Any help to do the 'next bit' to merge the two is greatly appreciated, thank you.

A: I think you should continue with the following:
for (var i = 0; i < arrayTwo.length; i++) {
    if (arrayTwo[i] in myMap)
        myMap[arrayTwo[i]] = true;
}

... setting properties to true only if they exist in the map.

A: Use indexOf() method to check if the item is in second array or not
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/indexOf
http://www.w3schools.com/jsref/jsref_indexof_array.asp
var myMap = {};
var arrayOne = [ "board", "admin" ];
for (var i = 0; i < arrayOne.length; i++) {
    var a = arrayOne[i];
    myMap[a] = false; // sets default value
    if ( arrayTwo.indexOf( a ) != -1 )
    {
        myMap[a] = true;
    }
}

A: Just do one then the other...
var i;
var myMap = {};
var arrayOne = [ "board", "admin" ];

for (i = 0; i < arrayOne.length; i++) {
     myMap[arrayOne[i]] = false;
}

var arrayTwo = [ "board" ];

for (i = 0; i < arrayTwo.length; i++) {
     myMap[arrayTwo[i]] = true;
}

A: ES5 version
arrayOne.forEach(function(item){
    myMap[item] = false;
});
arrayTwo.forEach(function(item){
    (item in myMap) && (myMap[item] = true);
});


text:
Q: Use backup restore then attach in Sharepoint 2007 to 2010 migration The microsoft technet article for using the detach/attach method for migrating from Sharepoint 2007 to 2010 is here, http://technet.microsoft.com/en-us/library/cc263299.aspx.
However, I would like to know if it would be possible to not "detach" the original database from Sharepoint 2007 and leave the Sharepoint 2007 system operational. Instead is it possible to do the following procedure?

*

*Backup the Sharepoint 2007 DB.

*Install Sharepoint 2010 on new separate Windows Server 2008 R2 with SQL Server 2008.

*Restore the DB on separate Windows Server 2008 R2 VM with SQL Server 2008.

*Attach content database to new Sharepoint 2010 system via powershell commands.

I.e. I want to leave the existing sharepoint site live without having to bring it down and then create a new sharepoint site on a separate system using the same content. Is this possible?

A: This is possible.  That was our process for a recent upgrade to 2010  Be sure to run all pre-upgarde checks and correct any issues before the upgrade. Pay close attention to any added solutions on the 2007 farm.

A: AS the proposed answer you can do that but it is not advicable to keep the production live as you might lost the data between the backup and making 2010 site live.
1.make 2007 farm readonly from Central admin_contentdatabases_Readonly checked.
2. Backup of Content DB.
3. Attach Content DB via powershell.
4. Update DNS to the new 2010 site.
5.Done!!
http://sharepoint2010blog.blogspot.com/2010/01/how-to-upgrade-to-sharepoint-2010-using.html


text:
Q: Finding the joint p.f. I have two questions here that, I believe, revolves around the same topic.
1) Suppose there are 10 red balls, 9 yellow balls, and 6 blue balls. Five balls are selected at random without replacement.
Let $X$ be the number of red balls selected and $Y$ be the number of yellow balls selected. What is the joint p.f. of $X$ and $Y$?
I am not sure how to start this question. I know it's hypergeometric distribution. but the question require to find the p.f. of the "number of red/yellow balls" throws me off.
2) The Hardy-Weinberg law of genetics states that, under certain conditions,
the relative frequencies with which three genotypes $AA$, $Aa$ and $aa$ occur
in the population will be $θ^2$, $2θ(1 − θ)$ and $(1 − θ)^2$ respectively where
$0 < θ < 1$. Suppose $n$ members of the population are selected at random.
Let $X$ be the number of $AA$ types selected and let $Y$ be the number of
$Aa$ types selected.
I feel the two questions are similar in nature and our variables are defined as the "number of ..." throws me off and I am not sure how to tackle these.


text:
Q: Adding arbitary data in Jquery using .data() I was trying add arbitrary data while doing this I got following doubts in my mind:

*

*How much data I can add, is there any limit?

*Does it affect in anyway to performance/execution Speed?

*And what about safety of data, is it safe?

*Where does these get stored?

A: Since you haven't provided any real or example markup with the attributes you've thought to use, let's just talk briefly about HTML5's data--prefixed attributes: What are they, why are they there, and what they're not. This should go a long way to clear up your anxiety.
First, what are they? The W3C specification is clear:
3.2.3.9 Embedding custom non-visible data with the data-* attributes

... an attribute in no namespace whose name starts with the string "data-" ... intended to store custom data ... for which there are no more appropriate attributes or elements.

You might notice it's also emphatically stated what they are not meant to do. Before we get to that, and what mechanism is designed for their appropriate implementation, let's step back briefly and consider what was before data- came to be.

If you're familiar with HTML, you know there are defined core (global) attributes (id, class, etc.) all elements inherit. There are attributes that float amongst groups for different reasons (src, accesskey?, etc.). There are specialized event attributes, some fairly specific or deprecated or otherwise oddball attributes.
There are even microsyntaxes and microformats. Let's focus here, though; the former is about expressive attribute syntax (<input type="email" required ...), the latter is prohibitively not inclusive of data- attributes (due to rules of structured attribute specificity).
You should get the idea somebody, at length, thought this stuff through. All the above has everything to do with the way this marked-up content is described purposefully (and if possible semantically) to the browser. It's not willy-nilly it exists as it does. Neither is it set in stone (HTML5 is now living), nor equivalent to that XML namespace-free hooliganism XHTML-doctype'd webpages purport to be.
If you've never thumbed through one, go through the HTML5 spec. It's interesting, once you get the hang of reading it's stilted and wobbly unhuman diction.

Making our way back, we're now gifted this oddball data-* syntax, plus a clumsily executed prose depicting some dataset and scripting beast that's going to make it all wonderful.
And so you think (naturally) what is this for and what can I do with it? Good question.
There's two answers, what you should do, and what you should avoid at all cost. The former will have you frolicking in a daisy-lined fragrant garden of awesomeness; the latter, Beelzebub himself may seek your very soul. (Or at least wonder what you're up to.)
What you should do is use data- to address those situations where you need to associate data of some sort to an element or elements on the page. Not willy-nilly; don't be tempted by the barbeque flames of hell. When you need that data and you find yourself possibly resorting to something like:
var = '<?=json_encode($restaurants)?>'; // This is so sad, really.

Or, God help us:
<a id="client-005" rel="200907,$5000;200908:$3500;oh,why" ...

Get it? Sales data for the "client" in that element (we think... hope...). Asynchronously grabbing data has obviated some of the need for these eccentric approaches. Also, some clever folks figured out you could:


text:
Q: GROUP BY and COUNT using ActiveRecord Refering to this:
Is there any difference between GROUP BY and DISTINCT
Given a table that looks like this:

name
------
barry
dave
bill
dave
dave
barry
john
This query:

SELECT name, count(*) AS count FROM table GROUP BY name;
Will produce output like this:

name    count
-------------
barry   2
dave    3
bill    1
john    1

What is the correct Rails convention here for ActiveModel to perform a GROUP BY with COUNT?

A: Note that the accepted answer will return a hash:
Tagging.joins(:tag).group(:name).size
   (0.4ms)  SELECT COUNT(*) AS count_all, `name` AS name FROM `taggings` INNER JOIN `tags` ON `tags`.`id` = `taggings`.`tag_id` GROUP BY `name`
 => {"applesauce"=>1, "oranges"=>2}

But what if you want to return the count plus some columns from different tables in a join. Then you also need to use the select ActiveRecord query:
collection = Tagging.select('COUNT(*) as total, taggings.taggable_id, taggings.taggable_type').joins(:tag).where(taggable_type: 'LineItem', taggable_id: ['5cad0dcc3ed1496086000031', '5cad0dcd3ed1496086000081'] ).group(:name)

collection.each do |item|
  puts item.taggable_id
  puts item.total
end

5cad0dcc3ed1496086000031
1
5cad0dcc3ed1496086000031
2

With this second approach, you can fetch additional details about a join relationship without any additional queries or loop constructs.

A: another option:
Person.select(:name, 'COUNT(name)').group(:name)

this generate an array of people with attribute count

A: Distinct and Group By are going to give you different results. To get the results you expect you'll want to use
Person.group(:name).count
(1.2ms)  SELECT COUNT(*) AS count_all, name AS name FROM "people" GROUP BY "people"."name"
=> {"Dan"=>3, "Dave"=>2, "Vic"=>1}

Seen above, group will return things as a hash. While distinct just returns the number of people in total, seen below.
Person.distinct(:name).count
(0.4ms)  SELECT DISTINCT COUNT(DISTINCT "people"."id") FROM "people"
=> 6

A: Another option:
Person.select(:name).distinct(:name).count


text:
Q: Polymer Event Target if i add a tap-event-listener to an instance of a polymer component with some elements in its local dom, the target (and source) of the event can be a element of the local dom.
What is the best way to get always a reference to the host element and not any of its children in the local dom?
Example: component with local dom
<dom-module id="x-foo">
  <template>

Foo

  </template>

</dom-module>

Use component and add a listener
<x-foo on-tap="_onTap">
...
_onTap: function(e) {
   // here i need a reference to the element
   // that listens to the tap (host / x-foo)
   // but if i tap on the img, the target is a
   // reference to the img element
}

Thank you
Greets,
Meisenmann

A: You can try to use
e.currentTarget

instead of
e.target

as described here
You can see in the description that it "Identifies the current target for the event, as the event traverses the DOM. It always refers to the element to which the event handler has been attached, as opposed to event.target which identifies the element on which the event occurred."

A: As suggested by Mishu in his comments about e.currentTarget, however there is another important point to note is that if you wish to know how many places your events has traversed from, check composedPath() this method keeps track of all the places your event has traversed through !


text:
Q: crystal report with sub reports not working on production/test machine C# winforms I have created crystal report with 8 sub-reports (using VS 2010). I have created stored proc which populates all the dump SQL server tables which are linked to main report & sub reports.  My code is working fine on development machine but when same is deployed to another machine it throws following error.
Failed to Open the connection.
Details : [Database vendor code 17]
Failed to Open the connection.
rpt_reportName{GUID}.rpt
Details : [Database vendor code 17]
following is my code to generate report.
ReportDocument crReportDocument;
        Boolean TypesDSReports = false;
        clsErrorLog oLog = new clsErrorLog();

        static TableLogOnInfo crTableLogonInfo;
        static ConnectionInfo crConnectionInfo;
        static Tables crTables;
        static Database crDatabase;
 public static void ReportLogin(ReportDocument crDoc, string Server, string Database, string UserID, string Password)
        {
            crConnectionInfo = new ConnectionInfo();
            crConnectionInfo.ServerName = Server;
            crConnectionInfo.DatabaseName = Database;
            crConnectionInfo.UserID = UserID;
            crConnectionInfo.Password = Password;
            crDatabase = crDoc.Database;
            crTables = crDatabase.Tables;
            foreach (CrystalDecisions.CrystalReports.Engine.Table crTable in crTables)
            {
                crTableLogonInfo = crTable.LogOnInfo;
                crTableLogonInfo.ConnectionInfo = crConnectionInfo;
                crTable.ApplyLogOnInfo(crTableLogonInfo);
            }

            //crDoc.Subreports["aa"].co = crConnectionInfo;

        }

private void DisplayReportWithSubReport()
        {
            try
            {
                ReportDocument crReportDocument = new ReportDocument();
                crReportDocument.Load(sReportPath.Trim());

                ReportLogin(crReportDocument, clsCustomize.gsPropServerName, clsCustomize.gsPropCurrentDataBaseName, clsCustomize.gsPropDataBaseUserID, clsCustomize.gsPropDataBasePassword);
                crReportDocument.Refresh();
                CRViewer.ReportSource = crReportDocument;
                CRViewer.RefreshReport();
                this.Text = sDisplayReportCaption;

                if (TypesDSReports == false)
                {
                    crReportDocument.PrintOptions.PaperSize = CrystalDecisions.Shared.PaperSize.PaperA4;
                }
                this.WindowState = FormWindowState.Maximized;

                if (HMS.Common.clsConstants.gbPropCloseReportForm == true)
                {

                    crReportDocument.PrintOptions.PaperSize = CrystalDecisions.Shared.PaperSize.PaperA4;
                    if (HMS.clsCustomize.giNoOfPrintCopies == 0)
                    {
                        HMS.clsCustomize.giNoOfPrintCopies = 1;
                    }

                    crReportDocument.PrintToPrinter(HMS.clsCustomize.giNoOfPrintCopies, false, 1, 1);
                    HMS.Common.clsConstants.gbPropCloseReportForm = false; //Reset the Flag
                    this.Close();
                }
                else
                {
                    this.WindowState = FormWindowState.Maximized;
                }
            }
            catch (Exception ex)
            {
                oLog.LogError(ex, "", "", "", "");
            }

        }

Dev machine and target machine both have same system configuration.Kindly help where is the issue?
Regards,
Vikram

A: I'm not 100% on this but I'm pretty sure that it's not enough to set the connection info at the top level only. You need to loop through your subreports / tables and apply the logonInfo to each
crDoc.Subreports[x].Database.Tables[y].ApplyLogOnInfo(crTableLogonInfo) ...

A: I figured out solution myself. I added following code in the ReportLogin method and it worked perfectly.
 for (int i = 0; i < crDoc.Subreports.Count; i++)
                {
                    crDoc.Subreports[i].SetDatabaseLogon(UserID, Password, Server, Database);
                }


text:
Q: influence of array pointer When we have:
#include <iostream>
using namespace std;

int main()
{
    int a[100];
    cout << a[0] << endl;
}

I get "1".
But when I change it like this:
#include <iostream>
using namespace std;

int main()
{
    int a[100];
    int* b = &a[0];
    cout << a[0] << endl;
    cout << *b << endl;
}

I get something like "-1219451320", which changes after each run.
What was the influence of b variable so a[0] got changed? For example now, If I change it to previous code, the result will be "1" again.
in both of the states, the array was not initialized! so there shouldn't be difference like this. for example in the first code, if we got "-12242311231", it wouldn't be strange but now ...

A: You have not initialized the array, so the values are (or can be) arbitrary.
The standard calls them indeterminate values.
With two different programs, which you have, you can expect to get two different values, or the same value, with no discernible pattern or reason (it's arbitrary). You can even get different values from two runs of the same program. To initialize, just write
int a[100] = {};  // All zeroes. :-)

Instead of raw arrays, consider using std::vector, e.g.
#include <vector>

// ...
std::vector<int> a( 100 );    // All zeroes

It initializes automatically and always.
And it can also be resized.


text:
Q: Apache httpd: How to enable OCSP stapling with mod_md? I want to enable OCSP stapling with mod_md on my Debian 10 server with Apache httpd. I have enabled the module, and the command MDomain example.org is understood, but the example
<MDomain mydomain.net>
  MDStapling on
</MDomain>

yields an error "Invalid command '<MDomain', perhaps misspelled or defined by a module not included..." when starting apache2. And if I just keep MDStapling on, I get an error "Invalid command 'MDStapling', perhaps misspelled or defined by a module not included...".
If do not enable the mod_md module, I get an error on the command MDomain example.org. Thus the fact that command is understood shows that this module has been loaded.
Note: the suggestion to use mod_md comes from this comment of Apache bug 57121.

A: It seems that in older versions of mod_md you have to use: <MDomainSet> if you make it a container directive. OCSP stapling however only made its appearance in mod_md version 2.1.0 and can only be used with mod_ssl from Apache 2.4.41 and higher.
Apache 2.4.30 upstream included mod_md 1.1.8 in the base build.
Current Buster stable Apache is derived from 2.4.38 and should contain mod_md 1.1.17. But that is only fit for ACME v1 protocol, so even if you can get it to work, it would be useless when Letsencrypt stops handling ACME v1 domain validations in june of 2020. Already you can't use it for registering new accounts.
Apache 2.4.41 included a preparing change for callbacks in mod_ssl that would allow OCSP stapling from other providers like mod_md. But mod_md was included still in version 2.0.8 which was the best available version at the moment. This version is available in buster-backports, although I don't know if that build enabled this module. It wouldn't support OCSP stapling however. https://packages.debian.org/buster-backports/apache2-bin
Current versions of mod_md:
https://github.com/icing/mod_md
Please also upvote this bug if you can, I have voted for it also and for the one you referred:
https://bz.apache.org/bugzilla/show_bug.cgi?id=60182


text:
Q: Make the right input for json file I try to use this command from this project
python create_text_folder.py -i Apache -o output_dir

I use as input this json data in the file mailcorpus.json
[
   {
      "id":12,
      "mailing_list_url":"12",
      "type_of_recipient":"before",
      "email_address":"test@test.org",
      "message_body":"Here is one text to test sentiment and feel happy",
      "is_response_of":"before"
   },
   {
      "id":21,
      "mailing_list_url":"21",
      "type_of_recipient":"before",
      "email_address":"test@gmail.com",
      "message_body":"Here is one text to test sentiment and feel happy and feel fine",
      "is_response_of":"before"
   },
   {
      "id":21,
      "mailing_list_url":"21",
      "type_of_recipient":"after",
      "email_address":"test@gmail.com",
      "message_body":"Not feel so good for this code",
      "is_response_of":"after"
   }
]

The first part of the command is this code
import rpy2.robjects as robjects
from bs4 import BeautifulSoup as BS4
from rpy2.robjects.packages import importr
import json
from email_reply_parser import EmailReplyParser

'''
NLoN training
'''
def training_nlon():
    nlon = importr('NLoN')
    #Path to NLoN training data
    robjects.r['load']('data/training_data.rda')

    return nlon, nlon.NLoNModel(robjects.r['text'], robjects.r['rater'])
'''
Gets mail corpus from email addresses
'''
def get_mail_corpus(nlon_cleaning=False):
    if (nlon_cleaning):
        nlon, nlon_model = training_nlon()

    #Path to mail's corpus
    corpus_file = 'data/mailcorpus.json'
    with open(corpus_file) as data_file:
        corpus = json.load(data_file)

    print('Reading and cleaning emails corpus. Number of emails: ' + str(len(corpus)))
    dict = {}
    n = 0
    #Text cleaning
    for d in corpus:
        if d['type_of_recipient'] == 'From':
            # if not d['is_response_of'] == None:
            res = EmailReplyParser.read(d['message_body'].replace('\\n', '\n'))
            text = res.reply
            # else:
            #     text = d['message_body'].replace('\\n', '\n')
            n += 1

            if (nlon_cleaning):
                try:
                    soup = BS4(text, 'html.parser')
                    clean_message_body = soup.text
                except Exception as e:
                    print('Error with BS4 on text:\n\n%s\n\n' % text, str(e))
                    clean_message_body = text.strip()
                message_by_lines = text.splitlines()
                list_length = len(message_by_lines)
                index = 0
                for count in range(0, list_length):
                    text1 = robjects.StrVector([message_by_lines[index]])
                    if nlon.NLoNPredict(nlon_model, text1)[0] == 'Not':
                        del message_by_lines[index]
                    else:
                        index = index + 1
                clean_message_body = '\n'.join(message_by_lines)
                text = clean_message_body

            if not text == '':
                if d['email_address'] in dict:
                    dict[d['email_address']].append(text)
                else:
                    dict[d['email_address']] = [text]
        print(str(n)+'/'+str(len(corpus))+'\n' if n%50==0 else '', end='')

    print('Mails retrieved: '+ str(n))
    print('Email addresses: '+ str(len(dict)))
    return dict

It is available from github repository link I don't own it.
And the second part is the following code:
import MailCorpus as mc
import sys, getopt, os
import csv

def main(argv):
    input_dataset = ''
    output_dir = ''
    dataset_path = ''
    nlon_cleaning = False
    try:
        opts, args = getopt.getopt(argv,"hi:o:p:nlon",["inputdataset=","outputdir=","datasetpath="])
    except getopt.GetoptError:
        print('create_text_folder.py -i Apache|LIWC [-nlon] [-p <dataset_path>] -o <output_dir>')
        sys.exit(2)
    for opt, arg in opts:
        if opt == '-h' or opt=='-help':
            print('create_text_folder.py -i Apache|LIWC [-nlon] [-p <dataset_path>] -o <output_dir>')
            sys.exit()
        elif opt in ("-nlon"):
            nlon_cleaning = True
        elif opt in ("-i", "--inputdataset"):
            input_dataset = arg
        elif opt in ("-o", "--outputdir"):
            output_dir = arg
        elif opt in ("-p", "--datasetpath"):
            dataset_path = arg

    print('Dataset: '+ str(input_dataset))
    print('NLoN: '+ str(nlon_cleaning))
    print('Dataset path: ' + dataset_path)
    print('Output directory: ' + output_dir)

    dict = {}
    if input_dataset == 'Apache':
        dict = mc.get_mail_corpus(nlon_cleaning)
        if not os.path.exists(output_dir):
            os.makedirs(output_dir)

        for k in dict.keys():
            text = '\n'.join(dict[k])
            with open(output_dir + '/' + str(k) + '.txt', "w") as text_file:
                print(text, file=text_file)

    else:
        if dataset_path == '':
            print('Wrong input dataset')
            print('create_text_folder.py -i Apache|LIWC [-nlon] [-p <dataset_path>] -o <output_dir>')
            sys.exit()

        else:
            if input_dataset == 'LIWC':
                # Path to liwc gold standard
                # header is 'ID,text,cEXT,cNEU,cAGR,cCON,cOPN'

                with open(dataset_path, encoding='cp1252') as csv_file:
                    csv_reader = csv.reader(csv_file, delimiter=',')
                    for row in csv_reader:
                        dict[row[0]] = row[1]

                if not os.path.exists(output_dir):
                    os.makedirs(output_dir)

                for k in dict.keys():
                    with open(output_dir + '/' + str(k), "w") as text_file:
                        print(dict[k], file=text_file)

            else:
                print('Wrong input dataset')
                print('create_text_folder.py -i Apache|LIWC [-nlon] [-p <dataset_path>] -o <output_dir>')
                sys.exit()

if __name__ == "__main__":
   main(sys.argv[1:])

Again this code is from github repository
It seems to work but I receive this in the command output
$ python create_text_folder.py -i Apache -o output_dir
Dataset: Apache
NLoN: False
Dataset path:
Output directory: output_dir
Reading and cleaning emails corpus. Number of emails: 3
0/3
0/3
0/3
Mails retrieved: 0
Email addresses: 0

I think it is something wrong with json format as it understands that there are 3 objects but non of the is going to the process and in the output_dir there is not any file
What can I do?

A: From your code I see that type_of_recipient in your dict should be From for the calculation stuffs to happen. Try this:
[
   {
      "id":12,
      "mailing_list_url":"12",
      "type_of_recipient":"From",
      "email_address":"test@test.org",
      "message_body":"Here is one text to test sentiment and feel happy",
      "is_response_of":"before"
   },
   {
      "id":21,
      "mailing_list_url":"21",
      "type_of_recipient":"From",
      "email_address":"test@gmail.com",
      "message_body":"Here is one text to test sentiment and feel happy and feel fine",
      "is_response_of":"before"
   },
   {
      "id":21,
      "mailing_list_url":"21",
      "type_of_recipient":"From",
      "email_address":"test@gmail.com",
      "message_body":"Not feel so good for this code",
      "is_response_of":"after"
   }
]

A: I see that there were minor errors in your json, and correcting them, this is the result that you can use:
[
  {
    "id": 12,
    "mailing_list_url": "12",
    "type_of_recipient": "before",
    "email_address": "test@test.org",
    "message_body": "Here is one text to test sentiment and feel happy",
    "is_response_of": "before"
  },
  {
    "id": 21,
    "mailing_list_url": "21",
    "type_of_recipient": "before",
    "email_address": "test@gmail.com",
    "message_body": "Here is one text to test sentiment and feel happy and feel fine",
    "is_response_of": "before"
  },
  {
    "id": "21",
    "mailing_list_url": "21",
    "type_of_recipient": "after",
    "email_address": "test@gmail.com",
    "message_body": "Not feel so good for this code",
    "is_response_of": "after"
  }
]
If your code is still not being able to do what you want, you can add a comment below and i'll get baack to your code after that.
Cheers