text:
Q: How do I open a port on one IP only with UFW? I have seven IPs on my server. Using UFW, if I enter the rule 'ufw allow 7443', port 7443 is exposed and opened on all my IPs. But I only want port 7443 to be exposed on one particular IP address and to be closed on all the others. How do I achieve this?

A: Specify the destination IP address as the to address:
sudo ufw allow to 198.51.100.205 port 7443/tcp


text:
Q: Sequilize/express and AWS RDS too many connections Building an API backend using Node/Express/Sequelize. Running pm2 on 2 quad core EC2 instances (8 clusters) and Aurora RDS with 3,000 connections available. Currently running Sequelize 5. Every few days of testing I get "too many connections" error from mysql.
This is for a new job. I've tried multiple pool configurations but the result is the same.
    "dialect": "mysql",
    "pool": {
        "max": 30,
        "min": 5,
        "idle": 10000,
        "acquire": 60000
    }
} ```

Expected Sequelize to reuse or close connections.

A: I can suggest somethings which may help you to resolve this issue.
1) Just increase the connection pool because you have enough server specs.
2) Decrease time of acquire to 30000 rather than 60000 so it will take much time to start connecting again and avoid to lost any data or problem to the user of the system.
3) Just check with "top" server logs that how much connection are created and make sure idle connections should be removed.

redpajama_set_name: RedPajamaStackExchange


text:
Q: SCOTUS reject request to prevent PA from doing it The structure "SCOTUS rejects Mr.R's request to prevent PA from doing it" appears to have two opposite meanings to me:

*

*It means "SCOTUS rejects Mr.R's request so that 'PA doing it' can be prevented."

*It means "SCOTUS rejects Mr.R's request, this request is that 'PA doing it' should be prevented" (Now SCOTUS has rejected the request, so 'PA doing it in favor of Biden is successful').
I guess (2) is what the author means. But I am not absolutely sure.

SCOTUSblog
@SCOTUSblog
The Supreme Court has rejected a Pennsylvania Republican congressman's request to prevent Pennsylvania from certifying its presidential election results in favor of Joe Biden.
This case is different from the lawsuit filed by the state of Texas this morning.

Source of article

A: The plain meaning here is clearly (2). If the author wanted to ensure it was read as (1), they would probably add commas and perhaps "in order":

...has rejected a congressman's request, in order to prevent Pennsylvania...


text:
Q: Work done by friction opposing a force at an angle Let's imagine there's a block of mass m sitting on a rough surface with a kinetic friction coefficient $\mu$. It's being pulled with a constant force $A$ at $h$ degrees above the horizontal and is displaced a distance $d$. The work done by $A$ on the block is positive and is the horizontal component of $A$ times the displacement:
$$A\cos (h)*d.$$
I thought this meant that the work done by friction would be either the negative of that amount or else
$$\mu*(mg-A\sin (h))*d$$
but apparently not?

A: You were very close. The work done by the constant force of kinetic friction is W_fric = Fdcos(a) where a is the angle between the friction and the displacement. Kinetic friction always points in the direction opposite the motion, so a equals 180°. This was your error. If the force and displacement point in opposite directions the angle bewteen them is 180° not 0°.
F = un = u(mg-Asin(h)) (as you have). d=d (highly insightful). And cos(a) = cos(180°) = -1. So W_fric = -u*(mg-Asin(h))*d, which is really just the negative of your answer. Also as a general rule, kinetic friction always points opposite to the direction of motion and hence always does negative work. Thanks for the question, I hoped my answer helped you out, and have a nice day.


text:
Q: How to use google app script property service in a html applet Good morning and thank you in advance for the help. I am a noobi at java/gas scripting so any help is appreciated.
On a google spreadsheet I have a custom menu that launches a small html menu that I would like to be able to launch various web pages from. The actual addresses are variable. I have set those as Keys with the property service when the page launches.
Here is the html code (taken from another example and trying to adapt)"
<!DOCTYPE html>
<html>
<head>
<base target="_top">
</head>
<body>
<script type="text/javascript">

var myArr = ["Peter", "Paul", "Tony", "Adam"];
function display(name) {
var accScriptPageLinkID= PropertiesService.getScriptProperties().getProperty('scriptPageLinkAdd');
Logger.log(accScriptPageLinkID)
alert(name);
}

for(var i = 0; i < 4; i ++) {
document.write('<input type="button" onclick="display(this)" name="'+  myArr[i] + '" value="'+ myArr[i] +'">'); // Will log Peter, Paul..
}
</script>
</body>
</html>

I need to modify the above code so that when the button Peter is pressed it opens the Script Page linked under the Property Service Key 'scriptPageLinkAdd'.
Or if there is an easier way to create a dynamic html page for my menu that is linked to cells in the google spreadsheet, please advise.
Mike

A: PropertiesService (and Logger too) are server-side AppsScript classes - they can't be invoked directly from the client side (your html page).
To invoke them on the server side from your html page you must use google.script.run.withSuccessHandler(clientSideFunctionToProcessReturnedData).someServerSideFunction() which can return some data back to your html page.
Learn more about HtmlService and communicating with the server here


text:
Q: A linear transformation that maps (1,2,3) to (3,2,1) and vice versa. Question: Let $v_1=(1,2,3)^T$ and $v_2=(3,2,1)^T$. Find a standard matrix for a linear transformation that maps $v_{1}$ to $v_{2}$ and vice versa.
I'm interested in different ways of going about this problem.
I offer one way.
One way: Let $A=[a_1 a_2 a_3]$ with $a_i \in \mathbb{R^3}$. Then this leads to a system with vectors as unknowns,
$$a_1+2a_2+3a_3=v_2$$
$$3a_1+2a_2+a_3=v_1$$
Now we use "augmented form" to make calculations easier, and reduce it to "RREF", and get our solution.
$$\begin{bmatrix} 1 & 0 & -1 & \frac{v_1-v_2}{2} \\ 0 & 1 & 2 & \frac{3v_2-v_1}{4} \end{bmatrix}$$
For example take Let $a_3=0$, this leads to:
$$A=\begin{bmatrix}  -1 & 2 & 0 \\ 0 & 1 & 0 \\ 1 & 0 & 0 \end{bmatrix}$$

A: You may use
$$A=\begin{bmatrix}  0 & 0 & 1 \\ 0 & 1 & 0 \\ 1 & 0 & 0 \end{bmatrix}$$
which is a permutation matrix.
This is easily obtained by swapping the first and the third row of the identity matrix.

A: Following from one of the comments we can use a permutation matrix in this scenario, and conjugate it. There is already an answer involving permutation matrices that is shorter, and in some sense simpler. I think my solution is a little bit more general, since it would work for any two vectors you want to swap.
For instance, consider the linear map $T_{12}$ that sends $e_1 \to e_2$, $e_2 \to e_1$ and $e_3 \to e_3$. This would have have matrix
$$ \begin{bmatrix}0 & 1 & 0 \\ 1 & 0 & 0 \\ 0 & 0 & 1 \end{bmatrix}$$
Now, let $S$ be the linear maps that sends $e_1 \to v_1$, $e_2 \to v_2$, and $e_3 \to e_3$. This would, of course, have matrix:
$$ \begin{bmatrix}1 & 3 & 0 \\ 2 & 2 & 0 \\ 3 & 1 & 1 \end{bmatrix}$$
If you compute it, the determinant of this matrix is $-4$. Look at the composition: $S \circ T_{12} \circ S^{-1}$.
Acting on $v_1$, we have:
$$S \circ T_{12} \circ S^{-1}(v_1) = S \circ T(e_1) = S(e_2) = v_2$$
and acting on $v_2$, we have:
$$S \circ T_{12} \circ S^{-1} (v_2) = S \circ T_{12}(e_2) = S(e_1) = v_1$$
And there you have it. This map also fixes $e_3$. The matrix for $S^{-1}$ is $$\begin{bmatrix} -\frac{1}{2} & \frac{3}{4} & 0 \\ \frac{1}{2} & -\frac{1}{4} & 0 \\ 1 & -2 & 1 \end{bmatrix}$$
The matrix for this map will be:
$$
\begin{bmatrix}1 & 3 & 0 \\ 2 & 2 & 0 \\ 3 & 1 & 1 \end{bmatrix}
\begin{bmatrix}0 & 1 & 0 \\ 1 & 0 & 0 \\ 0 & 0 & 1 \end{bmatrix}
\begin{bmatrix} -\frac{1}{2} & \frac{3}{4} & 0 \\ \frac{1}{2} & -\frac{1}{4} & 0 \\ 1 & -2 & 1 \end{bmatrix} = \begin{bmatrix} -1 & 2 & 0 \\0 & 1 & 0 \\2 & -2 & 1 \end{bmatrix} $$

A: Another way is to find $v_3$ such that $\{v_1,v_2,v_3\}$ forms a basis for $\mathbb R^3$ (e.g. $v_3=(1,0,0)^T$).
Then one can take $A$ to be $\pmatrix{0&1&0\\1&0&0\\0&0&0}$ under this basis. And then transform $A$ to the standard basis.

Hope this helps.


text:
Q: Erase the space between my div and the browser window space between my browser and my div
Hi guys, I'm a new dev and I would like to know how to erase the space between my div and my browser
Thanks
I try right=0; I try right=-10px; I try clear=both, but I'm not sure for this one.

A: Reset your browser's default styles by setting:
body{
    margin: 0;
    padding: 0;
}

A: I think you are looking at padding in CSS.
padding: 0px
to the div element in your CSS Stylesheet

A: Try setting the margin and padding to '0', as well as setting the box-sizing to 'border-box' on the root element (*) or body element in css. This may help
*{
margin: 0;
padding: 0;
box-sizing: border-box;
}

I can provide more help if you post your code along with the question. Hope this helps


text:
Q: class method triggered without being called I've defined a class to handle playing audio files. I'm instantiating the class, and calling its addEventListener() method at which time, playSound() is being triggered without the element being tapped. Also, when I call getEventListeners(bgMusic.elem) - the listener is no longer attached.
class WebAudio {

    constructor(soundFile, elem) {
        this.soundFile = soundFile;
        this.elem = elem;
        this.audio = new Audio('sound/' + this.soundFile);
    }

    addListener() {
        this.elem.addEventListener('touchstart', this.playSound());
    }

    playSound() {
        if (context.state != 'suspended') {
            console.log('playing audio file');
            if (!this.audio.playing) {
                this.audio.play();
            }
        } else {
            console.log("Audio Context locked? " + context.state)
        }
    }

}

var AudioContext = window.AudioContext || window.webkitAudioContext;
var context = new AudioContext();
function webAudioTouchUnlock(context) {
    return new Promise( (resolve, reject) => {
        //if AudioContext is suspended, and window has been interacted with
        if (context.state === 'suspended' && 'ontouchstart' in window) {
           console.log(context.state);
           var unlock = () => {
               //resume AudioContext (allow playing sound), remove event listeners
               context.resume().then(() => {
                   console.log("context resumed");
                   document.body.removeEventListener('touchstart', unlock);
                   document.body.removeEventListener('touchend', unlock);
                   resolve(true);
               }, function (reason) {
                 reject(reason);
               });
           };
           document.body.addEventListener('touchstart', unlock, false);
           document.body.addEventListener('touchend', unlock, false);
       } else {
           console.log('context not suspended? Context is ' + context.state);
           resolve(false);
       }
    });
}

webAudioTouchUnlock(context);
let bgMusic = new WebAudio('bensound-clearday.mp3', document.querySelector('#sound_button'));
bgMusic.addListener();

A: When you add the event listener like:
 this.elem.addEventListener('touchstart', this.playSound());

You care calling the function: this.playSound() and adding the result of that function (undefined) as the listener.
You just want to add the reference to the function:
this.elem.addEventListener('touchstart', this.playSound);

so the listener can call it when it needs too.
Also you will probably need to use something like this to maintain the proper this:
this.elem.addEventListener('touchstart', () => this.playSound());

or:
this.elem.addEventListener('touchstart', this.playSound.bind(this));


text:
Q: Nouns of plural form preceding another noun I was reading Computers, Communications, and Information A User's Introduction (Seventh Edition) by Sarah E. Hutchinson and Stacey C. Sawyer.
The authors consistently used such terms as communications hardware and applications software. I thought we should use communication hardware and application software instead. Why did the authors use nouns of plural form this way?
EDIT: As far as I can remember from English grammar courses, a noun should typically be modified by a single noun preceding it. Rarely have I seen such usages as in the book.

A: I do believe that in both phrases you mention are grammatical and colloquially  interchangeable.
However, I also think that there is actually a difference in the meaning. Peter Shor suggests this in his comment also. "Communications" and "Applications" refer to fields, or topic areas. So while "communication software" means something like "software that allows people to communicate with each other", "communications software" might mean something more like "software used in or made for the communications field". It's actually useful to use the plural here to disambiguate these two meanings. Notice that "Communications" is also plural in the title of the book - it's the name of a field or topic area.

A:
Why did the authors use nouns of plural form this way?

The real answer can only be found by asking them or their editor...
As someone who works in that domain I don't make any real difference between the plural or singular adjective in these cases; I prefer the singular as you do.
A couple of things to give some perspective:

*

*Technical communications are hardly a source of grammatical correctness. If there is a real distinction between plural or singular in the cases you cited, it's not used with consistency in the field (although as you point out, the authors are consistent in their book).

*Google (with quotes) "communications hardware" and you'll find 269,000 hits.

*Google (with quotes) "communication hardware" and you'll find 276,000 hits.

*Google (with quotes) "applications software" and you'll find 6,440,000 hits.

*Google (with quotes) "application software" and you'll find 13,500,000 hits.

A: I believe that 'communication software' is used when you are talking about specific software.
"Why won't my phone connect to my laptop anymore" ~ "It has a fault in the communication software."
'Communications software' is when you are talking in a more general or generic way about the software.
"We need to update our communications software."

A: Generally, your observation holds true: in compounds, nouns that are not the 'main' noun ("non-head nouns" as they would be formally termed in some frameworks) lose their inflection.
So for example, one would say:

"printer drivers" / "*printers drivers"
"restaurant meals" / "*restaurants meals"
"child laborers" / "*children laborers"

etc
However, there are a few exceptions, typically when the plural that is embedded in the compound is in someway "iconic". This can often happen for the names of fields that are per se plural, e.g. "telecommunications" or for the occasional irregular plural:

"telecommunication(s) services"
"mathematics professors" / "*mathematic professors"
"women MPs" / "?woman MPs"

In at least some of these cases, you will find both forms. For example, you'll find both "telecommunication service(s)" and "telecommunications service(s)". If you like, there's a conflict between the usual pattern of losing the inflection and the "iconicity" of the particular plural "telecommunications", and different speakers resolve this conflict in one way or the other.


text:
Q: How can I upmix audio system wide from stereo to 5.1 surround? I currently have a studio subwoofer hooked up to the c/sub jack and a 2.1 speaker system in the green front LR audio jack.
System: Windows 10 Pro, Maximus Hero VIII motherboard with Realtek HD Audio Manager
I'd like to turn off the sub on the 2.1 system and just use the subwoofer instead for bass. I have gone into Realtek HD audio manager and switched to 5.1 mode. When I test the audio, I get the rumble from the sub and the normal sound from the 2.1 sound system.
Is there some sort of registry edit, etc. which enables stereo audio being duplicated through all channels? This way I can get clean audio through the 2.1 speakers bypass, and all the bass from the sub which has no studio monitors attached.


text:
Q: Plot smooth cumulative distribution function using MATLAB How is it possible to make the following cumulative distribution function (CDF) curve smoother?
Here's my code, using cdfplot:
clear all;
close all;
y = [0.75862069 0.666666667 0.882352941 0.875 0.736842105 0.566666667 0.703703704 0.6 0 0.730769231 0.714285714 0.625 0.675 0.693877551 0.731707317 0.558823529 0.679245283 0.740740741 0.785714286 0.789473684 0.615384615 0.6 0.739130435 0.576923077 0 0.75];
cdfplot(y)

The plot looks like:

A: data = [1 2 2 3 4];
dsum = sum(data);
normalized_data = data/dsum;

cdf = data;

for i = 1:length(data)
    cdf(i) = sum(normalized_data(1:i));
end

plot(cdf);

Is this what you are looking for?

A: data = [2 1 4 2 3];
sdata = sort(data);
plot(sdata,(0.5:length(sdata))./length(sdata),'-');

A: You can use the function ecdf:
[f,x] = ecdf(y);
plot(x,f);

A: There is one method. But I consider it as a kind of cheating. Use it with your own responsibility.
you can try cdfplot([x,x+a*randn(length(x),1)]). You can play with parameter a, but I suggest you to use value around 0.5. Cheers.


text: Q: How to shrink the size of AAR file produced by building an Android Library Module? I have seen the Android Developer Documentation on shrinking APK size. But, for a library module, I couldn't find a proper documentation or tutorial for shrinking the AAR file size. So, how to achieve smaller AAR file size ?


text:
Q: Using CanCanCan, how do I authorize either/or in a controller? I've got a page for administrating multiple objects (like users and groups), and I want to ensure that only users who have access to create at least one of those types of objects can view the page.
Basically, I want to be able to write something like
(authorize! :create, User) || (authorize! :create, Group)

Any suggestions?

A: One way to achieve this is by mixing
load_and_authorize_resource :user
load_and_authorize_resource :through => :user

this is a convenience helper for calling authorize on all resources in a controller that does something like this:
class GroupsController < ActionController::Base
  load_and_authorize_resource
  load_and_authorize_resource :through => :user

  def create
    # Automatically does the following:
    # @group = Group.find(group_params[:id])
    # authorize! :create, @group

    # @user= User.find(group_params[:user_id])
    # authorize! :create, @user
  end

end

so where in your controller you load the Group and User objects it will auto authorize them against your rules/Abilities like
can [:create], [User, Group]

Of course you will need your Groups to be a nested resource:
resources :users do
  resources :groups
end

Hope it helps.

A: The best I can come up with is to use multiple can? statements and raise AccessDenied on failure. You also should avoid authorization checks against a model class, and instead authorize against a model instance. See CanCanCan - Common Mistakes.
user = User.new(...)
group = Group.new(...)
raise CanCan::AccessDenied.new(nil, :create, [user, group]) \
  unless can?(:create, user) || can?(:create, group)

AccessDenied.new(nil, ..) -> nil for the first argument result in the default error message.
See cancan/exceptions.
I'd probably move this into a helper to a method named def authorize create_group_or_user!
That said, maybe you are doing too much in this controller? Alternatively, you could make this controller redirect without authorization to the appropriate GroupController or UserController, and perform the appropriate authorization checks in those locations.
Alternate Option 2: Maybe use an accessible_by restriction on the content, and don't call authorize! at all.


text:
Q: Gitolite and http Error 500. Permission issue in setup I attempted to install Gitolite on a Fedora 17 server with the aim of setting up git and HTTP access along with authorisation. Git access works OK. Can push and pull. But HTTP access falls over with an Error 500. It appears I got something wrong with permissions.
Here's what I did. I followed instructions from here: sitaramc.github.com
I have documented what I have tried to do here if anyone would like to see it down to detail.
HTTP Error:

Internal Server Error - 500
  The server encountered an internal error or misconfiguration and was unable to complete your request.
  More information about this error may be available in the server error log.

Error Log - /var/log/httpd/error-git.log

[Wed Feb 13 08:26:11 2013] [error] [client 192.168.0.40] suexec failure: could not open log file
  [Wed Feb 13 08:26:11 2013] [error] [client 192.168.0.40] fopen: Permission denied
  [Wed Feb 13 08:26:11 2013] [error] [client 192.168.0.40] Premature end of script headers: gitolite-suexec-wrapper.sh
  [Wed Feb 13 08:30:13 2013] [error] [client 192.168.0.40] Directory index forbidden by Options directive: /var/www/git/

* Update 1 *
 - Managed to post the error output here.
* Update 2 *
Relaxed permissions on log directory and gitolite-suexec-wrapper.sh. More details are available at the link above where I have documented in detail.
/var/log/httpd/error-git.log

[Wed Feb 13 21:18:47 2013] [error] [client 192.168.0.40] suexec policy violation: see suexec log for more details
  [Wed Feb 13 21:18:47 2013] [error] [client 192.168.0.40] Premature end of script headers: gitolite-suexec-wrapper.sh
  [Wed Feb 13 21:18:54 2013] [error] [client 192.168.0.40] Directory index forbidden by Options directive: /var/www/git/
$ sudo more /var/log/httpd/suexec.log
  [2013-02-13 21:18:47]: uid: (990/git) gid: (988/git) cmd: gitolite-suexec-wrapper.sh
  [2013-02-13 21:18:47]: cannot stat program: (gitolite-suexec-wrapper.sh)

Not sure where next
* Update 3 *
Ok, so I made some progress. I may have fixed the permissions issue. Now facing a PATH issue. Like before, most relevant output is included here. Full details are  updated at the link in my original post.
My knowledge of Apache config is very basic. After reading about suEXEC, I realised the permission issue could be arising out of SELinux. So I disabled it for now. (Would like to identify a way of having gitolite working with SELinux active, but that's for later. Suggestions are welcome.)
Now when I access the url: http:// mochapenguin /git/testing.git in browser
001E# service=git-upload-pack
0000003BERR FATAL: unknown git/gitolite command: 'testing.git'
When I test from the client machine, I see:

ssh git@mochapenguin \echo $PATH
  FATAL: unknown git/gitolite command: 'echo /usr/lib64/qt-3.3/bin:/usr/local/bin:/usr/bin:/bin:/usr/local/sbin:/usr/sbin:/home/mochapenguin/.local/bin:/home/mochapenguin/bin'

* Update 4 *
Alright, got it working. No further change was needed since my last update.
I ought to have tried accessing the repo like so, instead of trying the URL in the browser:
git clone http://username:password@mochapenguin/git/testing.git

This setup allows clone and push over http
I can't figure out what I got wrong.
Could someone point me the right way, please?


text:
Q: how replace existing image in PHP? I'm having a difficulty on how to replace the image on my folder and database.
I don't have the slightest idea on how to code it. Can somebody help me?
My code is like this.
if ((($_FILES["prodImage"]["type"] == "image/gif")
|| ($_FILES["prodImage"]["type"] == "image/jpeg")
|| ($_FILES["prodImage"]["type"] == "image/pjpeg")
|| ($_FILES["prodImage"]["type"] == "image/jpg")
|| ($_FILES["prodImage"]["type"] =="image/png"))
&& ($_FILES["prodImage"]["size"] < 2000000))
{
    if (file_exists("product_images/" . $_FILES["prodImage"]["name"]))
        {
        ?>
            <script language="javascript">
            alert("<?php echo $_FILES["prodImage"]["name"] . " already exists. ";?>");
            window.history.back();
            </script>
        <?php
        }
        else
        {
            move_uploaded_file($_FILES["prodImage"]["tmp_name"],
            "product_images/" .$_FILES["prodImage"]["name"]);
            $im = $_FILES["prodImage"]["name"];

            $qry = "INSERT INTO products(productID, productName, productDesc, price, image, product_status, product_type) VALUES(null,'$prodName','$prodDesc','$price','$im','$category', '$prodtype')";
            $result = @mysql_query($qry);
            //Check whether the query was successful or not

    }
}

A: Basically you should check if the file already exists. If it exists: delete or overwrite it, then use an UPDATE statement instead of the INSERT INTO. If it does not exist: Save the file and use the INSERT INTO statement just like before.


text:
Q: How do I update a Label from within a BackgroundWorker thread? When I used WinForms, I would have done this in my bg_DoWork method:
status.Invoke(new Action(() => { status.Content = e.ToString(); }));
status.Invoke(new Action(() => { status.Refresh(); }));

However in my WPF application I get an error saying that Invoke does not exist for Label.
Any help would be appreciated.

A: Use the capabilities already built into the BackgroundWorker. When you "report progress", it sends your data to the ProgressChanged event, which runs on the UI thread. No need to call Invoke().
private void bgWorker_DoWork(object sender, DoWorkEventArgs e)
{
    bgWorker.ReportProgress(0, "Some message to display.");
}

private void bgWorker_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
    status.Content = e.UserState.ToString();
}

Make sure you set bgWorker.WorkerReportsProgress = true to enable reporting progress.

A: If you're using WPF, I'd suggest looking into DataBinding.
The "WPF way" to approach this would be to bind the label's Content property to some property of your model. That way, updating the model automatically updates the label and you don't have to worry marshalling the threads yourself.
There are many articles on WPF and databinding, this is likely as good a place to start as any: http://www.wpf-tutorial.com/data-binding/hello-bound-world/

A: You need to use
Dispatcher.Invoke(new Action(() => { status.Content = e.ToString(); }))
instead of status.Invoke(...)

A: This will help you.
To Execute synchronously:
Application.Current.Dispatcher.Invoke(new Action(() => { status.Content = e.ToString(); }))

To Execute Asynchronously:
Application.Current.Dispatcher.BeginInvoke(new Action(() => { status.Content = e.ToString(); }))

A: You really should think about using the power of "Data Binding" in WPF.
You should be updating an object in your view model and binding that to your user interface control.
See MVVM Light. Simple and easy to use. Don't code WPF without it.


text:
Q: MySQL, get the position of a row in a set for multiple row I have this query that compute a position of a publication inside a set of publications (here named as community), according to there effective_publishing_date :
SELECT p.publication_id
     , p.name publication_name
     , IF(p.scheduled_at is not null, p.scheduled_at, p.created_at) effective_publishing_date
     , @current_rank := @current_rank + 1 publication_rank
FROM publications p
JOIN (SELECT @current_rank := 0) r
WHERE p.community_id = 8513
ORDER
    BY effective_publishing_date ASC;

This result as:
[![enter image description here][1]][1]
Now I have a list of feed_item which have each community_id and publication_id as properties and I would like to get, for each feed_item, the associated publication_rank.
For instance, if I have a publication_item with publication_id = 18 and community_id = 2, I want the publication_rank of the publication_id #18 among all the publications of the community_id #2. I don't success to get that in one query (or with sub queries etc).
Thanks per advance,

A: Here are the two solutions I finally found. Thanks to @Barmar !

*

*Only with joins:

SELECT
  g1.community_id,
  g1.publication_name,
  g1.publication_name,
  g1.publication_id,
  COUNT(*) AS rank
FROM
  (
    SELECT
      publications.publication_id as publication_id,
      publications.name as publication_name,
      publications.community_id as community_id,
      communities.name as community_name,
      IF(
        publications.scheduled_at is not null,
        publications.scheduled_at, publications.created_at
      ) as effective_publishing_date
    FROM
      feed_items
      JOIN publications ON feed_items.publication_id = publications.publication_id
      JOIN communities ON publications.community_id = communities.community_id
    WHERE
      feed_items.user_id = 489387
  ) AS g1
  JOIN (
    SELECT
      publications.publication_id as publication_id,
      publications.community_id as community_id,
      IF(
        publications.scheduled_at is not null,
        publications.scheduled_at, publications.created_at
      ) as effective_publishing_date
    FROM
      feed_items
      JOIN publications ON feed_items.publication_id = publications.publication_id
    WHERE
      feed_items.user_id = 489387
  ) AS g2 ON (
    g2.effective_publishing_date, g2.publication_id
  ) <= (
    g1.effective_publishing_date, g1.publication_id
  )
  AND g1.community_id = g2.community_id
GROUP BY
  g1.publication_id,
  g1.community_id,
  g1.effective_publishing_date
ORDER BY
  g1.community_id,
  rank ASC;

*With SQL variables

SELECT data_table.publication_id, data_table.publication_name, data_table.community_id, data_table.effective_publishing_date,
   @publication := IF(@community <> data_table.community_id, concat(left(@community := data_table.community_id, 0), 0), @publication+1) AS rank
FROM
  (SELECT @publication:= -1) p,
  (SELECT @community:= -1) c,
  (SELECT
        publication.name as publication_name,
        publication.community_id as community_id,
        feed_item.publication_id as publication_id,
        IF(publication.scheduled_at is not null, publication.scheduled_at, publication.created_at) as effective_publishing_date
   FROM feed_items feed_item
   JOIN publications publication ON feed_item.publication_id = publication.publication_id
   WHERE feed_item.user_id = 489387
   ORDER BY publication.community_id, effective_publishing_date ASC
  ) data_table;


text:
Q: What should I do to add a domain event after the completion of UnitOfWork? I used the ABP vNext framework.I need to publish a domain event when saved an aggregated specified property to the database successfully,but now, the domain event is always triggered before the unit of work is completed.
Code
public class Meeting : AggregateRoot<Guid>{
        public Meeting(Guid id, Guid applicantId) : base(id) {
            ApplicantId = applicantId;
            Phase = MeetingPhase.Draft;
            Type = MeetingType.Default;
            TimeAndPlaces = new Collection<TimeAndPlace>();
            InsideAttendees = new Collection<InsideAttendee>();
            MeetingFiles = new Collection<MeetingFile>();
        }

        /// <summary>
        /// 取消会议
        /// </summary>
        public void Cancel() {
            Phase = MeetingPhase.Draft;
            Type = MeetingType.Canceled;
            var cancelData = new MeetingCancelData(this);
            AddLocalEvent(cancelData);
        }
    }

A: You can contribute to IUnitOfWork.CompletedHandlers handlers.
See https://github.com/abpframework/abp/blob/dev/framework/src/Volo.Abp.Uow/Volo/Abp/Uow/UnitOfWork.cs#L194


text:
Q: Passing object from one component to another component in Angular I am working in Angular 7 .
where I am passing object to another component , I am doing it using @input decorative , but components are siblings ,
        so How I can pass the object to another component

A: It is better use Service for the communication in this scenario.
In service u can use Subject which can act as both observer and observable.
ex.
In Service
  someSubject = new Subject<any>();

In component one
 someService.someSubject.next(objectUWantToSend);

In Component two u can subscribe or vise versa
someService.someSubject.subscribe((receiveObjectHere) => {});

A: @input decorative can only be used for passing values from parent to child components.
For communication between siblings or any components use rxjs subject and Observable instead.
You can follow this -
http://jasonwatmore.com/post/2018/06/25/angular-6-communicating-between-components-with-observable-subject


text:
Q: Developing a google play app with HTC Desire I've been a Java developer for 6 years, but this is my first foray into Android, and it's not going well.
I've set up a simple example app which uses google maps api v2 - it's just a single page: I copied it from one of the many helpful sites on this topic.
I then discovered that I can't run it in an emulator since it uses the google maps api v2, which requires google play. So I bought a device (HTC Desire).
Now the device doesn't show up in the eclipse run configuration. It shows up with ./adb devices just fine.
I thought maybe this was because the device is on Android 2.2, and my app has minimum OS level of 4.2. So I tried to upgrade, but I couldn't work out how. In the software / update section on the phone it just says 'no updates available'. Can this be right?
Ok so assuming I can't upgrade the OS (in which case the phone is now useless), I modified the project so the minSdkVersion is now 8. But now my project won't build!
Errors include 'No resource identifier found for attribute 'showAsAction' in package 'android'' - what does that even mean?
And to cap it all the device is now doing the 'buzzing 7 times instead of booting' thing. I can access some menu called HBOOT, and selecting RECOVERY just reboots the machine, which fails.
So now I've spent £50 and several hours, and I haven't even got as far as hello world - just a bricked phone.
What am I doing wrong? Can Android dev really be this hard?


text:
Q: Does sending goroutine get blocked? I've created the example here: https://play.golang.org/p/kpV3T1XF9bz
Essentially, I have the main goroutine that creates three additiona goroutines.  In the main goroutine, I have a for loop with a select statement that prints the results of the created channel, followed by a sleep.
When I run the program, I don't see a delay in any of my print statements.  Does this mean that sending goroutines never block?
My expectation was that while the main goroutine was sleeping, before we looped back to the select statement, the unbuffered channel would not be ready to accept new data, but what I'm seeing contradicts this.
EDIT: Updated playground link with proper delay in seconds.

A: You don't need to use select. Just use the for loop, it will solve your problem. Here is the code.
package main

import (
    "fmt"
    "time"
)

func First(c chan string) {
    c <- "FirstOne"
    // fmt.Println("First string")
}

func Second(c chan string) {
    c <- "SecondOne"
    // fmt.Println("Second string")
}

func Third(c chan string) {
    c <- "ThirdOne"
    // fmt.Println("Third string")
}

func main() {
    c := make(chan string)
    go First(c)
    go Second(c)
    go Third(c)

    for i := 0; i < 3; i++ {
        fmt.Println(<-c)
        time.Sleep(time.Second * 2)
    }
    fmt.Println("Timeout")
}


text:
Q: How to search image which image name contain '12345' in textbox I'm a newbie in C# programming language. I need some guide on how can I search image in textbox which just typing image name that contain 12345. This is because each image name in my folder is naming like this > JUN (12345). I want the image display at picturebox after typing 12345 in textbox. Here is my code that I already try it not display image that contain 12345. Hope anyone can help me. Thanks
  private void textBoxWorkNo_KeyUp(object sender, KeyEventArgs e)
                {
                    if (e.KeyCode == Keys.Enter)
                    {
                        if (textBoxWorkNo.Text != "")
                        {
                            //Do something
                            string selectSql = "select name, empno, icnum, passport, deptno, section, designation from m_employee where workno=@workno";
                            SqlCommand cmd = new SqlCommand(selectSql, con);
                            cmd.Parameters.AddWithValue("@workno", textBoxWorkNo.Text);

                            bool isDataFound = false;

                            try
                            {
                                con.Open();

                                using (SqlDataReader read = cmd.ExecuteReader())
                                {

                                while (read.Read())
                                {
                                    isDataFound = true;

                                    textBoxEmplNo.Text = (read["empno"].ToString());
                                    textBoxName.Text = (read["name"].ToString());
                                    textBoxICPass.Text = (read["icnum"].ToString());
                                    textBoxPassport.Text = (read["passport"].ToString());
                                    textBoxDept.Text = (read["deptno"].ToString());
                                    textBoxSection.Text = (read["section"].ToString());
                                    textBoxDesignation.Text = (read["designation"].ToString());

                                    //BaseFolder that contains the multiple folders
                                    //If the folders don't share the same base folder make an array with full paths
                                    string baseFolder = "C:\\Users\\hamizah\\Desktop\\photo";
                            string[] employeeFolders = Directory.GetDirectories(baseFolder);

                                    //Search image
                                    string imgName = "%'" + textBoxEmplNo.Text + "%'" + ".jpg";

                                    //Bool to see if file is found after checking all
                                    bool fileFound = false;

                                    foreach (var folderName in employeeFolders)
                                    {
                                        var path = Path.Combine(folderName, imgName);
                                        if (File.Exists(path))
                                        {
                                            pictureBox1.Visible = true;
                                            pictureBox1.Image = Image.FromFile(path);
                                            fileFound = true;
                                            //If you want to stop looking, break; here
                                        }
                                    }
                                    if (!fileFound)
                                    {
                                        //Display message that No such image found
                                        pictureBox1.Visible = true;
                                        pictureBox1.Image =

     Image.FromFile(@"C:\Users\hamizah\Desktop\images\photo\No-image-found.jpg");
                                    }

                                    dataGridView1.Visible = false;
                                }

                            }

                            if (!isDataFound)
                            {
                                textBoxEmplNo.Text = "";
                                textBoxWorkNo.Text = "";
                                textBoxName.Text = "";

                                // Display message here that no values found
                                MessageBox.Show("No Result Found");
                            }
                        }
                        finally
                        {
                            con.Close();
                        }
                    }

                    else
                    {
                        textBoxEmplNo.Text = "";
                        textBoxName.Text = "";

                    }

                }
            }

A: You can use below code to get the files in the specific directory, which has a partial matching names as input value.
For each directory you are iterating through get the directory info first:
 DirectoryInfo directoryInfo = new DirectoryInfo(@"c:\");

Then get the files as mentioned below:
FileInfo[] fileInfoArray = directoryInfo.GetFiles("*" + inputFileName + "*.*");

Then you can check the fileInfoArray for the file you are looking for. It can return multiple file info, depending on your input.
For reference: added the actual code here:
string partialInputName = "12345"; //textbox input value or whatever you want to input
        string[] directories = Directory.GetDirectories(@"C:\Code");
        FileInfo fileinDir;
        foreach(string dir in directories)
        {
            DirectoryInfo dirInfo = new DirectoryInfo(dir);
            if (dirInfo.Exists)
            {
                //taking the first (FirstOrDefault()), considering that all files have a unique name with respect to the input value that you are giving. so it should fetch only one file every time you query
                fileinDir = dirInfo.GetFiles("*" + partialInputName + "*.*").FirstOrDefault();
            }
        }

A: File.Exists looks for one specific file. There is no file with weird name %'12345%'.jpg I guess. You can use this form:
foreach (var f in Directory.EnumerateFiles(rootPath, "*12345*.jpg")){
...
}

A: If it's already on the disk just use Directory.GetFiles() like so:
var strings = Directory.GetFiles(".","*12345*");

foreach (var s in strings)
{
    Debug.Write(s);
}


text:
Q: Pattern matching a non-exceptional value using try-catch expression I have a question regarding the try catch block .Here is an example :
val num = try {
  110 / 12
} catch {
  case ex: NumberFormatException => 0
}

val num1 = try {
  110 / 13
} catch {
  case a: num1 > 10 => 10
  case b: num1 < 10 => 12
}

I know num works so why is num1 not valid? All the examples and articles I've seen only do the NumberFormatException or ArithmenticException. And also are greater than and less than not valid operators in the case statement? Is it possible to treat the try catch block like an if else block using pattern matching?

A: I guess you are attempting to write something like
try {
  110 / 13
} catch {
  case a if a > 10 => 10
  case b if b < 10 => 12
}

however this is not valid syntax because a try expression is of the form
try { b } catch h

where handler h must be a partial function of type
PartialFunction[Throwable, T]

so a in case a if a > 10 must be Throwable however Throwable does not have > method defined on it.

Consider monadic error handling using Try instead of try-catch expression. This would allow you to simply map over in the happy case. For example, consider
Try(110 / 13)
  .map(num => if (num > 10) 10 else 12)
  .getOrElse(someDefaultValue)

Handling Error Without Exceptions has some interactive exercises to get you started with the concept.

A: Supplementing the other answer, if you itch to have a tidy list of cases:
scala> import util._
import util._

scala> Try(1/0) match {
     | case Success(i) if i > 42            => 42
     | case ok @ Success(_)                 => ok
     | case Failure(_: ArithmeticException) => 27
     | }
res0: Int = 27


text:
Q: Determine max possible intensity of image Starting to use the PHP Imagick classes and the lack of documentation. In particular using the paintTransparentImage method.
In the CLI version of ImageMagick one can simply pass a percentage for the fuzz parameter. However, in PHP it seems you have to specify it as an amount relative to the "maximum possible intensity" of the image.
How do you determine the max possible intensity of an image then? Apparently it can be 255, 65535, or 4294967295.

A: With PHP you would determine the quantum range, and calculate the intensity with pow(2,Q)
$img = new Imagick('source.png');
$quantum = $img->getQuantumDepth()['quantumDepthLong'];
$target = 'black';
$alpha = 0.0; // Fully transparent
$fuzz = 0.5 * pow(2,$quantum); // From black to gray50
$img->paintTransparentImage($target, $alpha, $fuzz);

From the above comments, the maximum intensity can be mapped by the quantum sizes
+---------------+-------------+---------------+
| Quantum Range | Packet Size | Max Intensity |
+---------------+-------------+---------------+
|  8            |  32 bits    |        255    |
| 16            |  64 bits    |      25535    |
| 32            | 128 bits    | 4294967295    |
+---------------+-------------+---------------+

A: based on the answer above I'll just post my own solution in case it might benefit others. Essentially just massaging the Imagick class a bit to make it more sane for a human user. The good news is, it doesn't violate the syntax of the existing paintTransparentImage function since the fuzz parameter is already listed as a float (it does change the semantics though). This tweak just makes it resemble the cli interface where you can pass a percentage (although here you will pass .1 instead of 10 to indicate 10%).
class SaneImagick extends Imagick
{
    public function paintTransparentImage($target, $alpha, $fuzz)
    {
        $iQuantumDepth = pow(2, $this->getQuantumDepth()['quantumDepthLong']);
        return parent::paintTransparentImage($target, $alpha, $fuzz * $iQuantumDepth);
    }
}


text:
Q: Switching Map Units on Data Frame Properties back to Feet in ArcMap? Using ArcView 10.1, I cannot switch the Map (Units) nder Data Frame Properties to Feet.  It is currently at Decimal Degrees.  Display can switch.
How do you switch it back to Feet?

A: I believe you must have your coordinate system set to a system that uses feet as its units.

A: Your data frame is probably set to a Geographic Coordinate System on its Coordinate System tab. Try changing it to a Projected Coordinate System which has feet units.


text:
Q: Java Iterator hasNext strange behavior I have the following code:
  Set<OWLNamedIndividual> individuals = reasoner.getInstances( tClass, false ).getFlattened();
  for(OWLNamedIndividual it1 : individuals)
       {
     NodeSet<OWLNamedIndividual> names = reasoner.getObjectPropertyValues( it1, obj1 );
         System.out.println(it1.getIRI().getShortForm() + " has objects:");
     for(Node<OWLNamedIndividual> it2: names)
         {
          Iterator iter=it2.iterator();
          while(iter.hasNext())
           {
            System.out.print("\t");
            System.out.println(iter.next().toString());
               System.out.println(iter.hasNext());
           }
         }
       }

that returns the following:
name has objects:
<http://www.test/#name>
     false
<http://www.test/#name2>
     false

The inner hasNext seams not working while the outer do. I need to check for the last iteration. What is the issue here ? Many thanks.

A: There is no problem here. When you call next(), the value of hasNext() can change. The last time through it will print as false. In this case each outer collection appears to have only one element each.


text:
Q: Mapping ReactJS list with data from an API.graphql call I'm trying to map a list with data from an API call to a DynamoDB and I admit, there are many holes in my self-taught JavaScript knowledge.
How do I expose the songList object created in songs = () => {} to my return songList.map?
I've tried with API call outside the component declaration, and in and outside a function.
import React, { Component } from 'react';
import * as queries from '../graphql/queries';
import Song from './Song';

API.configure(awsconfig);

class SongList extends Component {
  render() {
    const songs = () => {
      API.graphql(graphqlOperation(queries.listSongs)).then(function (songData) {
        const songList = songData['data']['listSongs']['items'];
        return songList;
      });
    }

    console.log(songs()); // undefined

    return (

        {
          songList.map((song, i) => <Song
            key={i}
            title={song['title']}
            author={song['author']}
            keywords={song['keywords']}
            instruments={song['instruments']}
            isrcCode={song['isrcCode']}
            lyrics={song['lyrics']}
          />)
        }

    )
  }
}

export default SongList;

A: never NEVER do reqests in render method
componentDidMount(){
 const songs = () => {
      API.graphql(graphqlOperation(queries.listSongs)).then(function (songData) {
        const songList = songData['data']['listSongs']['items'];
        return songList;
      });
this.setState({list:sondgs()})

}

render() {
    let list = this.state.list || []

    return (

        {
          list.map((song, i) => <Song
            key={i}
            title={song['title']}
            author={song['author']}
            keywords={song['keywords']}
            instruments={song['instruments']}
            isrcCode={song['isrcCode']}
            lyrics={song['lyrics']}
          />)
        }

    )
  }
}


text:
Q: Change color of Font Awesome icons in Zurb Foundation 6.3 with css hover I want to change the color of the circles in my stacked Font Awesome social icons (ie., the icons are on top of circles) on pages in Zurb Foundation 6.3, using the hover property to go from a gray to a red color.
I've researched different solutions but nothing works. (I understand you can't specify the inline-block property to align the icons because it keeps the hover property from working, so I used ul and li tags instead.)
Is the problem because I'm using Font Awesome in Foundation rather than in Bootstrap?  I can't find any documentation on this; I assume it will work with Foundation.  Any help would be much appreciated.
Thanks,
Steve J.
Here's my code:
CSS:
.social fa-circle {
color: #808080;
}

.social fa-circle:hover {
color: #990000;
}

HTML:

A: I think the problem is you're missing the periods for the fa classes. try:
.social .fa-circle {
color: #808080;
}

.social .fa-circle:hover {
color: #990000;
}


text:
Q: Ruby unable to load after installing TotalTerminal through brewcask with boxen After running Boxen with a
package { 'totalterminal':
  provider => 'brewcask',
  install_options => ['--appdir=/Applications'],
}

directive, my system Ruby is unable to load libraries, including builtins like Set, rendering commands like ruby, irb, bundle, gem etc., completely unusable and Boxen unable to run:
mba2:~ nrser$ echo $PATH
/usr/bin:/bin:/usr/sbin:/sbin:/usr/local/bin:/opt/X11/bin

mba2:~ nrser$ which ruby
/usr/bin/ruby

mba2:~ nrser$ ruby -v
ruby 2.0.0p451 (2014-02-24 revision 45167) [universal.x86_64-darwin13]

mba2:~ nrser$ ruby -e ''
Could not find mini_portile-0.5.3 in any of the sources
Run `bundle install` to install missing gems.

irb, gem and bundle all immediately fail with the same error.
If I put the RBenv stuff back in the path (by sourcing /opt/boxen/env.sh), I get an even weirder fail, where Ruby can't find the Set module:
mba2:~ nrser$ echo $PATH
bin:/opt/boxen/rbenv/shims:/opt/boxen/rbenv/bin:/opt/boxen/rbenv/plugins/ruby-build/bin:node_modules/.bin:/opt/boxen/nodenv/shims:/opt/boxen/nodenv/bin:/opt/boxen/bin:/opt/boxen/homebrew/bin:/opt/boxen/homebrew/sbin:/usr/bin:/bin:/usr/sbin:/sbin:/usr/local/bin:/opt/X11/bin

mba2:~ nrser$ which ruby
/opt/boxen/rbenv/shims/ruby

mba2:~ nrser$ ruby -v
ruby 2.0.0p451 (2014-02-24 revision 45167) [universal.x86_64-darwin13]

mba2:~ nrser$ ruby -e ''
/System/Library/Frameworks/Ruby.framework/Versions/2.0/usr/lib/ruby/2.0.0/rubygems/core_ext/kernel_require.rb:55:in `require': cannot load such file -- set (LoadError)
    from /System/Library/Frameworks/Ruby.framework/Versions/2.0/usr/lib/ruby/2.0.0/rubygems/core_ext/kernel_require.rb:55:in `require'
    from /Library/Ruby/Gems/2.0.0/gems/bundler-1.5.3/lib/bundler/index.rb:1:in `<top (required)>'
    from /Library/Ruby/Gems/2.0.0/gems/bundler-1.5.3/lib/bundler/source/rubygems.rb:168:in `fetch_specs'
    from /Library/Ruby/Gems/2.0.0/gems/bundler-1.5.3/lib/bundler/source/rubygems.rb:66:in `specs'
    from /Library/Ruby/Gems/2.0.0/gems/bundler-1.5.3/lib/bundler/lazy_specification.rb:53:in `__materialize__'
    from /Library/Ruby/Gems/2.0.0/gems/bundler-1.5.3/lib/bundler/spec_set.rb:88:in `block in materialize'
    from /Library/Ruby/Gems/2.0.0/gems/bundler-1.5.3/lib/bundler/spec_set.rb:85:in `map!'
    from /Library/Ruby/Gems/2.0.0/gems/bundler-1.5.3/lib/bundler/spec_set.rb:85:in `materialize'
    from /Library/Ruby/Gems/2.0.0/gems/bundler-1.5.3/lib/bundler/definition.rb:133:in `specs'
    from /Library/Ruby/Gems/2.0.0/gems/bundler-1.5.3/lib/bundler/definition.rb:178:in `specs_for'
    from /Library/Ruby/Gems/2.0.0/gems/bundler-1.5.3/lib/bundler/definition.rb:167:in `requested_specs'
    from /Library/Ruby/Gems/2.0.0/gems/bundler-1.5.3/lib/bundler/environment.rb:18:in `requested_specs'
    from /Library/Ruby/Gems/2.0.0/gems/bundler-1.5.3/lib/bundler/runtime.rb:13:in `setup'
    from /Library/Ruby/Gems/2.0.0/gems/bundler-1.5.3/lib/bundler.rb:119:in `setup'
    from /Library/Ruby/Gems/2.0.0/gems/bundler-1.5.3/lib/bundler/setup.rb:7:in `<top (required)>'
    from /System/Library/Frameworks/Ruby.framework/Versions/2.0/usr/lib/ruby/2.0.0/rubygems/core_ext/kernel_require.rb:55:in `require'
    from /System/Library/Frameworks/Ruby.framework/Versions/2.0/usr/lib/ruby/2.0.0/rubygems/core_ext/kernel_require.rb:55:in `require'

This is the second box this has happen on, though both boxes use very similar manifests. Both are on OSX 10.9.3.
My guess is that this has something to do with the TotalTerminal installer restarting the Terminal app during its installation, terminating Boxen/Puppet.
Does anyone have any idea what's gone wrong, or how i can repair my Ruby?
I don't really care that much about having TotalTerminal install through Boxen, but no Ruby is basically a broken machine for me.


text:
Q: HTML5 Boilerplate and NetBeans Are there any instructions available about how to use HTML5 Boilerplate with NetBeans?

A: HTML5 boilerplate is just a default template for HTML5 websites. If I get you right, you want to use it with Netbeans. The answer seems quite simple to me: Download, unzip and open up the files with your favourite editor (in your case, Netbeans w/ HTML). The boilerplate is mostly simple plain text; nothing fancy. They even tell you on their webpage:

Boilerplate is not a framework, nor does it prescribe any philosophy of development, it's just got some tricks to get your project off the ground quickly and right-footed.

So just: Download, Unzip, Open, Enjoy.


text:
Q: Custom MenuStrip in Visual C# Express I would like to create very nice looking menu as shown on the picture:

How can I do this? I can create one item with image and text behind it, but how to group them etc.

A: If you are using Winforms, this ribbon interface is very nice to use with a well documented intuitive API
Check out Krypton from Component Factory:
https://github.com/ComponentFactory/Krypton


text:
Q: XHTML to Structured XML with XSLT 1.0 I have an XHTML document from a basic ePub output that I'm trying to convert into a structured XML document. The format of it shouldn't be too crazy in general and looks like the following:
<?xml version="1.0" encoding="utf-8"?>

Topic 1

1.0.1

1.0.2

Subtopic 1.1

1.1.1

1.1.2

Subtopic 1.2

1.2.1

1.2.2

Topic 2

2.0.1

2.0.2

Subtopic 2.1

2.1.1

2.1.2

Subtopic 2.2

2.2.1

2.2.2

Ideally, I'd like to convert this into some structured code, based on the h1, h2, ... tags. The stuff after the first h1, but before the second should be contained inside its own container, and the stuff in the second h1 to the end of the document inside its own. Likewise, the stuff between h2's should also go into a container, thereby nesting it. The output should be something like this:
<Root>
   <Topic>
      <Title>Topic 1</Title>
      <Paragraph>1.0.1</Paragraph>
      <Paragraph>1.0.2</Paragraph>
      <Topic>
         <Title>Subtopic 1.1</Title>
         <Paragraph>1.1.1</Paragraph>
         <Paragraph>1.1.2</Paragraph>
      </Topic>
      <Topic>
         <Title>Subtopic 1.2</Title>
         <Paragraph>1.2.1</Paragraph>
         <Paragraph>1.2.2</Paragraph>
      </Topic>
   </Topic>
   <Topic>
      <Title>Topic 2</Title>
      <Paragraph>2.0.1</Paragraph>
      <Paragraph>2.0.2</Paragraph>
      <Topic>
         <Title>Subtopic 2.1</Title>
         <Paragraph>2.1.1</Paragraph>
         <Paragraph>2.1.2</Paragraph>
      </Topic>
      <Topic>
         <Title>Subtopic 2.2</Title>
         <Paragraph>2.2.1</Paragraph>
         <Paragraph>2.2.2</Paragraph>
      </Topic>
   </Topic>
</Root>

Even though the example only consists of p tags, it may also contain div's, and other elements, so don't count on it being just one node. It needs to be generic enough to not care what's between the header tags.
I'm familiar with Muenchian grouping, but this is a bit complex of a situation for me. I've tried using keys like this:
<xsl:key name="kHeaders1" match="*[not(self::h1)]" use="generate-id(preceding-sibling::h1[1])"/>

<xsl:template match="h1">
  <Topic>
    <Title><xsl:apply-templates /></Title>
    <xsl:apply-templates select="key('kHeaders1', generate-id())" />
  </Topic>
</xsl:template>

<xsl:template match="html">
  <Root>
     <xsl:apply-templates select="body/h1" />
  </Root>
</xsl:template>

<xsl:template match="p">
   <Paragraph><xsl:apply-templates /></Paragraph>
</xsl:template>

This works well enough for the first level, but then trying to repeat the process, but using h2, seems to break my mind. Since at the h2 level, the key for any node should be the first, h1 or h2 sibling. It almost seems like it could be combined into a single set of keys, where the id is whatever the last h* was that came before it, and where the h* elements are not listed in the grouping (so that they don't recurse). I would imagine something like:
<xsl:key name="kHeaders" match="*[not(self::h1 or self::h2)]" use="generate-id(preceding-sibling::*[self::h1 or self::h2][1])"/>

However, that leaves out the h2 elements from the list, which need to be present in the grouping for the previous h1. And if I relax the restrictions on the match to include the h1/h2 elements (and make the h1 templates also match h2), then I get the h2's re-listing the h1's and so on (somewhat expected).
An ideal solution is one that can be extended to work for h3, h4, and so on without a lot of effort. However, it does not need to include script elements for handling the generic h* elements. Simple instructions for how to add an additional layer would be sufficient.
Does anyone have some advice here?

A: This will do the trick:
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
  <xsl:output method="xml" indent="yes"/>

  <xsl:template match="/">
    <Root>
      <xsl:apply-templates select="//h1"/>
    </Root>
  </xsl:template>

  <xsl:template match="*[starts-with(local-name(), 'h')]">
    <xsl:variable name="lvl" select="number(substring-after(local-name(), 'h'))"/>
    <Topic>
      <Title>
        <xsl:value-of select="text()"/>
      </Title>
      <xsl:apply-templates select="//following-sibling::*[not(starts-with(local-name(), 'h'))
                           and preceding-sibling::*[starts-with(local-name(), 'h')][1] = current()]"/>
      <xsl:apply-templates select="//following-sibling::*[local-name() = concat('h', $lvl + 1)
                           and preceding-sibling::*[local-name() = concat('h', $lvl)][1] = current()]"/>
    </Topic>
  </xsl:template>

  <xsl:template match="*">
    <Paragraph>
      <xsl:value-of select="text()"/>
    </Paragraph>
  </xsl:template>
</xsl:stylesheet>

A: Below stylesheet(most of the essential code copied from this answer) would work when more headers are involved:
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
    <xsl:output method="xml" indent="yes"/>
    <xsl:strip-space elements="*"/>

    <xsl:key name="next-headings" match="h6"
          use="generate-id(preceding-sibling::*[self::h1 or self::h2 or
                                               self::h3 or self::h4 or
                                               self::h5][1])" />

    <xsl:key name="next-headings" match="h5"
          use="generate-id(preceding-sibling::*[self::h1 or self::h2 or
                                               self::h3 or self::h4][1])" />
    <xsl:key name="next-headings" match="h4"
          use="generate-id(preceding-sibling::*[self::h1 or self::h2 or
                                               self::h3][1])" />
    <xsl:key name="next-headings" match="h3"
          use="generate-id(preceding-sibling::*[self::h1 or self::h2][1])" />

    <xsl:key name="next-headings" match="h2"
          use="generate-id(preceding-sibling::h1[1])" />

    <xsl:key name="immediate-nodes"
          match="node()[not(self::h1 | self::h2 | self::h3 | self::h4 |
                           self::h5 | self::h6)]"
          use="generate-id(preceding-sibling::*[self::h1 or self::h2 or
                                               self::h3 or self::h4 or
                                               self::h5 or self::h6][1])" />

    <xsl:template match="/">
        <Root>
            <xsl:apply-templates select="html/body/h1"/>
        </Root>
    </xsl:template>

    <xsl:template match="p">
        <Paragraph>
            <xsl:value-of select="."/>
        </Paragraph>
    </xsl:template>

    <xsl:template match="h1 | h2 | h3 | h4 | h5 | h6">
        <Topic>
            <Title>
                <xsl:value-of select="."/>
            </Title>
            <xsl:apply-templates select="key('immediate-nodes', generate-id())"/>
            <xsl:apply-templates select="key('next-headings', generate-id())"/>
        </Topic>
    </xsl:template>

</xsl:stylesheet>


text:
Q: Every thing is true but fonts doesn't display I do some changes for website like:
More Secure, PageSpeed and etc
Every thing is true but fonts doesn't display!!!!
this is Url with Bad Display:
http://wellan.ir/index.php/ir/
another wonder still is here, in Url:
http://wellan.ir/index.php/en/
Font Displays truely!
I Check Css, Font-face, js & etc
No thing is wrong!
Any Suggestion?
please, see this image too:
Link 1 OR Link 2

A: Thanks a lot Sulthan Allaudeen, Finally I find problem and its solution.
Solution is here, I add this to .htaccess
Header set Access-Control-Allow-Origin "http://wellan.ir"
for multiple domain solution, see:
Access-Control-Allow-Origin Multiple Origin Domains?


text:
Q: LNK1181 Linker error, cannot open input file, on Windows 10 -- spurious, then solved I don't use visual studio -- just Make and command line.
My Makefile originally had
QT_LIB_DIR = C:\Qt\5.12.5\msvc2017_64\lib

with the link line containing
 /LIBPATH:$(QT_LIB_DIR)

This resulted in the link error.  The fix was simply to put quotes around the folder name:
QT_LIB_DIR = "C:\Qt\5.12.5\msvc2017_64\lib"

This is odd for various reasons:
1) The file separators are all back slashes.
2) There is no white space in the name.
3) When I copy and pasted the original command resulting from Make into a cmd.exe window, the link succeeded, even though the failing make command and successful pasted command are identical on the screen.
Is Make inserting some odd non-visible characters to the command line, but copy and paste turned them into harmless white space?  Do the quotes cause Link to be more careful?


text:
Q: helm template output showing values not being resolved I'm new to helm charts and K8s, so forgive me.  I'm working on a project that deploys an application project with several apps as part of it.  The previous dev that put the charts together was using a "find-and-replace" technique to fill in values for things like the image repository, tags, etc.  This is making our CICD pipeline development tricky and not scalable.  I'm trying to update the charts to use variables and values.yml files.  Most of it seems to be working, values are getting passed down to the templates except for one part and I can't figure out why.  Its a large project so I won't copy all the chart files. I'll try to lay out the important parts:
Folder structure:
helm
  project1
     dev
       charts
          app1
            templates
               *template files
            Chart.yaml
            values.yaml
          app2
            *same subfolders
          app3
            *same subfolders
       Chart.yml
       values.yml

Base Values.yml
artifactory_base_url: company.repo.io/repo_folder
imageversions:
  app1_tag: 6.1.2-alpine-edge
  app2_tag: 8.1.0.0-edge
  app3_tag: 8.1.0.0-alpine-edge
  app4_tag: 10.1.1-alpine-edge
  initcontainer: latest

App Values.yml file
app:
  image:
    repository: "{{ .Values.artifactory_base_url }}/pingaccess"
    tag: "{{ .Values.pa_tag }}"

deployment.yml template file
containers:
      - name: {{ .Chart.Name }}
        image: "{{ .Values.app.image }}"

I'm running the following helm template command to confirm that I'm getting the proper output for at least the app1 part before actually trying to deploy to the k8s cluster.
helm template app1 --set date="$EPOCHSECONDS" --set namespace='porject_namespace' --values helm/project1/dev/values.yaml helm/project1/dev/charts/app1
Most of the resulting yaml looks great, and it looks like the values I have defined in the base values.yml file are getting passed through in other areas like this example:
initContainers:
  - name: appinitcontainer
      image: "company.repo.io/repo_folder/initcontainer:latest"

But there is one portion that is populated from the deployment.yml template file that is still showing the curly braces for variables
containers:
  - name: app1
    image: "map[repository:{{ .Values.image_repo_base_url }}/app1 tag:{{ .Values.app1_tag }}]"
    imagePullPolicy: Always

I've tried making variations in all the files mentioned above to remove quotes, use single quotes, etc.  In those attempts I usually get a variation of the following errors:
"error converting yaml to json. did not find expected key"
"error mapping values"
I haven't been able to find a solution.  I'm assuming that the "helm template" command should not contain any braces like that, all variables and values should be resolved.  I'm hoping somebody can provide some tips of things I might be missing.

A: You're hitting two issues here.  First, .Values.app.image is a map containing the two keys repository and tag; that's why you get the weird map[repository:... tag:...] syntax in the output.  Second, string values in values.yaml aren't reinterpreted for Helm template syntax; that's why the {{ ... }} markup gets passed through to the output.
This in turn means you need to do two things.  To resolve the map, construct the string from the contents of the dictionary; and to resolve the templating markup inside the string values, use Helm's tpl function.
{{- $repository := tpl .Values.app.image.repository . }}
{{- $tag := tpl .Values.app.image.tag . }}
image: "{{ $repository }}:{{ $tag }}"

(You may find it useful to separate "repository", "registry" or "image", and "tag" into three separate parts, since probably all of your images are coming from the same repository; that would let you configure the repository in one place and customize the image name per component.  The bitnami/postgresql chart is one example of this setup.)


text:
Q: how to create realtime firebase subnodes android problems how to create realtime firebase subnodes
note I did not put the user changed because I have been trying to add from the mainactivity code and also because everyone I built to make this addition when creating the user went wrong.
Thank you very much in advance.
any help is welcome.
Hello i'm trying to create subnodes
within user
has
{
   "Users": {
     "Hr1riTVGQWWsKnOsT8n7wIBO7R63": {
       "address": "asdasd",
       "email": "a@a.com",
       "fullname": "asdasd",
       "helpsms": "123456",
       "phone": "55555555555"
     }
   }
}

wanted to create a node inside users called casino and inside the casino would have the subnodes of the casino inside user
time: with default value of 200 seconds
reward: with default value of 200
but when i try to modify my builder everything goes wrong when i click the button. can anybody help me
Button code:
   addButton.setOnClickListener(new View.OnClickListener() {
            DatabaseReference ref = FirebaseDatabase.getInstance().getReference();
            @Override
            public void onClick(View v) {
                FirebaseDatabase.getInstance().getReference("Users");
                ref.child("Users").child(userUid).addListenerForSingleValueEvent(new ValueEventListener() {
                    @Override
                    public void onDataChange(DataSnapshot dataSnapshot) {
                        for (DataSnapshot ds : dataSnapshot.getChildren()) {

                            ref.child(userUid).child("cassino").setValue(dataSnapshot);

                        }
                    }

                    @Override
                    public void onCancelled(DatabaseError databaseError) {

                    }
                });
            }
        });

my user.class
public class User {
    public String helpsms;
    public String email;
    public String phone;
    public String address;

    public User(String helpsms, String email, String phone, String address, String fullname) {
        this.helpsms = helpsms;
        this.email = email;
        this.phone = phone;
        this.address = address;
        this.fullname = fullname;
    }

    public String fullname;
}

A: Change this:
ref.child(userUid).child("cassino").setValue(dataSnapshot);

into this:
Map<String,Object> map = new HashMap<>();
map.put("address",dataSnapshot.child("address").getValue(String.class));
ref.child("Users").child(userUid).child("cassino").setValue(map);

Add the child("Users") and then add the values


text:
Q: Why is insertion sort not dynamic programming A dynamic programming problem has optimal substructure and has a solution that can be described by a recurrence relation.
A sorted list is the addition of an element to an already sorted list, so Insertion sort thus has optimal substructure. The recurrence relation could be described as
Sorted_List_n = Sorted_list_n-1 + next element

So why isn't insertion sort considered a dynamic programming algorithm? I understand how it is applied in Fibonacci numbers and in edit distance, but not really beyond that.

A: A given problem can be solved using Dynamic Programming (DP) if the problem has following two properties.
1) overlapping sub problems (osp)
2) Optimal sub-structure (oss)
Even though insertion sort algorithm has optimal sub-structure property, it does not have overlapping sub problems property. A bit elaborated explanation is as follows..
In, Fibonacci numbers calculation case, we are clearly having the above mentioned two properties.
osp : fib(5) calculation has fib(3) as its subproblem. At the same time, fib(4) calculation has fib(3) as its subproblem. But fib(5) = fib(4) + fib(3). If we blindly calculate fib(5) with out DP technique, we end up calculating fib(3) twice (one for fib(4) and one for fib(3) itself). Here, one of the overlapping subproblems is fib(3)
oss : In the same way, if we can calculate the solution to fib(4) and fib(3) optimally, then the solution to fib(5) as well can be calculated optimally. Because fib(5) is simply a sum of fib(4) and fib(3).
Now, let us try to check whether these two properties exist in insertion sort or not.
Let us say you are sorting an array of numbers {5, 2, 3, 1}.
osp : According to the recurrence that you are thinking the subproblems will be as follows..

*

*{5, 2, 3, 1}

*{5, 2, 3}

*{5, 2}

*{5}
If we observe closely, we can see that there are no two subproblems which are similar. That means the overlapping sub problems property does not exist.
oss : If we can sort an array of size (n-1) optimally, then we can as well sort an array of size (n) optimally. So optimal sub-structure property exist.
In summary, insertion sort algorithm does not have overlapping sub problems property. Hence it is not a DP solution.


text:
Q: Как правильно реализовать выбор нужного Activity? Есть приложение с активити авторизации и с активити для клиентских операций. Стоит ли создавать лаунчер-активити, который будет читать SharedPreferences и открывать нужную активити или есть другой, правильный способ?

A: Запускайте всегда активити авторизации, в onCreate() читайте свои настройки, если авторизация уже пройдена просто сразу открывайте следующие активити и это закрывайте если нет оставляйте это.
П.С. А вообще очень часто используют так званые SplashScreen активити, это просто заставка с логотипом что то вроде такого. Этот экран висит пару секунд и открывает следующий после себя. Можно создать такой экран в методе onCreate() запустить что то такое
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
        @Override
        public void run() {
            if (authorized) {
                Intent intent = new Intent(SplashScreen.this, ClientActivity.class);
                startActivity(intent);
                finish();
            }else {
                Intent intent = new Intent(SplashScreen.this, LoginActivity.class);
                startActivity(intent);
                finish();
            }
        }
    }, 2000);//Ставите сколько сек, 1000 = 1с.


text:
Q: Rolling jQuery into another library? I have a project that requires a custom JavaScript library to be included in end user's websites. Sort of a third party thing, think JavaScript tracking like Google Analytics.
We'll have no control over what other JS libraries/frameworks might also be loaded or what versions.
I'd like to be able to leverage jQuery's event delegation, selector and AJAX functionalities but:

*

*Not cause any conflicts with other libraries or other versions of
jQuery that might be loaded

*Not require the end user to have to think
about including jQuery separately.

So, rolling in all of jQuery sort of seems like overkill but again, event delegation, selector and AJAX are required. I know jQuery's sizzel engine is broken out in such a way that it's possible to include it in 3rd party libraries and there are plenty of tiny AJAX libraries but we need good event delegation support as well. Additionally, I foresee us needing to do some heavy DOM lifting with this library in the near future as well so it's arguable we do need most of jQuery's functionality.
Any suggestions on how to encapsulate jQuery in such a way that we don't trample over anyone's code? Also, how advisable is this? It does feel a tad iffy.
Also, what's the best wat to encapsulate it into another library? Is there a better way than this?:
(function(window){
    window.myNamespace = {
        _jq:null,
        init: function(){
            // Include jQuery
            myNamespace.setJq();
        },
        setJq:function(){
            /*! jQuery v1.8.2 jquery.com | jquery.org/license */
            (function(a,b){function G(a){...}}) // <- minified jQuery
            // Stash a local copy of jQuery
            myNamespace._jq = jQuery;
            // Return $ and jQuery namespace
            $.noConflict(true);
        }
    }
})(window)

(We intend on offering a version of the library without jQuery for those savvy enough to know that it's already loaded on their page and what version they're using)

A: Have a look at jQuery in Parts: https://github.com/mythz/jquip

A: What about dong a conditional load... Test if $ exists. If it does, don't load the script. If it doesn't, then load it.

A: You could use the following pattern to make sure that the jQuery is being passed in to the function and then you can map it to the local variable $ without issues.
(function(window,$){
  //use $ as a local jQuery variable
})(window,jQuery);


text:
Q: How to make multiple buttons on a GUI work Im creating a GUI program with multiple buttons. I'm only able to use one of the buttons at the moment. Here is my Button Listener class. I want to be able to use the "Test" button and then use the "Yes" or "No" button after. Let me know if you need to see any more of my code.
public class ButtonListener implements ActionListener
{
    public void actionPerformed(ActionEvent e)
    {
        if(e.getSource()==TestButton)
        {

            TestWord = (Text_Input.getText());

            StringBuilder RevTestWord = new StringBuilder();
            RevTestWord.append(TestWord);
            RevTestWord = RevTestWord.reverse();

            DisplayText = "Is " + RevTestWord + " a real word?";
            Test_Anadrome.setText(DisplayText);

            if(e.getSource()==YesButton)
            {
            DisplayText = "Word added to Anadrome list.";
            Test_Anadrome.setText(DisplayText);
            }

            if(e.getSource()==NoButton)
            {
                DisplayText = "Type a different word and press the 'Test Word' Button.";
                Test_Anadrome.setText(DisplayText);
            }

        }
    }
}

Sorry I'm pretty new to Java.

A: It looks like your if/else statements for your YesButton and NoButton are inside of your if statement for TestButton, so as a result those statements are only being checked if source==TestButton. Try moving this code outside of the if statement:
            if(e.getSource()==YesButton)
            {
            DisplayText = "Word added to Anadrome list.";
            Test_Anadrome.setText(DisplayText);
            }

            if(e.getSource()==NoButton)
            {
                DisplayText = "Type a different word and press the 'Test Word' Button.";
                Test_Anadrome.setText(DisplayText);
            }

A: You need to have all your testing at the same level.  The nested ifs are causing problems.  And remember to use if/else.  No sense in continuing to do other checks if the previous one succeeds.
You can also set the ActionCommand which is a String.  For components that use the actionListener, you can do for example button.setActionCommand("mycommand").
Then in the actionPerformed(ActionEvent e) you can do
String cmd = e.getActionCommand();
That allows you do discern between buttons or other components without having direct access to their instance.
If you don't set the ActionCommand it defaults to the button's text.


text:
Q: Using BSCAN_SIME2 I have instantiated the BSCANE2 in my tutorial designs in order to do easy controls and commands into the trial designs, and in order to simulate this I will use the BSCAN_SIME2.
However, I do not seem to find any documentation on this SIME2.
My trials so far on simulating has shown that it does set the SHIFT signal when going through the DR Shift states, but I have not yet been able to get a SEL signal from issuing a USER1 JTAG instruction.
Anyone had success using this simulation component?
Up until now I have just used very simple structures in my test bench. I dont want to build a larger design before I know exactly how to stimulate it.
Thanks.


text:
Q: WM_MOUSELEAVE and Parent-Child windows In a main window hwndFrame, it has a child hwndChild which has a child hwndDescendant. These two childs have no non-client area. hwndDescendant occupy most of the region of hwndChild, so hwndChild looks like just a "boundry" of hwndDescendant. This "boundry" has width 4 pixels only. (But the size of hwndChild is much big than this).
I want to track WM_MOUSELEAVE for 'hwndChild'. If I move the mouse slowly, this works fine.
But if I move mouse very quickly from hwndFrame to hwndDescendant or vice versa, hwndChild didn't receive WM_MOUSEMOVE, hence neither WM_MOUSELEAVE.
Also when mouse move from hwndChild to either hwndFrame or hwndDescendant will generate WM_MOUSELEAVE. But I wish that when move from hwndChild to hwndDescendant don't generate WM_MOUSELEAVE.
I don't want to solve this issue by subclass the window procedure of hwndDescendant, because if hwndChild has many childs, it is not a good way.
SetCapture method is not preferable. In this case, what is the best way taht I can deal with this issue?


text:
Q: Supplying credentials safely to a RESTFUL API I've created a RESTful server app that sits and services requests at useful URLs such as www.site.com/get/someinfo. It's built in Spring.
However, these accesses are password protected. I'm now building a client app that will connect to this RESTful app and request data via a URL. How can I pass the credentials across? Currently, it just pops up the user/password box to the user, but I want the user to be able to type the username and password into a box on the client app, and have the client app give the credentials to the RESTful app when it requests data. The client is built using Struts.
Cheers
EDIT - I don't think I made the question clear enough. I'm already forcing HTTPS, my question is more, in-code, when I'm requesting data from www.site.com/get/someinfo, how do I pass my credentials alongside making the request?

A: You more or less have 3 choices:

*

*HTTP Auth

*Roll your own protocol, ideally HMAC challenge/response based

*OAuth
OAuth is currently susceptible to a variation of a phishing attack, one that is largely undetectable to the target. As such I wouldn't recommend it until the protocol is modified.
OAuth should also be a lesson about how difficult it is to design secure protocols, and so I'm hesitant to reccomend the roll your own route.
That leaves HTTP auth, which is likely best if you can use it.
All that said, almost everything on the internet uses form based authentication, and many don't even bother with https for transport level security, so perhaps simply sending the password text in the clear is "good enough" for your purposes. Even still I'd encourage using https, as that at least reduces the dangers to a man in the middle attack.

A: If you can add HTTP headers to your requests you can just add the Authorization header:
Authorization: Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ==

where you're using basic authentication and the QWxhZGRpbjpvcGVuIHNlc2FtZQ== bit is "username:password" base64 encoded (without the quotes). RFC 2617

A: Well, https has nothing to do with authentication, it's just transport-level encryption.
if you interact with an HTTP api, be it that it's https or not, and the dialog box pops up, it means its using HTTP authentication, either basic or digest. If your client instantiates an http client to read data from those "services", then you can pass those credentials when you instantiate the object.
If you use client-side script, XmlHttpRequest supports http authentication as well.
So in terms of code, how you pass the credentials to the RESTful services is dependent on the http client you're using (the object you instantiate to retrieve the data). You can simply collect such a username / password yourself from the client, and use it to call the other service.

A: look at existing solutions. In this case, oauth


text:
Q: Disable Highlighting of Strings in Visual Studio All of my strings in visual studio are highlighted (see screenshot)
This makes it very difficult when i'm actually highlighting something or using the find functionality.
I cannot find an option for this anywhere, anyone know how to disable this?
This is Visual Studio Community 2017

A: Go to Tools > Options > Fonts and Colors. On the Display Items, find String and change the Item background color to whatever the color of your editor background is.


text:
Q: Installing Visual Studio 2010 AFTER Visual Studio 2012 I had Visual Studio 2012 installed on my new development computer and it worked fine. Without thinking I then installed VS2010 onto the computer which already had the 2012 install. 2012 continues to work correctly but 2010 cannot compile any of my previous working source code and it seems unable to locate any of the correct libraries.
For instance in a simple C++ hello world program I get the following error
fatal error C1083: Cannot open include file: 'iostream': No such file or directory

I have tried un-installing both, installing 2010 first then 2012 but the same problems still occur. I have also made sure it is using platform toolkit v100 but it seems to make no difference.
I have also tried repairing VS2010 to no avail.
Has anyone else experienced the same issues and if so how did they manage to fix it?

A: I'd guess it has something to do with VS2012's new v110_xp platform toolset which uses an SDK similar to 7.1.  For my older projects that need 2003 Server and XP support I use that toolset now with VS2012 instead of the default toolset with VS2008 or VS2010 so I no longer need the older Visual Studios.  It might solve your problem as well.


text:
Q: Shippo API error on import We are implementing the shipping API from Shippo. On exports everything seems to work, but on import we get the following error from UPS in test mode:

120120: Hard: The country associated with Shippers ShipperNumber must be the same as the shipments Shippers country.

We did notice the same error reported on the UPS developer forum, but no solution was given. Shippo say UPS must enable import on my account. UPS says:

Your account is active and enable for every function.

A: The error message indicates that your UPS account is not enabled for shipments from the outbound country you have requested. While your UPS account number might be enabled "for every function" (e.g. rating, label purchase, pickup, etc.) it might not be enabled for all outbound countries.
I'd recommend you reach out to UPS and ask how to to get your account enabled for shipments from this country. It's not unlikely that you'll get a separate account number for this country.


text:
Q: How to place percentage orders with Binance API and Python-CCXT? I'm playing with Binance API to make my trading bot with Python 3.6. and CCXT library (here you find the docs ).
One very useful thing they have in their site is the capability to place orders for a percentage of your current balance:
for example if I'm lookin at BTC/USDT crypto coin pair, and I have 50 USDT on my account, I can choose between buying N amount of BTC or using 100% of my account's USDT for buying, consequently buying the maximum amount of BTC I can.
I read the docs many times, but I can't find the option to do these "percentage of balance" orders with the API in any way: the only thing I can do is passing a float to the order function.
This is how i place orders now:
amount = 0.001
symbol = "BTC/USDT"

def buyorder(amount, symbol): # this makes a market order taking in the amount I defined before, for the pair defined by "symbol"

    type = 'market'  # or 'limit'
    side = 'buy'     # or 'sell'
    params = {}      # extra params and overrides if needed
    order = exchange.create_order(symbol, type, side, amount, params)

Do anyone know if there is a built-in capability to do
a percentage order? If API gives no way to do so, would you suggest some workarounds?
I want to be able to give to the API percentage of my current balance as an amount, so I can always use the full of it without having to update when fees are detracted

A: Use a custom function like this:
 def get_max_position_available():
    to_use = float(exchange.fetch_balance().get('USDT').get('free'))
    price = float(exchange.fetchTicker('BTC/USDT').get('last'))
    decide_position_to_use = to_use / price
    return decide_position_to_use

A: I don't know of any Binance API function that does that, but you can try something like this:
# You ask for the balance
balance= client.get_asset_balance(asset='USDT')

# set the percentage or fraction you want to invest in each order
portion_balance = float(balance['free']) * 0.35

# you assign the created variable in the quantity of your order
sell_market = client.order_market_sell(
    symbol= 'ETHUSDT',
    quantity= portion_balance)

Greetings ;)


text:
Q: Logging data without using a normal SQL database? I am currently logging every "failure" on my site (login/signup/etc) to a database so I can monitor what is giving my users a hard time - or which ips/users are doing suspicious things.
However, I find that I only really need the data for about a week or so since I check it every day and, at most, need to see the activity from the past week.
I was thinking that perhaps I should try to save some of the load my database is taking from all this logging and place the data in something like memcached or couchdb. However, I'm not sure how I could query the data into result sets.
How could you use a key-value store or document-database to monitor logs and track relations between activity? And is it even worth it to add another data store to the server or just keep the database from handling it? I mention memcached and couchdb because both can have very light RAM usage if needed (unlike mongodb and redis).
Let me give an example. IP 0.0.0.0 failed login 37 times in 3 hours (each recorded) it also failed to reset a password for a valid email 84 times in 2 hours. Thanks to my logs I can now research (and block) this bot. On the other hand, I see that out of the 5827 users registered - there were 2188 failed register attempts. This tells me that there is something wrong with my signup form causing many of the people to fail the form at least once.
Again, the bounty is for a working example of using key-value or document store to log data.

A: Key-value stores or document-based databases are not a panacea. If you want to play with them just for fun, then it's fine, but if you want to do this to save some of the load my database, I highly recommend not to waste your time. Let me explain.
First, you must realize that these data structures recently became popular because of need for scalability for ultra-large sites (LinkedIn, Facebook, etc.). And more importantly, they gave that portion of scalability at a price of convenience.
Think of these new generation data stores as of stripped down databases which don't have inter-table relationships and SQL layer. So writes become cheap as there's no need to worry about dependant data. But reads can then become expensive (if you don't have an index) as you have to deal with O(n) complexity. This is OK for cases where key id is always known or for post-processing jobs where response time isn't a big deal. Or, you can have fast searches with index on a flat document, but don't expect foreign keys to be handled automatically.
If you were to log data into a k-v store, you could possibly solve your query problem by logging entire record into a k-v store and logging keys (ids) for "failure" cases separately (e.g. could be stored under special key). Afterwards, you could locate the offending records in O(1) time. Need to quickly lookup different cases (failed to reset password, failed to register)? No problem, just add another "special" key and reindex all existing data :) You have been warned about the loss of convenience!
If you were to log data into a document store, you could only benefit if your log records are flat (de-normalized). Otherwise I don't see how could you store the data in them it the first place. You could then create indices based on event type and query by it. I however don't see any big difference/improvement from what you have now.
But think about it. You will probably spend weeks (if not months) rewriting, debugging and  testing existing logging code. You will have to define different backup strategies. You will have pain explaining that to your sysadmins, bosses, etc. Or you can buy a few hundred $ worth of SSD disk and achieve the same, if not better, results.

A: So, if I understand you correctly:

*

*You have a rolling 50-70 million records in your logging data store.

*The read latency is not critical (sub-second) as you check it daily, based on triggers such as site anomalies or customer requests.

*Your logging database and OLTP database currently reside on the same server.

*Based on your profile and your answers above, I'm going to guess that it's MySQL, not MSSQL that you're using.

*I also assume that since you cap your logging database at seven days, backup is not something that you care about (as much) with it.

A couple things about non-relational solutions and document-oriented stores in particular:
1. They don't require you to be Facebook or Twitter. Setup for both MongoDB and CouchDB does not have to be an enterprise undertaking.
2. They are well-suited to storing log and event data.
3. Both CouchDB and MongoDB will take advantage of as much memory as is available to cache their indexes.
4. MongoDB offers a "capped" collection, which sets size limits on the data stored and then rolls of data rows/messages as they age out. This seems particularly suited to your needs, were you to implement MongoDB, as it doesn't require you to continually run heavy deletes against your relational database.
5. The query interface is materially different from the SQL you are used to.  Both can take JSON-based query documents and bring back results. MongoDB's function library is easier for a relational developer to pick up, IMHO.
That said, here's the rub:
1. If you aren't going to set it up on a different machine, you won't solve the load issue. Non-relational stores are not as efficient with disk or memory as your MySQL instance is.
2. Both store data in JSON.  If your logging component doesn't speak JSON, you'll need to code that.
3. If you rely on regex, Couch won't do it.  Mongo will.
Mindas is right when he says that non-relational stores achieve their scale by ripping out the foundational aspects of relational stores: ACID transactions, strongly-typed data, well-defined structures, optimized join relations, efficient data storage.
That said, things like log records that have a finite lifespan, variant content and a flat structure are ideal for a document store and don't require as much infrastructure.  I've spent literally decades building relational structures that work well for 90% of a system and shoe-horning the rest in through a series of work-arounds.
For me, non-relational stores offer the chance to keep flat, schema-variant data in a more natural form.
I hope this helps you find a path that works for you.

A: Just write to a log file and analyse it offline. Logging is a solved problem, and writing a line of text to a file on disk is about as cheap, IO and CPU-wise, as you can possibly get. Log rotation is also a solved problem, and there's really no point in reinventing that wheel.
Once the log data is on disk, you can copy it off to another machine for parsing and analysis using whatever toolkit you want, and if you want to use a document store, that's the place to introduce it. There's no need to burden your front-facing production machines with that job.


text:
Q: Colored grep causing trouble when run in subprocess (OS X) I'm having troubles in doing simple stuff with grep in my Mac. I'd like to rename a file, and for that I use grep and sed.

*

*If I don't use grep, it works fine.

*

*If I use grep, it doesn't work: mv shows a weird error.

For what I understand, the reason may be the colored grep I am using, and then mv uses not the filename, but the code for displaying the colored filename in the console (as elm content is a colored yum.txt, instead of a normal one).
Is this the reason? What can I do?

A: You are right, those strange characters are indeed color codes. You can search for the --color= option either in GREP_OPTIONS environment variable (printenv) and/or your user defined aliases.
Then just change --color=always to --color=auto; with the --color=auto option set, grep should display color codes only when the standard output is connected to a terminal and plain text otherwise.


text:
Q: Invisible border applied to inputs on Apple IOS devices Inputs are having an almost invisible border applied on iOS devices, on all browsers.
How do I remove or prevent this styling from being applied?
const StyledInputString = styled.input`
    width: 40%;
    background: #fff;
    font-size: 18px;
    color: #8f8fa1;
    line-height: 1.2;
    font-family: 'Montserrat', sans-serif;
    outline: none;
    border: none;
    border-bottom: 1px solid black;
    padding-left: 20px;
    height: 56px;
    margin-bottom: 20px;
    &:focus {
      border-bottom: 2px solid #03a900;
      color: black;
    }

Example image with the styles applied:

A: Try using border-radius property.
input {
    border-radius: 0;
}

Also try setting
input {
    -webkit-appearance: none;
}


text:
Q: Defining a command to define commands where the name uses the argument using xparse Using xparse I want to create a command which defines other commands. However I want the secondary command to consist of text and then the argument to the first command. For example
For example in the following
\documentclass{article}
\usepackage{xparse}
\begin{document}

\ExplSyntaxOn
\DeclareDocumentCommand{\DeclareTest}{m}{%
%
\DeclareDocumentCommand{\csname test#1\endcsname}{}{This is a #1 test}
}
\ExplSyntaxOff

\DeclareTest{work}
\testwork

\end{document}

I would like \testwork to be a command that evaluates to This is a work test. However when I do this I get an "xparse/bad-arg-spec" error and I am not sure why.

A: As is the case for \newcommand, \DeclareDocumentCommand and relatives are designed to take ta command name as the first argument. At present, if you want to construct the name you therefore need to use \expandafter
\DeclareDocumentCommand\DeclareTest{m}{%
  \expandafter\DeclareDocumentCommand\csname test#1\endcsname{}{This is a test}%
}

The reason that at the moment there is not a 'variant' available which does this internally is that 'dynamic' commands are problematic from a conceptual point of view. The syntax of xparse is intended to make it clear within the code what new commands are begin created for a document, and thus constructing them 'on the fly' is really not what the aim is. This is however I think still and area which needs discussion based on good examples from real use cases.


text:
Q: Django objects.filter multiple filters The user can select fields to filter by, I need to filter by only those fields but there can be 3 fields.
The user selects all three options:a, b and c
Foo.objects.filter(a=1,b=2,c=3), good

What if the user selects only 1 option or 2 options ?
Foo,objects.filter(a=1, b=2, c=not selected)

How can I do this to only filter by the selected choices. THis comes from a post to the view, and looks like this if not selected:
a=1,b=NaN,c=3

So b was not selected and I would not like to inlclude it in my filter,
Foo.objects.filter(a=1,c=3)

Or can I perhaps so a filter that is basically a "all" selector
So as per above:
Foo.objects.filter(a=1,b=%,c=3)

A: You can use a keyword argument dict:
filterargs = { 'a': 1, 'b': 2, 'c': 3 }
Foo.objects.filter(**filterargs)

then to only filter on a and b:
filterargs = { 'a': 1, 'b': 2 }

or a and c:
filterargs = { 'a': 1, 'c': 3}


text:
Q: How can I Host my files present in resources through Spring Boot App I have a requirement in which I have to store some files within the Spring Boot Application and on API hit I should provide a URL for each file present within the Spring Application.
Any advice on how can I achieve it, without any Storage Service like S3.
Java Files and the hosting files should be within the same project and same server.
Thanks in advance.