text:
Q: select and upload multiple files to ajax I'd like to be able to select a series of images, then upload the data through ajax call. Below is my html. Am unable to append the files in for loop.
 <form name="nameform" method="POST" enctype="multipart/form-data">
    <input id="file_input" type="file" name="files[]" multiple>
    <input type="button" name="button" value="Submit" onClick="getInfo(this.form)" />
 </form>

  var oMyForm = new FormData();
  var filelenth = file_input.files;
  for (var i = 0; i < filelenth.length; i++) {
    var fileCheck = file_input.files[i];
    if (!fileCheck.type.match('image.*')) {
      continue;
    }
    oMyForm.append('files[]', fileCheck, fileCheck.name);
  }

  $.ajax({
    url: 'URL',
    data: oMyForm,
    dataType: 'json',
    processData: false,
    contentType: false,
    type: 'POST',
    success: function(data) {
      alert(data);
    }
  });

Any suggestions?

A:  var data2 = new FormData();
    $.each($("#attachmentInfo :file"), function(i, file) {
        data2.append('attachmentFiles', file.files[0]);
    });

        $.ajax({
            type: 'POST',
            contentType: false,
            processData: false,
            dataType: 'text',
            url: 'savefile2.html',
            data: data2,
            success: function(responseData, textStatus) {

            },
            complete: function(textStatus) {

            },
            error: function(responseData)
            {

            }
        });


text:
Q: C# how to change bitmap image color and apply anti-aliasing I am working on a flowchart making application and it involves changing the color of images with transparency(png). I've been searching for hours about workarounds and it's either that it's not what I'm looking for or I can't make it work.
First, let me show you the codes and how I do it. I removed the parts of the code that are unrelated to the question.
This is the class where I "create" the flowchart symbols. I inherited the Label class because I need text centered on the symbols. I use images in .png format located inside my Resources folder and change their color according to what the user wants.
namespace PF2
{
    public class Terminal : Label
    {
            public void createTerminal(int x)
            {
                this.Width = 250;
                this.Height = 100;
                this.Name = "Terminal" + x;
                this.AutoSize = false;

                Bitmap resized = new Bitmap(Properties.Resources.shapeTerminal, new Size(this.Width, this.Height));
                this.Image = Globals.ChangeColor(resized, Color.Yellow);

                this.Text = this.Name;
                this.TextAlign = ContentAlignment.MiddleCenter;
            }
     }

}

Here is the color changing algorithm I use (found this on stackoverflow as well):
namespace PF2
{
    public static class Globals
    {
        public static Bitmap ChangeColor(Bitmap scrBitmap, Color newColor)
        {
            Color actualColor;
            Bitmap newBitmap = new Bitmap(scrBitmap.Width, scrBitmap.Height);
            for (int i = 0; i < scrBitmap.Width; i++)
            {
                for (int j = 0; j < scrBitmap.Height; j++)
                {
                    actualColor = scrBitmap.GetPixel(i, j);
                    if (actualColor.A > 150)
                        newBitmap.SetPixel(i, j, newColor);
                    else
                        newBitmap.SetPixel(i, j, actualColor);
                }
            }
            return newBitmap;
        }
    }
}

And finally, how I call my class on my form
int x = 0;
private void btnTerminal_Click(object sender, EventArgs e)
{
    Terminal newSymbol = new Terminal();

    newSymbol.createTerminal(x);
    newSymbol.Parent = tabPage1;

    newSymbol.Location = new Point(newSymbol.Width * x + 4, 0);
    x++;
}

This is how my image looks like whenever I don't apply the color changing algorithm. It just sets the default image located in my Resources folder.
Algo not applied
This is how my image looks like whenever I apply the color changing algorithm. I want to apply anti-aliasing to make the edges look smooth like the original but I don't know how.
Algo applied
I stumbled upon  Interpolation while working on this but I can't make it work either. I would really appreciate it if someone could help me solve this problem with minimal changes in the code. Any alternative ways would be good as well as long as it doesn't involve 3rd party software. Thank you very much.

redpajama_set_name: RedPajamaStackExchange


text:
Q: PJSIP is Not Logging (Android) I am making my own app with PJSIP and PJ_LOG is not working (calling works).
Code is below, please HELP!!!
Thanks!
status = pjsua_create();
if (status != PJ_SUCCESS) error_exit("Error in pjsua_create()", status);
/* Init pjsua */
{
pjsua_config cfg;
pjsua_logging_config log_cfg;

pjsua_config_default(&cfg);
pjsua_logging_config_default(&log_cfg);
cfg.cb.on_incoming_call = &on_incoming_call;
cfg.cb.on_call_media_state = &on_call_media_state;
cfg.cb.on_call_state = &on_call_state;

__android_log_print(ANDROID_LOG_DEBUG,"INIT","PJ_LOG_MAX_LEVEL %d", PJ_LOG_MAX_LEVEL); //PRINT 5!!!

status = pjsua_init(&cfg, &log_cfg, 0);

if (status != PJ_SUCCESS) error_exit("Error in pjsua_init()", status);
}
__android_log_print(ANDROID_LOG_DEBUG,"INIT","PJ_LOG_MAX_LEVEL %d", PJ_LOG_MAX_LEVEL);//PRINT 5!!!

PJ_LOG(1,(THIS_FILE, "Trying log %d", 1));//NOT PRINTING
PJ_LOG(2,(THIS_FILE, "Trying log %d", 2));
PJ_LOG(3,(THIS_FILE, "Trying log %d", 3));
PJ_LOG(4,(THIS_FILE, "Trying log %d", 4));

A: The problem you have is different logging tools using (android and pjsip). For android you have to use __android_log_print only. No other works. But to catch pjsip logging output you have to override pjsip log writer:
#include <android/log.h>

extern "C" {
    static void log_writer(int level, const char *data, int len)
    {
        __android_log_write(ANDROID_LOG_INFO, "pjsua", data);
    }
}

/** Callback wrapper **/
static void on_cli_config(pjsua_app_config *cfg)
{
    pjsua_cb_orig = cfg->cfg.cb;
    cfg->log_cfg.cb = &log_writer;

    /* Override pjsua callback, e.g: to install renderer view */
    cfg->cfg.cb.on_call_media_state = &on_call_media_state;
}

You can found this example with pjsua sources: pjsip-apps\src\pjsua\android\jni\pjsua_app_callback.cpp


text:
Q: Element will not stay centered, especially when re-sizing screen My problem is that I cannot horizontally center a triangle pointer.
Well, I can center the pointer for some window sizes, but when I shrink or extend the window it places it in the wrong place again.
What am I missing?

body {
  background: #333333;
}
.container {
  width: 98%;
  height: 80px;
  line-height: 80px;
  position: relative;
  top: 20px;
  min-width: 250px;
  margin-top: 50px;
}
.container-decor {
  border: 4px solid #C2E1F5;
  color: #fff;
  font-family: times;
  font-size: 1.1em;
  background: #88B7D5;
  text-align: justify;
}
.container:before {
  top: -33px;
  left: 48%;
  transform: rotate(45deg);
  position: absolute;
  border: solid #C2E1F5;
  border-width: 4px 0 0 4px;
  background: #88B7D5;
  content: '';
  width: 56px;
  height: 56px;
}

great distance

A: You have your arrow centered with left:48%. This positions the arrow near the center of the container based on the arrow element's left edge.
In other words, assume you used left:50% (which is the correct way to go), this doesn't center the arrow element in the container. It actually centers the left edge of the element in the container.
In the image below a marker is centered on the page using text-align:center.
For comparison, see your arrow centered with left:50%.

The element is positioned center-right. This misalignment becomes more noticeable as the window gets smaller.
As a result, it is common to see centered, absolutely positioned elements use the transform property:
.triangle {
   position: absolute;
   left: 50%;
   transform: translate(-50%,0);
}

The transform rule tells the triangle to shift itself back by 50% of its width. This makes it perfectly centered on the line. Now it emulates text-align:center.

In translate(-50%,0), the first value targets the x-axis (horizontal), the other applies to the y-axis. An equivalent rule would be transform:translateX(-50%) (there's also transform:translateY()).

As an aside, here's how to center an element both horizontally and
  vertically using this method:
.triangle {
   position: absolute;
   left: 50%;
   top: 50%;
   transform: translate(-50%,-50%);
}

Note: If you were using right: 50% or bottom: 50%, the respective translate values would be 50% (not negative).

In this particular question, however, an issue arises because transform:rotate(45deg) is also in the declaration block. Adding a second transform means the first one is ignored (per the cascade).
So, as a solution, try this:
.container::before {
    left: 50%;
    transform: translate(-50%,0) rotate(45deg);
}

By chaining functions together, multiple functions can be applied.
Just note that order matters. If translate and rotate were reversed, the triangle would first rotate 45 degrees and then shift -50% along the rotated axis, breaking the layout. So make sure that translate goes first. (Thanks @Oriol for pointing this out in the comments.)
Here's the full code:

body {
    background: #333333;
}

.container {
    width: 98%;
    height: 80px;
    line-height: 80px;
    position: relative;
    top: 20px;
    min-width: 250px;
    margin-top: 50px;
}

.container-decor {
    border: 4px solid #C2E1F5;
    color: #fff;
    font-family: times;
    font-size: 1.1em;
    background: #88B7D5;
    text-align: justify;
}

.container::before {
    top: -33px;
    left: 50%;
    transform: translate(-50%,0) rotate(45deg);
    position: absolute;
    border: solid #C2E1F5;
    border-width: 4px 0 0 4px;
    background: #88B7D5;
    content: '';
    width: 56px;
    height: 56px;
}

great distance

jsFiddle

A: You could potentially use the new CSS3 calc() function which allows you to do arithmetic to figure out the center point.
To get your center point, the calculation will have to be:
50% - (56px / 2)

So this ends up being
50% - 28px

Putting this into the calc() function should then figure it out within the browser and position it perfectly in the center.

body {
  background: #333333;
}
.container {
  width: 98%;
  height: 80px;
  line-height: 80px;
  position: relative;
  top: 20px;
  min-width: 250px;
  margin-top: 50px;
}
.container-decor {
  border: 4px solid #C2E1F5;
  color: #fff;
  font-family: times;
  font-size: 1.1em;
  background: #88B7D5;
  text-align: justify;
}
.container:before {
  top: -33px;
  left: calc(50% - 28px);
  transform: rotate(45deg);
  position: absolute;
  border: solid #C2E1F5;
  border-width: 4px 0 0 4px;
  background: #88B7D5;
  content: '';
  width: 56px;
  height: 56px;
}

great distance


text:
Q: QML ShapePath clear path elements I want to remove all path elements from my ShapePath. Since pathElements is a Qml list, the only way to modify it is by setting it to a new Javascript array. Therefore, I expected to be able to clear it by just assigning an empty array to it.
I tried path.pathElements = [], which does not work for me.
Then I tried path.pathElements = null, which does work (PathLine is no longer drawn), but it prints this ugly error message: QObject::connect: Cannot connect (nullptr)::changed() to QQuickShapePath::processPath()
Any other ideas?
Code to reproduce:
Shape {
    anchors.fill: parent

    ShapePath {
        id: path

        strokeWidth: 2
        strokeColor: "green"
        fillColor: "green"

        Component.onCompleted: path.pathElements = []

        PathLine { x: 50; y: 50 }
    }
}

A: I filed a bug report at Qt and they confirmed my bug.
The workaround until this gets fixed is to first assign null, followed by [].
Shape {
    anchors.fill: parent

    ShapePath {
        id: path

        strokeWidth: 2
        strokeColor: "green"
        fillColor: "green"

        Component.onCompleted: {
            path.pathElements = null
            path.pathElements = []
        }

        PathLine { x: 50; y: 50 }
    }
}


text:
Q: The conditional expectation of exp(XY) given Y $ X \sim N(0;\sigma^2) $ and Y is a random variable that is independent of X.
How do I compute $ \mathbb{E}[e^{XY}|Y] $ ?

A: Let $f(x,y)=e^{xy}$ and $g(y)=E[f(X,y)]$. By the Independence Lemma,
$$
E[f(X,Y)|Y]=g(Y).
$$
So let's compute $g(y)$:
$$
g(y)=E[f(X,y)]=E[e^{yX}]=\exp(\frac{1}{2}\sigma^2y^2)
$$
where we have noted $E[e^{yX}]$ is just the moment generating function of $X$ evaluated at $y$. The final answer is then $g(Y)=\exp(\frac{1}{2}\sigma^2Y^2)$.

To derive $E[e^{yX}]$ note that
\begin{align*}
E[e^{yX}]&=\int(2\pi\sigma^2)^{-1/2}\exp(yx)\exp(-\frac{x^2}{2\sigma^2})dx\\
&=\exp(\frac{1}{2}\sigma^2y^2)\int(2\pi\sigma^2)^{-1/2}\exp(-\frac{(x-y\sigma^2)^2}{2\sigma^2})dx\\
&=\exp(\frac{1}{2}\sigma^2y^2).
\end{align*}
The integral in the second line evaluates to $1$ because $x\mapsto(2\pi\sigma^2)^{-1/2}\exp(-\frac{(x-y\sigma^2)^2}{2\sigma^2})$ is the density function of $N(y\sigma^2,\sigma^2)$.


text:
Q: Firefox addon to see the request Is it possible to see the request which my browser send to the server. Or if it's some addon for firefox.

A: Firebug for firefox or fiddler standalone

A: webdeveloper addon
install it and in the "forms" tab see the "convert form methods".
Download it from : https://addons.mozilla.org/en-US/firefox/addon/60/

A: All the answers given so far are good, but I really like HttpFox, personally.

A: You can check Live HTTP Headers

A: I just use the Web Developer Tools in Firefox. You can easily view the request using Web Console (Ctrl+Shift+K)
In addition, if you are interested in exploring the effects of various headers, such as say you are interested to tamper with/ block those requests, you may have a look at the firefox extension Tamper Data.


text:
Q: Are there finite decimal numbers that cannot be represented by fixed point and /or floating point types? Let's be specific and talk about finite 32 bit decimal numbers, AKA any number which can fit within 32 bits, i.e not 1/3 as the fraction part continues infinitely like 0.333333....
Are there finite, 32 bit decimal numbers which cannot be represented by either Floating Pint numbers or Fixed Point integers? If the answer is yes, how can I figure out if a decimal number can be represented accurately by these two types or not?


text:
Q: Netstat -i redirection problem When I run this command netstat -t 1 -i 2>&1 > $NETStat_OUT_FILE & inside a script , the output of netstat does not get redirected to the file.. Could any one find a solution for this ?

A: What's the whole line? Chances are the problem is in the declaration of the $NETStat_OUT_FILE variable, because the rest seems to work normally.

A: Does the file get created at all?  Try changing "$NETStat_OUT_FILE" to "${NETStat_OUT_FILE:?}" to catch the possibility of a typo.  It's possible that the output is being buffered, so that you won't see anything in the file until after some block of text (probably 512 bytes) has been buffered and flushed.


text:
Q: Windows Phone 8 Push Notification (MPNS) Server Code Windows Phone 7 has the MpnsRecipe NuGet package which you can use to send push notification messages to the Microsoft Push Notification Service (MPNS) on the server side. However, this package has not been updated for Windows Phone 8.
http://nuget.org/packages/MpnsRecipe
What is the equivelant for Windows Phone 8? I want to make use of the new wide tiles but I can't find any code online to get me started. All I can find is the XML format for the new messages on MSDN and I'd rather not have to write my own if there is a ready made package available.

A: Most WP7 projects should just work on WP8. Did you try to use the NuGet package and something didn't work? Did you forgot to unblock the web downloaded DLLs or did you forgot to update your NuGet package manager.

A: Check out PushSharp: https://github.com/Redth/PushSharp It appears to have been updated for the new notification payload formats in Windows Phone 8.


text:
Q: python develop non-greedy regex to match specific pattern several times I am about to develop a regex for a pattern given in a file I want to process.
The file contains several articles, which all follow a similar pattern:

*

*start with a line i.e. newline

*then have some non-word characters on a line followed by "Dokument xx von xx" and a newline

*that is followed by a body of characters

*ends with two newlines, followed by a line with non-word characters followed by "Copyright" followed by more characters and a new line

*one optional line containing non-word characters followed by more characters and a new line

*finally one line containing non-word characters followed by either "All Rights Reserved" or "Alle Rechte vorbehalten" and a new line

I try to come up with a non-greedy regex, that accurately matches the start, body, and end of the article(s).
For 1-4 I have ^n\W+Dokument.+?[\r\n][\r\n]\W+Copyright[^\n]+\n
What is necessary for 5-6?
Do I actually need a dotall flag if I aim to use this regex as proposed to match the pattern several times in a file?
I have been on this all day. Can someone with a fresh mind show me the missing bits?
Cheers,
Andrew

A: You can use the following:

*one optional line containing non-word characters followed by more characters and a new line

(\W+?(?:(?!All|Alle).)+?\n)?

*one line containing non-word characters followed by either "All Rights Reserved" or "Alle Rechte vorbehalten" and a new line

\W+(All Rights Reserved|Alle Rechte vorbehalten)\n

Combining 1-6:
^\W+Dokument.+?[\r\n][\r\n]\W+Copyright[^\n]+\n(\W+?(?:(?!All|Alle).)+?\n)?\W+?(?:All Rights Reserved|Alle Rechte vorbehalten)\n

See DEMO


text:
Q: What is the optimal current for charging two 12V batteries in series? I have to charge two 12 V, 184 Ah lead-acid batteries in a series circuit. I have read that the provided current should be the 10% of the Ah rating of the battery, e.g. in this case it would be 18.4 A for a single battery.
If this "10%" statement is true, would it be the 10% of 185 Ah or 185 + 185 Ah?

A: It should be 10% of 185 Ah, as two 12V 185Ah batteries in series essentially behave as one 24V 185Ah battery.

A: The optimal charge method is using a Battery Balancer which will extend the weakest battery life more than the variance from 5% 20h to 20% 5h.
Also using a pulse desulfator which operates onky when charger is active extends the life by cleaning the anodes better than 14.2V per battery. Reducing CV from 28.4 to 28.2V with this also reduces acid evaporation.


text:
Q: Unable to apply changes on device on iOS real device I run tns run ios error on my real device after I change a develop .cert and .mobileprovision file.
I delete old cert in my keychain-access and double click the .cert file and the .mobileprovision file,
and I even update cli and tns-core-module to latest version, but it's still not work.
Could anyone help me?
I use mac .
cli version is 5.3.1
xcode version is 10.1
My package.json is here:
"nativescript": {
    "id": "com.softbrain.discounteasy",
    "tns-android": {
      "version": "5.2.1"
    },
    "tns-ios": {
      "version": "5.3.1"
    }
  },
"dependencies": {
    "@angular/animations": "~7.1.0",
    "@angular/common": "~7.1.0",
    "@angular/compiler": "~7.1.0",
    "@angular/core": "~7.1.0",
    "@angular/forms": "~7.1.0",
    "@angular/http": "~7.1.0",
    "@angular/platform-browser": "~7.1.0",
    "@angular/platform-browser-dynamic": "~7.1.0",
    "@angular/router": "~7.1.0",
    "@danvick/ngx-translate-nativescript-loader": "^2.0.0",
    "@ngx-translate/core": "^11.0.1",
    "crypto-js": "^3.1.9-1",
    "nativescript-angular": "~7.1.0",
    "nativescript-clipboard": "^1.1.7",
    "nativescript-code-push": "^1.0.1",
    "nativescript-exit": "^1.0.1",
    "nativescript-feedback": "^1.3.5",
    "nativescript-hex-string": "0.0.4",
    "nativescript-imagepicker": "^6.1.2",
    "nativescript-localstorage": "^2.0.0",
    "nativescript-microsoft-appcenter": "^1.2.1",
    "nativescript-plugin-firebase": "^8.0.1",
    "nativescript-theme-core": "^1.0.4",
    "nativescript-toast": "^1.4.6",
    "nativescript-windowed-modal": "^5.0.6",
    "reflect-metadata": "~0.1.8",
    "rxjs": "~6.3.3",
    "rxjs-compat": "^6.4.0",
    "tns-core-modules": "^5.3.1",
    "tns-platform-declarations": "^5.1.2",
    "zone.js": "^0.8.26"
  },
  "devDependencies": {
    "@angular-devkit/core": "~7.1.0",
    "@angular/cli": "^7.1.0",
    "@angular/compiler-cli": "~7.1.0",
    "@nativescript/schematics": "~0.4.0",
    "@ngtools/webpack": "^7.1.4",
    "nativescript-dev-sass": "^1.6.0",
    "nativescript-dev-typescript": "~0.7.0",
    "nativescript-dev-webpack": "^0.19.0",
    "tns-android": "^5.1.0",
    "tns-ios": "^5.1.1",
    "typescript": "~3.1.1",
    "uglifyjs-webpack-plugin": "^2.1.1"
  },

and the build log here:
nativescript-plugin-firebase: /Users/softbraintechnologylimited/projects/DiscountEasyUI/platforms/ios/.pluginfirebaseinfo not found, forcing prepare!
nativescript-plugin-firebase: running release build or change in environment detected, forcing prepare!
Detected short imports in your application. Please note that short imports are deprecated since NativeScript 5.2.0. More information can be found in this blogpost https://www.nativescript.org/blog/say-goodbye-to-short-imports-in-nativescript

In file /Users/softbraintechnologylimited/projects/DiscountEasyUI/app/pages/tabs/home-page/home-page/home-page.component.ts line import * as application from 'application' is short import. Add tns-core-modules/ in front of the required/imported module.

In file /Users/softbraintechnologylimited/projects/DiscountEasyUI/app/shared/pipes/image-cache.pipe.ts line import { ImageSource, fromResource } from 'image-source' is short import. Add tns-core-modules/ in front of the required/imported module.

In file /Users/softbraintechnologylimited/projects/DiscountEasyUI/app/shared/pipes/image-cache.pipe.ts line import { Cache } from 'ui/image-cache' is short import. Add tns-core-modules/ in front of the required/imported module.

In file /Users/softbraintechnologylimited/projects/DiscountEasyUI/app/shared/pipes/image-cache.pipe.ts line import { isFileOrResourcePath, isDataURI } from 'utils/utils' is short import. Add tns-core-modules/ in front of the required/imported module.

Hook skipped because either bundling or livesync is in progress.
Hook skipped because either bundling or livesync is in progress.
Preparing project...
Successfully prepared plugin nativescript-angular for ios.
Successfully prepared plugin nativescript-clipboard for ios.
Successfully prepared plugin nativescript-code-push for ios.
Successfully prepared plugin nativescript-feedback for ios.
Successfully prepared plugin nativescript-hex-string for ios.
Successfully prepared plugin nativescript-imagepicker for ios.
Successfully prepared plugin nativescript-localstorage for ios.
Successfully prepared plugin nativescript-microsoft-appcenter for ios.
Successfully prepared plugin nativescript-plugin-firebase for ios.
Successfully prepared plugin nativescript-theme-core for ios.
Successfully prepared plugin nativescript-toast for ios.
Successfully prepared plugin nativescript-windowed-modal for ios.
Successfully prepared plugin tns-core-modules for ios.
Successfully prepared plugin nativescript-intl for ios.
Successfully prepared plugin nativescript-appversion for ios.
Successfully prepared plugin nativescript-zip for ios.
nativescript-permissions is not supported for ios.
Successfully prepared plugin nativescript-permissions for ios.
Successfully prepared plugin tns-core-modules-widgets for ios.
Installing pods...
Analyzing dependencies
Pre-downloading: `ISMessages` from `https://github.com/EddyVerbruggen/ISMessages.git`, commit `580ac8cab611e2f92ebdd62b2201f9dada36ccd4`
Downloading dependencies
Installing AppCenter (1.14.0)
Installing Firebase (5.16.0)
Installing FirebaseAnalytics (5.5.0)
Installing FirebaseAnalyticsInterop (1.2.0)
Installing FirebaseCore (5.2.0)
Installing FirebaseInstanceID (3.7.0)
Installing FirebaseMessaging (3.3.0)
Installing GoogleAppMeasurement (5.5.0)
Installing GoogleUtilities (5.5.0)
Installing ISMessages (1.2)
Installing Protobuf (3.7.0)
Installing QBImagePickerController (3.4.0)
Installing SSZipArchive (2.1.4)
Installing Toaster (2.0.4)
Installing nanopb (0.3.901)
Generating Pods project
Integrating client project

[!] Please close any current Xcode sessions and use `DiscountEasyUI.xcworkspace` for this project from now on.
Sending stats
Pod installation complete! There are 7 dependencies from the Podfile and 15 total pods installed.
Project successfully prepared (iOS)
Configure firebase
Android not installed, skipping CodePush hook.
Building project...
Xcode build...
2019-04-06 09:39:21.580 xcodebuild[1297:29067]  DTDeviceKit: deviceType from df1b668dc0b68ae30113d5198979559ab1938293 was NULL
warning: Swift 3 mode has been deprecated and will be removed in a later version of Xcode. Please migrate "Toaster" to Swift 4.2 using "Convert > To Current Swift Syntax…" in the Edit menu. (in target 'Toaster')
warning: Swift 3 mode has been deprecated and will be removed in a later version of Xcode. Please migrate "Toaster" to Swift 4.2 using "Convert > To Current Swift Syntax…" in the Edit menu. (in target 'Toaster')
/Users/softbraintechnologylimited/projects/DiscountEasyUI/platforms/ios/Pods/Toaster/Sources/ToastCenter.swift:36:19: warning: static declarations are implicitly 'final'; use 'public' instead of 'open'
  open static let `default` = ToastCenter()
  ~~~~            ^
  public
/Users/softbraintechnologylimited/projects/DiscountEasyUI/platforms/ios/Pods/Toaster/Sources/ToastWindow.swift:24:19: warning: static declarations are implicitly 'final'; use 'public' instead of 'open'
  open static let shared = ToastWindow(frame: UIScreen.main.bounds)
  ~~~~            ^
  public
/Users/softbraintechnologylimited/projects/DiscountEasyUI/platforms/ios/Pods/Toaster/Sources/ToastCenter.swift:36:19: warning: static declarations are implicitly 'final'; use 'public' instead of 'open'
  open static let `default` = ToastCenter()
  ~~~~            ^
  public
/Users/softbraintechnologylimited/projects/DiscountEasyUI/platforms/ios/Pods/Toaster/Sources/ToastWindow.swift:24:19: warning: static declarations are implicitly 'final'; use 'public' instead of 'open'
  open static let shared = ToastWindow(frame: UIScreen.main.bounds)
  ~~~~            ^
  public
/Users/softbraintechnologylimited/projects/DiscountEasyUI/platforms/ios/Pods/Toaster/Sources/ToastWindow.swift:24:19: warning: static declarations are implicitly 'final'; use 'public' instead of 'open'
  open static let shared = ToastWindow(frame: UIScreen.main.bounds)
  ~~~~            ^
  public
/Users/softbraintechnologylimited/projects/DiscountEasyUI/platforms/ios/Pods/Toaster/Sources/ToastCenter.swift:36:19: warning: static declarations are implicitly 'final'; use 'public' instead of 'open'
  open static let `default` = ToastCenter()
  ~~~~            ^
  public
/Users/softbraintechnologylimited/projects/DiscountEasyUI/platforms/ios/Pods/Toaster/Sources/ToastCenter.swift:36:19: warning: static declarations are implicitly 'final'; use 'public' instead of 'open'
  open static let `default` = ToastCenter()
  ~~~~            ^
  public
/Users/softbraintechnologylimited/projects/DiscountEasyUI/platforms/ios/Pods/Toaster/Sources/ToastWindow.swift:24:19: warning: static declarations are implicitly 'final'; use 'public' instead of 'open'
  open static let shared = ToastWindow(frame: UIScreen.main.bounds)
  ~~~~            ^
  public
/Users/softbraintechnologylimited/projects/DiscountEasyUI/platforms/ios/Pods/Toaster/Sources/ToastCenter.swift:36:19: warning: static declarations are implicitly 'final'; use 'public' instead of 'open'
  open static let `default` = ToastCenter()
  ~~~~            ^
  public
/Users/softbraintechnologylimited/projects/DiscountEasyUI/platforms/ios/Pods/Toaster/Sources/ToastWindow.swift:24:19: warning: static declarations are implicitly 'final'; use 'public' instead of 'open'
  open static let shared = ToastWindow(frame: UIScreen.main.bounds)
  ~~~~            ^
  public
/Users/softbraintechnologylimited/projects/DiscountEasyUI/platforms/ios/Pods/Toaster/Sources/ToastWindow.swift:24:19: warning: static declarations are implicitly 'final'; use 'public' instead of 'open'
  open static let shared = ToastWindow(frame: UIScreen.main.bounds)
  ~~~~            ^
  public
/Users/softbraintechnologylimited/projects/DiscountEasyUI/platforms/ios/Pods/Toaster/Sources/ToastCenter.swift:36:19: warning: static declarations are implicitly 'final'; use 'public' instead of 'open'
  open static let `default` = ToastCenter()
  ~~~~            ^
  public
/Users/softbraintechnologylimited/projects/DiscountEasyUI/platforms/ios/Pods/ISMessages/ISMessages/Classes/ISMessages.m:198:1: warning: conflicting return type in
      implementation of 'accessibilityPerformEscape': 'BOOL' (aka 'signed char') vs 'bool' [-Wmismatched-return-types]
- (bool)accessibilityPerformEscape {
^  ~~~~
In module 'UIKit' imported from /Users/softbraintechnologylimited/projects/DiscountEasyUI/platforms/ios/Pods/Target Support Files/ISMessages/ISMessages-prefix.pch:2:
/Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS12.1.sdk/System/Library/Frameworks/UIKit.framework/Headers/UIAccessibility.h:276:1: note:
      previous definition is here
- (BOOL)accessibilityPerformEscape NS_AVAILABLE_IOS(5_0);
^  ~~~~
1 warning generated.
note: Using new build systemnote: Planning buildnote: Constructing build description
Xcode build...
2019-04-06 09:40:04.685 xcodebuild[3913:36112] [MT] IDEDistribution: -[IDEDistributionLogging _createLoggingBundleAtPath:]: Created bundle at path '/var/folders/qx/nqzfs3217731kb43q_pcpvfh0000gn/T/DiscountEasyUI_2019-04-06_09-40-04.685.xcdistributionlogs'.
Exported DiscountEasyUI to: /Users/softbraintechnologylimited/projects/DiscountEasyUI/platforms/ios/build/Debug-iphoneos
Project successfully built.
Installing on device df1b668dc0b68ae30113d5198979559ab1938293...
Unable to apply changes on device: df1b668dc0b68ae30113d5198979559ab1938293. Error is: Failed to install /Users/softbraintechnologylimited/projects/DiscountEasyUI/platforms/ios/build/Debug-iphoneos/DiscountEasyUI.ipa on device with identifier df1b668dc0b68ae30113d5198979559ab1938293. Error is: Could not install application.

A: Is the device included in that provisioning profile? Drag the profile to the TextEdit application and look for:
<key>ProvisionedDevices</key>
Is df1b668dc0b68ae30113d5198979559ab1938293 listed after that? If not, in the Apple Developer Portal, update the provisioning profile to include your device. Then, try again with the updated profile.
The only other reason I can think of for an app not to install is if the device doesn't meet the minimum requirements; if the device's iOS version is less the the app's deployment minimum, for example.
To see more information about the installation failure, open the Console application (not the Terminal), connect your unlocked phone to the computer, and then select the device in the Console application. Try to install the app again.
In the "Search" box at the top of the Console window, enter the name of your application and press enter to filter the log based on that.

You'll see a lot of text with details about the installation. It will look something like this, but should indicate an error somewhere:
default 23:04:32.280735 -0400   streaming_zip_conduit   com.mycompany.SuperApp:5:1:1:1:Beginning installation for file:///var/mobile/Media/PublicStaging/SuperApp.app/ with options {
    AllowInstallLocalProvisioned = 1;
    CFBundleIdentifier = "com.mycompany.SuperApp";
    DisableDeltaTransfer = 1;
    InstallDeltaTypeKey = InstallDeltaTypeSparseIPAFiles;
    IsUserInitiated = 1;
    PackageType = Developer;
}
default 23:04:32.288006 -0400   lsd com.mycompany.SuperApp:5:1:1:1:Ininstall file:///var/mobile/Media/PublicStaging/SuperApp.app/ with options {
    AllowInstallLocalProvisioned = 1;
    CFBundleIdentifier = "com.mycompany.SuperApp";
    DisableDeltaTransfer = 1;
    InstallDeltaTypeKey = InstallDeltaTypeSparseIPAFiles;
    IsUserInitiated = 1;
    PackageType = Developer;
}
default 23:04:32.289279 -0400   lsd com.mycompany.SuperApp:5:1:1:1:Ininstall file:///var/mobile/Media/PublicStaging/SuperApp.app/ with options {
    AllowInstallLocalProvisioned = 1;
    CFBundleIdentifier = "com.mycompany.SuperApp";
    DisableDeltaTransfer = 1;
    InstallDeltaTypeKey = InstallDeltaTypeSparseIPAFiles;
    IsUserInitiated = 1;
    PackageType = Developer;
}
default 23:04:32.292304 -0400   installd    0x16b15f000 -[MIClientConnection _doInstallationForURL:withOptions:completion:]: Install of "/var/mobile/Media/PublicStaging/SuperApp.app" type Developer (LSInstallType = (null)) requested by lsd (pid 31819)
default 23:04:32.306147 -0400   assertiond  Request to create termination assertion <BKSTerminationAssertionCreateEvent: 0x105ec9a00; Identifier: 29899-552C42A1-9731-49B7-B96B-41A0B2D360AB; Name: FBSApplicationTerminationAssertion; Target BundleID: com.mycompany.SuperApp; Efficacy: Unconditional> from client <BKClientHandle: 0x105f0da40; installd:29899; connections: 1>
default 23:04:32.309880 -0400   SpringBoard termination assertion efficacy for com.mycompany.SuperApp (app not found) changed to 3
default 23:04:32.310150 -0400   installd    Acquired termination assertion for event <BKSTerminationAssertionCreateEvent: 0x10a802170; Identifier: 29899-552C42A1-9731-49B7-B96B-41A0B2D360AB; Name: FBSApplicationTerminationAssertion; Target BundleID: com.mycompany.SuperApp; Efficacy: Unconditional>
default 23:04:32.321511 -0400   installd    0x16b15f000 -[MIInstaller performInstallationWithError:]: Installing <MIInstallableBundle ID=com.mycompany.SuperApp; Version=1, ShortVersion=1.0>
default 23:04:32.321804 -0400   installd    com.mycompany.SuperApp:7:5:1:1:Start : Install (New)
default 23:04:32.822905 -0400   installd    0x16b15f000 -[MIContainer makeContainerLiveReplacingContainer:reason:waitForDeletion:withError:]: Made container live for com.mycompany.SuperApp at /private/var/mobile/Containers/Data/Application/E18E5DFA-A7E2-4B20-AA88-571213D25CA4
default 23:04:32.827238 -0400   installd    0x16b15f000 -[MIContainer makeContainerLiveReplacingContainer:reason:waitForDeletion:withError:]: Made container live for com.mycompany.SuperApp at /private/var/containers/Bundle/Application/53C45EA1-44C3-4AAE-BD6E-72EE3F82B8BA
default 23:04:32.859543 -0400   installd    com.mycompany.SuperApp:7:5:2:1:Success (End) : Install (New)
default 23:04:32.859738 -0400   installd    0x16b15f000 -[MIInstaller performInstallationWithError:]: Install Successful for (Developer:com.mycompany.SuperApp); Staging: 0.01s; Waiting: 0.00s; Preflight/Patch: 0.01s, Verifying: 0.46s; Overall: 0.57s

There should be more clues there.


text:
Q: How to count cells that are shaded and greater than a certain value I have a series of shaded cell that i wish to count, but i also want to count those cells that are shaded and greater than zero
I have found some code that writes a formula that counts the cells based off the colour, but i am trying to modify it to add an additional condition. I have tried adding an AND command into the formula to give the additional condition.
Function CountColorIf(rSample As Range, rArea As Range) As Long

Dim rAreaCell As Range
Dim lMatchColor As Long
Dim lCounter As Long

lMatchColor = rSample.Interior.Color
For Each rAreaCell In rArea
    If rAreaCell.Interior.Color = lMatchColor And Cells.Value > "0" Then
        lCounter = lCounter + 1
    End If
Next rAreaCell
CountColorIf = lCounter
End Function

I added the    And Cells.Value > "0"   piece to existing code
As it is searching each "rAreaCell" can i not add an AND to also identify if it is greater than 0?

A: the cell you need to check is rAreaCell, you can not use cells
If rAreaCell.Interior.Color = lMatchColor And rAreaCell.Value > "0" Then


text:
Q: BitmapEncoder flush throws Argument Exception I'm trying to resize images in my UWP application. Most of the time the appended code works, but sometimes await encoder.FlushAsync(); throws an ArgumentException.
I've headed over to MSDN (https://msdn.microsoft.com/en-us/library/windows/apps/windows.graphics.imaging.bitmapencoder.bitmaptransform.aspx) and they tell me (at "Remarks"):

If you try scale an image stored in an indexed pixel format using the BitmapTransform member, FlushAsync fails with HRESULT WINCODEC_ERR_INVALIDPARAMETER . Instead, you must use GetPixelDataAsync to obtain the scaled pixel data and then use SetPixelData to set it on the encoder.

I've tried to do that, see the two commented lines (which look somehow wrong to me due to the repetition). On the second line (where I try to SetPixelData) the Encoder rewards me with an buffer allocated not sufficient Exception.
var decoder = await BitmapDecoder.CreateAsync(streamToReadFrom.AsStream().AsRandomAccessStream());
if (decoder.OrientedPixelHeight > height ||
    decoder.OrientedPixelWidth > width)
{
    var resizedStream = new InMemoryRandomAccessStream();
    BitmapEncoder encoder = await BitmapEncoder.CreateForTranscodingAsync(resizedStream, decoder);

    encoder.BitmapTransform.InterpolationMode = BitmapInterpolationMode.Fant;
    encoder.BitmapTransform.ScaledHeight = newHeight;
    encoder.BitmapTransform.ScaledWidth = newWidth;

    //"buffer allocated not sufficient"
    // var pd = await decoder.GetPixelDataAsync(BitmapPixelFormat.Rgba16, BitmapAlphaMode.Ignore,
    //             encoder.BitmapTransform, ExifOrientationMode.IgnoreExifOrientation, ColorManagementMode.DoNotColorManage);
    // encoder.SetPixelData(BitmapPixelFormat.Rgba16, BitmapAlphaMode.Ignore,
    //             decoder.OrientedPixelWidth, decoder.OrientedPixelHeight, decoder.DpiX, decoder.DpiY, pd.DetachPixelData());

    // write out to the stream
    // might fail cause https://msdn.microsoft.com/en-us/library/windows/apps/windows.graphics.imaging.bitmapencoder.bitmaptransform.aspx
    await encoder.FlushAsync();

    // Read out resizedStream and return
}

Example image which causes this issue: http://www.spiegel.de/images/image-1028227-hppano-lqbn.jpg. Unit Test here: https://github.com/famoser/OfflineMedia/blob/master/Famoser.OfflineMedia.UnitTests/Presentation/ImageResizeTest.cs
How can I avoid the ArgumentException? How do I know an image is in an "indexed pixel format", and how can I resize this format too?

A:
On the second line (where I try to SetPixelData) the Encoder rewards me with an buffer allocated not sufficient Exception.

This is because when you SetPixelData, the pixel data doesn't match it from GetPixelDataAsync. You can for example code like this:
if (file != null)
{
    BitmapImage bmp = new BitmapImage();
    using(var imageStream = await file.OpenAsync(Windows.Storage.FileAccessMode.ReadWrite))
    {
        BitmapDecoder decoder = await BitmapDecoder.CreateAsync(imageStream);
        InMemoryRandomAccessStream pixelras = new InMemoryRandomAccessStream();
        BitmapEncoder pixelencoder = await BitmapEncoder.CreateAsync(BitmapEncoder.JpegEncoderId, pixelras);
        BitmapTransform transform = new BitmapTransform();
        transform.InterpolationMode = BitmapInterpolationMode.Fant;
        transform.ScaledHeight = 400;
        transform.ScaledWidth = 400;
        var provider = await decoder.GetPixelDataAsync(BitmapPixelFormat.Bgra8,
            BitmapAlphaMode.Ignore,
            transform,
            ExifOrientationMode.RespectExifOrientation,
            ColorManagementMode.DoNotColorManage);
        var pixels = provider.DetachPixelData();
        pixelencoder.SetPixelData(BitmapPixelFormat.Bgra8, BitmapAlphaMode.Ignore, 400,
            400, decoder.DpiX, decoder.DpiY, pixels);

        try
        {
            await pixelencoder.FlushAsync();
        }
        catch(Exception ex)
        {

        }
        bmp.SetSource(pixelras);
        img.Source = bmp;
    }
}

How do I know an image is in an "indexed pixel format", and how can I resize this format too?

I couldn't find any effective way to detect an indexed pixel format image, but since it is said

If you try scale an image stored in an indexed pixel format using the BitmapTransform member, FlushAsync fails with HRESULT WINCODEC_ERR_INVALIDPARAMETER . Instead, you must use GetPixelDataAsync to obtain the scaled pixel data and then use SetPixelData to set it on the encoder.

It is a method to use catch the exception and use SetPixelData again, for example:
if (file != null)
{
    BitmapImage bmp = new BitmapImage();
    using(var imageStream = await file.OpenAsync(Windows.Storage.FileAccessMode.ReadWrite))
    {
        BitmapDecoder decoder = await BitmapDecoder.CreateAsync(imageStream);
        InMemoryRandomAccessStream ras = new InMemoryRandomAccessStream();
        BitmapEncoder encoder = await BitmapEncoder.CreateForTranscodingAsync(ras, decoder);

        encoder.BitmapTransform.InterpolationMode = BitmapInterpolationMode.Fant;
        encoder.BitmapTransform.ScaledHeight = 400;
        encoder.BitmapTransform.ScaledWidth = 400;

        try
        {
            await encoder.FlushAsync();
            bmp.SetSource(ras);
        }
        catch (Exception ex)
        {
            if (ex.HResult.ToString() == "WINCODEC_ERR_INVALIDPARAMETER")
            {
                InMemoryRandomAccessStream pixelras = new InMemoryRandomAccessStream();
                BitmapEncoder pixelencoder = await BitmapEncoder.CreateAsync(BitmapEncoder.JpegEncoderId, pixelras)
                BitmapTransform transform = new BitmapTransform();
                transform.InterpolationMode = BitmapInterpolationMode.Fant;
                transform.ScaledHeight = 400;
                transform.ScaledWidth = 400;
                var provider = await decoder.GetPixelDataAsync(BitmapPixelFormat.Bgra8,
                    BitmapAlphaMode.Ignore,
                    transform,
                    ExifOrientationMode.RespectExifOrientation,
                    ColorManagementMode.DoNotColorManage);
                var pixels = provider.DetachPixelData();
                pixelencoder.SetPixelData(BitmapPixelFormat.Bgra8, BitmapAlphaMode.Ignore, 400,
                    400, decoder.DpiX, decoder.DpiY, pixels);
                try
                {
                    await pixelencoder.FlushAsync();
                    bmp.SetSource(pixelras);
                }
                catch
                {

                }
            }
        }
        img.Source = bmp;
    }
}


text:
Q: Angular/TS: Asynchronous HTTP call inside forEach Loop Is there a way to make forEach loop in Typescript wait so that asynchronous code like http call can complete properly.
Let's say I have three Arrays a[], b[] & c[] in an Angular Component.
There are three functions, the latter two depends on the completion of previous functions.
loadA(){
this.http.get<a[]>(http://getA).subscribe(a=> this.a = a,
()=>loadB());
}

loadB(){
this.a.forEach((res, index)=>{
this.http.get<b[]>('http://getBbyA/res').subscribe(b=> this.b.push(...b),
()=> {
if(index===this.a.length-1){
loadC());
}
}
});

loadC(){
this.b.forEach(res=>{
this.http.get<c[]>('http://getCbyB/res').subscribe(c=> this.c.push(...c));
});
}

Now for the second Method the forEach loop makes it unpredictable to call the loadC() function after the b[] array is properly loaded with data fetched from http call. How to make forEach loop in loadB()  wait for all the http results are fetched and then call loadC() to avoid unpredictability?
Update (With RxJs Operators):
I have tried the following in my project:
loadData(): void {
    this.http.post<Requirement[]>(`${this.authService.serverURI}/requirement/get/requirementsByDeal`, this.dealService.deal).pipe(
      concatAll(), // flattens the array from the http response into Observables
      concatMap(requirement => this.http.post<ProductSet[]>(`${this.authService.serverURI}/productSet/getProductSetsByRequirement`, requirement).pipe( // loads B for each value emitted by source observable. Source observable emits all elements from LoadA-result in this case
        concatAll(), // flattens the array from the http response of loadB
        concatMap(pSet => this.http.post<Product[]>(`${this.authService.serverURI}/product/get/productsByProductSet`, pSet).pipe( // foreach element of LoadB Response load c
          map(product => ({requirement, pSet, product})) // return a object of type { a: LoadAResult, b: LoadBResult, c: LoadCResult}
        ))
      )),
      toArray()
    ).subscribe((results: { requirement: Requirement, productSet: ProductSet, product: Product }[] => {
      results.forEach(result => {
        this.requirements.push(...result.requirement);
        this.productSets.push(...result.productSet);
        this.products.push(...result.product);
      });
    }));
  }

But I am still getting some error (TS2345). Where I am going wrong?

A: There are several ways to achieve this. I suggest to use rxJs Operators concatAll and concatMap so fire the httpCalls in sequence. I prepared a quick snippet.
It first loads A, then for each element in A it loads B and for each element in B it loads C. You may need to adjust the aggregation of results depending on your needs
load(): void {
this.http.get<LoadAResult[]>("/loadA").pipe(
  concatAll(), // flattens the array from the http response into Observables
  concatMap(a => this.http.get<LoadBResult[]>("/loadB").pipe( // loads B for each value emitted by source observable. Source observable emits all elements from LoadA-result in this case
    concatAll(), // flattens the array from the http response of loadB
    concatMap(b => this.http.get<LoadCResult[]>("/loadC").pipe( // foreach element of LoadB Response load c
      map(c => ({a, b,c })) // return a object of type { a: LoadAResult, b: LoadBResult, c: LoadCResult}
    ))
  )),
  toArray()
).subscribe((results: { a: LoadAResult, b: LoadBResult, c: LoadCResult[]}[]) => {
  // do something with results
}));

}


text:
Q: Class 'Illuminate\Html\HtmlServiceProvider' not found Im trying to add the HtmlServiceProvider with Laravel 5. But when i write - "php artisan serve" in terminal i get error -
[Symfony\Component\Debug\Exception\FatalErrorException]
  Class 'Illuminate\Html\HtmlServiceProvider' not found

I already have these things in configs.
"laravelcollective/html": "5.2.*"
Collective\Html\HtmlServiceProvider::class,

and
'Form'      => Collective\Html\FormFacade::class,
'Html'      => Collective\Html\HtmlFacade::class,

*

*i cant run all php artisan commands.
Thanks for your attention!

A: Remove the Illuminate\Html\HtmlServiceProvider line from your config/app.php providers section since you are not using that package.
Also might be worth clearing the compiled file if that isn't enough.


text:
Q: Clojure/Java.regex: Why does re-find throw cast exceptions for my parenthesised regex (below) but not for a simple expression like "\d+"? Hi I'm new to Clojure and not very experienced with java and I'm struggling to use a more complex RegEx with the below code:
(defn clean-input [s]
  (read-string (re-find #"\d+" s)))
(defn map-numbers [s]
  (map clean-input (clojure.string/split s #" ")))

(map-numbers "1 2 3/3 4 5")
;=> (1 2 3 4 5)

I would like to take a delimited string like the one below and remove any non-numerics and map the remaining numbers into a lazy sequence, So I can square each item in the sequence and output the result in another function.
"1 2 3.2 4/4 ff 32.12342e+12 red 1.79769313486231570e+308d 0.001 32/3 0xe22A23 9C5.FF3B645A1C16 0556 0xff 0XFF 0x1f 0x223323223 hg 76 ghg6667  2r1111  32r34a32 33r35545 123."

So I have constructed the below (slightly ugly) RegEx do this and it seems correct using regexr.com  I've made this multiline and added comments for readability but is a single line when used in the code.
 (\d+\.\d+(e(-|\+)\d+)?)                             ;floats and scientific notation
|(\d+\/\d+)                                          ;fractions
|(0(x|X)([A-Fa-f]|\d)+)                              ;hex
|(([2-9]|[1-2][0-9]|3[0-2])(r|R)(([A-Za-z]|\d)+))    ;radix(ish)
|(\d+)                                               ;int and oct

When I replace "\d+" with the above RegEx I get the following casting exceptions:
Error printing return value (ClassCastException) at clojure.core/read-string (core.clj:3805).
class clojure.lang.Cons cannot be cast to class java.lang.String
(clojure.lang.Cons is in unnamed module of loader 'app'; java.lang.String is in module java.base of loader 'bootstrap')
I've tried to read into the issue further but I haven't made any headway, would someone be kind enough to explain what I'm doing wrong and what I should be doing instead?
It would be much appreciated,
Thanks

A: (read-string (re-seq re x)) makes little sense. re-seq returns a sequence, and read-string reads a string. These don't match, so the error you get is expected, no matter what re and x are.
The surprise is that you claim your first example works. It obviously shouldn't, and when I copy it into a new repl I find that indeed it does not work. Please make sure you include actual failing code when asking for help with it. If you edit it to make sure it's minimal (a good idea!), make sure the error is still reproducible after your edit.


text:
Q: c# - Keyboardhook on an Outlook Ribbon Control I want to Hook a specific control (a combobox) and receive all keys typed in that control. The Combobox is part of an Outlook Ribbon an has no events like keypress or something (just onChange which behaves really weird).
Here is the Code:
    private const int WH_KEYBOARD_LL = 13;
    private const int WM_KEYDOWN = 0x0100;
    private LowLevelKeyboardProc _proc;
    private IntPtr _hookID = IntPtr.Zero;

    private void SetHook(IntPtr handle)
    {
        uint PID; //not needed
        _proc = HookCallback;
        uint threadid = GetWindowThreadProcessId(handle, out PID);
        _hookID = SetWindowsHookEx(WH_KEYBOARD_LL, _proc, IntPtr.Zero, threadid );

    }

    private delegate IntPtr LowLevelKeyboardProc(
            int nCode, IntPtr wParam, IntPtr lParam);

    private IntPtr HookCallback(int nCode, IntPtr wParam, IntPtr lParam)
    {
        if (nCode >= 0 && wParam == (IntPtr)WM_KEYDOWN)
        {
            int vkCode = Marshal.ReadInt32(lParam);
            System.Diagnostics.Debug.WriteLine("Key: " + (Keys)vkCode);
        }
        return CallNextHookEx(_hookID, nCode, wParam, lParam);
    }

The handle i have and the ThreadID i get are correct (verified via Spy++) but no key is captured. Works fine with "0" as the last parameter of the SetWindowsHookEx function but then its a global hook ofcourse.

A: I add this for anyone who has the same problem. Keyboardhooks are global, one cannot hook to a specific control. What you need to do is capture the messages of the given handle. To do so, you have to subclass your window/handle.
    [DllImport("user32")]
    private static extern IntPtr SetWindowLong(IntPtr hWnd, int nIndex, Win32WndProc newProc);
    [DllImport("user32")]
    private static extern int CallWindowProc(IntPtr lpPrevWndFunc, IntPtr hWnd, int Msg, int wParam, int lParam);

    // A delegate that matches Win32 WNDPROC:
    private delegate int Win32WndProc(IntPtr hWnd, int Msg, int wParam, int lParam);

    // from winuser.h:
    private const int GWL_WNDPROC = -4;
    private const int WM_KEYDOWN = 0x0100;

    // program variables
    private IntPtr oldWndProc = IntPtr.Zero;
    private Win32WndProc newWndProc = null;

    private void SubclassHWnd(IntPtr hWnd)
    {
        // hWnd is the window you want to subclass..., create a new
        // delegate for the new wndproc
        newWndProc = new Win32WndProc(MyWndProc);
        // subclass
        oldWndProc = SetWindowLong(hWnd, GWL_WNDPROC, newWndProc);
    }

    private const int ENTER_KEY = 1835009;

    // this is the new wndproc, just show a messagebox on left button down:
    private int MyWndProc(IntPtr hWnd, int Msg, int wParam, int lParam)
    {

        switch (Msg)
        {
            case WM_KEYDOWN:
                int vkCode = lParam;
                if (vkCode == ENTER_KEY)
                    doSomething();
                return 0;

            default:
                break;
        }

        return CallWindowProc(oldWndProc, hWnd, Msg, wParam, lParam);
    }


text:
Q: NullReferenceException was unhandled by usercode- Object reference not set to an instance of an object I get NullReferenceException was unhandled by usercode in below code.
if (item["Area"] != null)
{
    drpArea.Items.FindByText(item["Area"].ToString()).Selected = true;//error occurs here.
}

Tried to figure out a million times.But i am unable to do.

A: may be you should first get listitem from Dropdownlist and than set the selected value
Try this :
 ListItem li = drpArea.Items.FindByText(Convert.ToString(item["Area"]));
 if (li != null)
    drpArea.SelectedValue = li.Value;


text:
Q: The centroid of the Morley triangle of an isosceles triangle is collinear with the foci of the Steiner inellipse I have a little question about geometry found by a friend:

Let $\triangle ABC$ be isosceles. Let $M$ be the (equilateral) Morley triangle determined by the trisectors of the angles of $\triangle ABC$, and let $E$ be the Steiner inellipse tangent to the edges of $\triangle ABC$ at their midpoints. Prove that centroid of $M$ is collinear with the foci of $E$.

I don't have any idea to prove this.
Thanks a lot.

A: For $\triangle ABC$ a "tall" isosceles, with vertex angle of measure less than $60^\circ$, the result is obvious by symmetry. (All points of interest lie on the appropriate altitude.) We can include the $60^\circ$ vertex angle ---that is, equilateral $\triangle ABC$--- in that case. (All points of interest coincide with the triangle's centroid.) For a "short" isosceles, the result simply isn't true, as shown.

To answer a question raised in a comment: In an isosceles triangle, the Morley center aligns with some axis of the Steiner inellipse. However, that isn't saying much, because everything's symmetric in an isosceles triangle.
In a scalene triangle, the Morley center need not align with either axis of the Steiner inellipse:

A: Hints for an algebraic approach.
First, Marden's theorem says that the foci of the Steiner inellipse are the roots of the derivative of the cubic polynomial, whose roots are the triangles vertices (Here, we are thinking of the coordinates of the triangles as complex numbers in the plane). So, if your triangle is isosceles, then you can assume your triangle has vertices $i, -a, a$ for some $a>0.$ Then, the foci points are easily found using the Marden's theorem.
Second, this Wikipedia entry says that the trilinear coordinates of Morley's triangle's centroid are: $$\cos\frac{A}{3}+2\cos\frac{B}{3}\cos\frac{C}{3}:\cos\frac{B}{3}+2\cos\frac{C}{3}\cos\frac{A}{3}:\cos\frac{C}{3}+2\cos\frac{B}{3}\cos\frac{A}{3}$$
This enables you to find the centroid's coordinates and then you can use your favorite coordinate/complex bashing method to establish the concurrence of the three points. Note that while the above looks daunting, you can easily calculate those cosines because your triangle now has sides: $$2a, \sqrt{a^2+1}, \sqrt{a^2+1} .$$
But from the looks of it, the calculations could become a little tedious.


text:
Q: MFC. Quickly highlight all matches in RichEditCtrl I have a very large text (>50mb).
FindText, SetSel and SetSelectionCharFormat is too slow for me.
I tried to formulate the text and then display but it was even slower.
Can I work with RichEditCtrl in memory and then just display?
Or can I speed up the first option or you can solve my problem in another way?

A: My measurements of improvement are different than yours.
Here is my code:
void CRichEditAppView::OnEditHighlight()
{
    FINDTEXTEX ft = {};
    ft.chrg = { 0, -1 };
    ft.lpstrText = L"Lorem ipsum";
    DWORD dwFlags(FR_DOWN);
    CHARFORMAT2 cf = {};
    cf.cbSize = sizeof cf;
    cf.dwMask = CFM_BACKCOLOR;
    cf.crBackColor = RGB(255, 255, 0);
    CRichEditCtrl& ctrl = GetRichEditCtrl();
    ctrl.HideSelection(TRUE, FALSE);
    ctrl.SetRedraw(FALSE);
    int count(0);
    while (ctrl.FindTextW(dwFlags, &ft) >= 0)
    {
        ctrl.SetSel(ft.chrgText);
        ctrl.SetSelectionCharFormat(cf);
        ft.chrg.cpMin = ft.chrgText.cpMax + 1;
        count++;
    }
    ctrl.HideSelection(FALSE, FALSE);
    ctrl.SetRedraw(TRUE);
    ctrl.Invalidate();
}

I have tested it on a file with 3,000 copies of "Lorem ipsum" text (file size 1,379 KB).
The "naive" implementation (without calls to HideSelection() and SetRedraw()) took 11 seconds.
Calling HideSelection() reduced the time to 9 seconds, adding SetRedraw() - to 1.2 seconds. So I expect to see a 10-times improvement.
Just to compare, if I remove a call to SetSelectionCharFormat(), I'm only saving 0.4 seconds.


text:
Q: Debian 7.3 emacs packages cannot be authenticated? I'm using Debian 7.3 (x64):
$ uname -a
Linux XXX 3.2.0-4-amd64 #1 SMP Debian 3.2.51-1 x86_64 GNU/Linux

I found this to be kind of weird, and I've never run into it before. Any ideas how to proceed?
$ sudo apt-get install emacs
Reading package lists... Done
Building dependency tree
Reading state information... Done
The following extra packages will be installed:
  emacs23 emacs23-bin-common emacs23-common emacsen-common libm17n-0 libotf0
  m17n-contrib m17n-db
Suggested packages:
  emacs23-common-non-dfsg emacs23-el m17n-docs gawk
The following NEW packages will be installed:
  emacs emacs23 emacs23-bin-common emacs23-common emacsen-common libm17n-0
  libotf0 m17n-contrib m17n-db
0 upgraded, 9 newly installed, 0 to remove and 0 not upgraded.
Need to get 25.1 MB of archives.
After this operation, 81.1 MB of additional disk space will be used.
Do you want to continue [Y/n]? Y
WARNING: The following packages cannot be authenticated!
  emacsen-common emacs23-common emacs23-bin-common libotf0 m17n-db
  m17n-contrib libm17n-0 emacs23 emacs
Install these packages without verification [y/N]?

And sources.list. The Havana repo is for OpenStack gear:
$ cat /etc/apt/sources.list
deb ftp://ftp.us.debian.org/debian/ wheezy main
deb http://security.debian.org/ wheezy/updates main

# wheezy-updates, previously known as 'volatile'
deb ftp://ftp.us.debian.org/debian/ wheezy-updates main
deb http://http.debian.net/debian/ wheezy-backports main contrib
# deb-src http://http.debian.net/debian/ wheezy-backports main contrib
deb http://archive.gplhost.com/debian havana-backports main
deb http://archive.gplhost.com/debian havana main

A: These errors usually come up when you haven't added the appropriate apt-key on your system. I see that you have two repositories there that Debian may not be aware of, and it is possible that these packages are coming from these repositories. The ones I am referring to are below:

deb http://archive.gplhost.com/debian havana-backports main
deb http://archive.gplhost.com/debian havana main

This can also happen when you upgrade to a new version of Debian, or if the keys that you have on the current machine have expired. In either case, this might help fix the issue.
EDIT: use the above Ubuntu forums link with care, OP used it and it seems to have broken apt-get. Perhaps the Ask Ubuntu link is the better route to take.


text:
Q: CSS: Topbar not following the scrolling of the page I know there may be a solution out the for my problem but because its a specific code i decided to make a post and ask for help, so lets get started
I have a topbar (like a banner) that needs to follow the scrolling but it doesn't it stays in one position and it doesn't move
i already tried position:fixed and width:100% but it adds a little empty space on the top of the page
This is my css code:
.topBar{
  height: 50px;
  overflow: hidden;
  list-style-type: none;
  margin-left: -10px;
  margin-top: -10px;
  margin-right: -8px;
  padding: 0;
  background-color: #111;
  z-index: 1;
  background-image : url("image.png");
  background-repeat: no-repeat;
  background-size: contain;
  background-position: center;
}

This is the code where i load the topbar in the header:

 <?php echo $username?>

This is my desired result, here the position and width is not set but there it doesn't follow the scrolling
This is what happens when i apply position:fixed and width:100%, there is a white bar added on top and the scrolling works just fine

A: Is this what you want?
https://jsfiddle.net/15416xb1/4/
.topBar {
  height: 50px;
  width: 100%;
  overflow: hidden;
  list-style-type: none;
  margin-left: -10px;
  margin-top: -10px;
  margin-right: -8px;
  padding: 0;
  background-color: #111;
  position: fixed;
  top: 0;
  z-index: 1;
  background-image: url("image.png");
  background-repeat: no-repeat;
  background-size: contain;
  background-position: center;
}

I do not get the white space at the top

A: .topbar {
    height: 50px;
    position: fixed;
    top: 0;
    left: 0;
    width: 100%;
    min-width: 500px;
    z-index: 99999;
}
html.is-topbar {
    padding-top: 50px;
}


text:
Q: How to get votes for imbalanced downsampled random forest I have 752 cases, 102 from class 1 and 650 from class 2.  I get reasonable classification results following down-sampling using this code…
metric <-     "ROC"
preProcess <- "range"

control <- trainControl(
    method="cv", number=5,
  sampling = "down",
  returnResamp = "all" ,
  savePredictions = "all",
  summaryFunction=twoClassSummary,
  classProbs = TRUE)

fit.rf <- train(Group~., data=final_data, method="rf", metric=metric, trControl=control, preProcess=preProcess, tuneGrid = expand.grid(mtry = seq(1, 28)), ntree=500)

My question is that I want to be able to see the votes (class probabilities) for the held-out data.  I can retrieve them using this code (fit.rf$finalModel$votes) which gives me 204 values.  But how can I figure out which class is which and which case from the original sample of 752 is which?
I have tried using
fit.rf$control$indexOut

and
fit.rf$control$index

but the output is not easy for me to interpret.  It would be helpful for the 204 values to each have a case number (from 1 to 752).


text:
Q: Solve the integral $- \int \frac{1}{\cos x} \frac{1}{1-\sin^2x}dx$ How to solve the following integral?
$$- \int \frac{1}{\cos x} \frac{1}{1-\sin^2x}dx$$
I tried a u substitution with $u=1-\sin^2x$ and $du=-2\cos x$ so $\frac{du}{2}=-\cos x$ so then I get
$$\int \frac{1}{\frac{du}{2}} \frac{1}{u}$$
$$\int \frac{2}{du} \frac{1}{u}$$
and then the $du$ is in the denominator...

A: Hint: $$\int \frac{1}{\cos x} \frac{1}{1-\sin^2x}\,{\rm d}x = \int \frac{1}{\cos x}\frac{1}{\cos^2x}\,{\rm d}x = \int \sec^3x\,{\rm d}x = \int (1+\tan^2x)\sec x\,{\rm d}x$$

A: Hint: $~\displaystyle\int\frac{dx}{\cos x~(1-\sin^2x)}~=~\int\frac{dx}{\cos^3x}~=~\int\frac{\cos x}{\cos^4x}~dx~=~\int\frac{d\big(\sin x\big)}{\big(1-\sin^2x\big)^2}$
Can you take it from here ? :-$)$


text:
Q: Return an array value from included file in a function Ok, stupid question, I guess...
I'm trying to do this:
File: pt.php
<?php $langlist = array ( "Car" => "Carro", "Big Car" => "Carro grande") ?>

File: index.php
<?php
$lang = 'pt';
if ($lang != 'en') include('locale/' . $lang . '.php');
function __($langstring){
    if ($lang != 'en'){
        echo $langlist[$langstring];
    } else {
        echo $langstring;
    }
}
?>

But this doesn't work  (Notice: Undefined variable: lang and langlist).
What am I doing wrong?
P.S.: I know using echo instead of return inside a function ins't correct, but I don't want do be using echo __(); every time I need to use this function...

A: Your syntax is wrong:
<?php $langlist = array { "Car" => "Carro", "Big Car" => "Carro grande"} ?>

should be
<?php $langlist = array("Car" => "Carro", "Big Car" => "Carro grande") ?>

A: $lang and $langlist are global variables, but they cannot be seen from within the function. Simply add the following as the first line of the function to gain access to them:
global $lang, $langlist;

Alternatively, you could access them as $GLOBALS['lang'] and $GLOBALS['langlist'] without using the global declaration.


text:
Q: How to make animation easing (ease-in and ease-out) duration-independent? I'm using jQuery with Easing plugin and i would like to achieve constant easing times for for animations of any duration:
Short animation (X milliseconds)
|<<<<|-------------------|>>>>|
 10ms                     10ms

Long animation (2X milliseconds)
|<<<<|-----------------------------------------|>>>>|
 10ms                                           10ms

Where <<<< / >>>> are easing-in / easing-out periods, and --- denotes constant velocity movement.
Is there an easing function/plugin for that or should i give a time-dependent custom function for each animation like this and, if yes, then what kind?

A: You can use the callback function in the .animate() calls to chain animations:
var $obj     = $('#some-id'),
    ani_dist = 500;

//animate first easing
$obj.stop().animate({ left : 100 }, 500, 'easeOutCirc', function () {

    //animate main body of the animation
    $obj.animate({ left : (ani_dist - 100) }, 1000, 'linear', function () {

        //animate the last easing
        $obj.animate({ left : ani_dist }, 500, 'easeInCirc');
    });
});

I'm not sure what you want to set the animation to animate or what duration to use but there's an idea.

A: I think you should use the animate queen
//animate first easing
$obj.stop()
    .animate({ left : 100 }, 500, 'easeOutCirc')
    .animate({ left : (ani_dist - 100) }, 1000, 'linear')
    .animate({ left : ani_dist }, 500, 'easeInCirc')
;

See jQuery.animate example-2


text:
Q: Airflow DAGs are queued up I am working on a project where I can see all of the dags are queued up and not moving (appx over 24H or more)
Looks like its scheduler is broken but I need to confirm that.
So here are my questions

*

*How to see if scheduler is broken

*How to reset my airflow (web server) scheduler?

Expecting some help regarding how to reset airflow schedulers

A: The answer will depend a lot on how you are running Airflow (standalone, in Docker, Astro CLI, managed solution...?).

*

*If your scheduler is broken the Airflow UI will usually tell you the time since the last heartbeat like this:

*

*There is also an API endpoint for a scheduler health check at http://localhost:8080/health (if Airflow is running locally).

*Check the scheduler logs. By default they are in a file at $AIRFLOW_HOME/logs/scheduler.
You might also want to look at how to do health checks in Airflow in general.
In terms of resetting it is usually best to restart the scheduler and again this will depend on how you started it in the first place. If you are using a standalone instance and have the processes in the foreground simply do ctr+c or close the terminal to stop it. If you are running airflow in docker restart the container, for the Astro CLI there is astro dev restart.


text:
Q: Contains Query into MongoDB Array using Mongoose I'm trying to query into following document and want to list all document which contains TaxonomyID "1" in "TaxonomyIDs" field.
...
"Slug" : "videosecu-600tvl-outdoor-security-surveillance",
"Category" : "Digital Cameras",
"SubCategory" : "Surveillance Cameras",
"Segment" : "",
"Usabilities" : [
    "Dome Cameras",
    "Night Vision"
],
"TaxonomyIDs" : [
    1,
    12,
    20,
    21,
    13
],
"Brand" : "VideoSecu",
...

Totally stuck!

A: Model.find({TaxonomyIDs: 1}, function(error, models) {
  //put code to process the results here
});

mongodb interprets the query conditions above as "match any document where the TaxonomyIDs array contains 1".


text:
Q: How do I pass a parameter in a stored procedure looping values and dump the result set into a temp table? How do I create a stored procedure which can be passed a @CandidatelistID as a parameter to the existing stored procedure logic below.
I am looping the CandidateID and CandidateListID and running a stored procedure usp_ApplyRankingRules inside the loop to get the Weightage for each of them.
Then instead of insert and update the values in a table - RPT_CandidateCardReport I want to load the same fields in a temp table. When I am doing that I am getting the following error -
(0 row(s) affected)

(0 row(s) affected)
Msg 208, Level 16, State 0, Procedure usp_RPT_CandidateCardReporttest, Line     24 [Batch Start Line 53]
Invalid object name '#tempRPTCandidateCardReport'.

The data is present in the tables I am trying to loop and should show display the result from the temptable select statement at the bottom..
CREATE PROCEDURE [dbo].[usp_RPT_CandidateCardReporttest]     @candidateListIDs varchar(36)
    AS
    BEGIN
declare @candidateListID varchar(36)
declare @candidateID varchar(36)
declare @var_weightage decimal
declare @listcount INT = (SELECT COUNT(1) FROM CandidateList_Candidates)
declare @loopcount INT = 1

IF OBJECT_ID('tempdb..#tmpListCandidate') IS NOT NULL DROP TABLE #tmpListCandidate
SELECT CandidateListID, CandidateID, ROW_NUMBER()OVER(ORDER BY cl.CandidateID) AS Id INTO #tmpListCandidate
FROM CandidateList_Candidates cl
where CandidateListID = @candidateListIDs

WHILE(@loopcount <= @listcount)
    BEGIN
        SET @candidateListID = (SELECT CandidateListID FROM #tmpListCandidate WHERE Id = @loopcount)
        SET @candidateID = (SELECT CandidateID FROM #tmpListCandidate WHERE Id = @loopcount)

        EXEC usp_ApplyRankingRules @candidateListID, @candidateID, @var_weightage OUTPUT

        IF EXISTS (SELECT 1 FROM #tempRPTCandidateCardReport WHERE listID = @candidateListID AND candidateID = @candidateID)
            BEGIN
                UPDATE #tempRPTCandidateCardReport SET weightage = @var_weightage WHERE listID = @candidateListID AND candidateID = @candidateID
            END
        ELSE
            BEGIN
                INSERT INTO #tempRPTCandidateCardReport (listID, candidateID, weightage)
                    VALUES (@candidateListID, @candidateID, @var_weightage)
            END
        SET @loopcount = @loopcount + 1
    END

select listid,candidateid,weightage from #tempRPTCandidateCardReport

IF OBJECT_ID('tempdb..#tmpListCandidate') IS NOT NULL
BEGIN
    DROP TABLE #tmpListCandidate
    DROP TABLE #tempRPTCandidateCardReport
END

END
GO

A: I'm not going to comment on several aspects of the stored procedure, but I think you want:
CREATE PROCEDURE [dbo].[usp_RPT_CandidateCardReporttest] (
   @candidateListID varchar(36)
)
AS
BEGIN
    . . .
    SELECT CandidateListID, CandidateID,
           ROW_NUMBER() OVER (ORDER BY cl.CandidateID) AS Id
    INTO #tmpListCandidate
    FROM CandidateList_Candidates cl
    WHERE CandidateListID = @CandidateListID OR @CandidateListID IS NULL;

    SELECT @ListCounct = COUNT(*)
    FROM #tmpListCandidate ;

    . . .
END;

Notes:

*

*Set the row count based on the number of rows in the temporary table.  The above code uses SELECT COUNT(*) to be explicit, but @@ROWCOUNT would work just as well.

*There is no need to delete the temporary table or to test for its existence.  Temporary tables will only "live" for the duration of each call of the stored procedure.

*BUT . . . I would actually recommend using a cursor instead.  I'm not a fan of cursors, but the use-case of calling a stored procedure for each row of a result set is definitely one place where they are helpful.  Not temporary table or looping values would then be necessary.

If you are going to loop through a temporary table (or table variable), then code such as this:
   SET @candidateListID = (SELECT CandidateListID FROM #tmpListCandidate WHERE Id = @loopcount)
   SET @candidateID = (SELECT CandidateID FROM #tmpListCandidate WHERE Id = @loopcount)

Can be replaced with:
SELECT @candidateListID = CandidateListID,
       @candidateID = CandidateID
FROM #tmpListCandidate
WHERE Id = @loopcount;


text:
Q: Select tag to set a session variable I have a web page written in html such that it displays the results of a query in the form of a list. Each record includes a link which when pressed opens a pdf report for that record.
I would like to be able to allow the user the option of choosing what might be included and have used a <select> tag at the top of the page to enable them to make a choice (in the example "Include comments in the report")

Is it possible for a session variable to be set so that each time the <select> is picked the session variable takes the value of the selection, enabling me to then know what needs to be included when the pdf document is created?
If not, are there any ways of achieving what I am trying to achieve?
This is an edited version of the code that is used to create the download link is:
Include comments in report

<select value="selectedReport">
<option value="Yes">Yes</option>
<option value="No">No</option>
</select>

<?php
while($row = mysql_fetch_array($result))
{
?>

<form name="createPdf" action="https://...createpdf.php" method="Post" target="_blank">
<input name="pdfID" size="0" type="submit" value="<?php echo $row['pdfID'] ?>" class="pdfButton">
</form>

<?php
}
?>

A: If you're redirecting to a new Page using PHP you just need to use $_POST['selectedReport'] in your php file:
$selectedReport = $_POST['selectedReport'];

And your select should be like this:
<select name="selectedReport">
   <option value="1">Report1</option>
   <option value="2">Report2</option>
   <option value="3">Report3</option>
</select>

And if you are in the same page you can do it with Javascript:
var sel = document.getElementById("selectedReport");

//to get the value of the selected option
var selectedReport = sel.options[sel.selectedIndex].value;

//to get the text of the selected option
var selectedReport = sel.options[sel.selectedIndex].text;

And your select Should be like this:
<select id="selectedReport">
   <option value="1">Report1</option>
   <option value="2">Report2</option>
   <option value="3">Report3</option>
</select>

EDIT:
Answering to your comment: you can use a hidden input inside your Form like this:
<form action="..." method="POST">
<input type="hidden" id="myReport" value=""/>
//... and the content of your form goes here
</form>

And use the following javascript function to put the selected option in the hidden input value so you can submit it with your form:
function takeValue(){
var sel = document.getElementById("selectedReport");
var selectedReport = sel.options[sel.selectedIndex].text;
//put the selected value in the hidden input value
document.getElementById("myReport").value=selectedReport;
}

And apply it using the onchange event of your select like this:
<select id="selectedReport" onchange="takeValue()">
   <option value="1">Report1</option>
   <option value="2">Report2</option>
   <option value="3">Report3</option>
</select>

And the value will be submitted with the form.

A: I have found a really good solution to this and so thought I would share it:
HTML - the script sends a request to setSessionVariable.php when the select chosen

The select tag - when option is chosen the takeValue function is called.
<select id="selectedReport" onchange="takeValue()">
<option value="Yes" Selected>Yes</option>
<option value="No" >No</option>
</select>

setSessionVariable.php  - runs in the background when select is chosen and sets session variable $selected.
<?php
session_start();
if (isset($_GET[choiceSelected]))
{
$_SESSION['$selected']=$_GET[choiceSelected];
}

?>


text:
Q: Is it possible to import a MySQL 5.7.21 database into a MySQL 5.6.38 setup? I am running MAMP 4 with MySQL 5.6.38 and a team-mate of mine is running MAMP 5 with MySQL 5.7.21.
He has exported a database for me to use but I'm getting the following error when I import their database using Sequel Pro:
You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'json NOT NULL,
  `dateCreated` datetime NOT NULL,
  `dateUpdated` datetime NOT N' at line 5

I am assuming the MySQL server version phrase is hinting that the mis-matched MYSQL versions is the issue here.
Upgrading to MAMP 5 may hurt other projects with other clients I have that all use my MAMP 4 install, but upgrading MySQL within MAMP 4 doesn't look simple.
Any advice on how to resolve this issue would be appreciated.
Thanks.

A: No, you can't import any 5.7 database to a 5.6 instance.
Every version — of every brand of database — introduces new features. If the exported database from 5.7 uses some features that are not recognized by 5.6, you must either modify the export (as the comments above state), or else upgrade your own instance to match the version the export was made from.
Is it possible to design a database in 5.7 that uses only features that are also present in 5.6? Yes, of course.
But that doesn't seem to be the case for your team-mate's database.


text:
Q: How do I fix a permission error using Cancan? I am trying to do authentications with Cancan in my Rails app and am having trouble doing so.  I have 2 columns in my user table named admin and owner, both of which are boolean.  My ability.rb file checks if this is true and then offers the appropriate permissions.  It seems that the permissions for a user that isn't signed in + a user that is an admin work.  However, the permission for an owner doesn't seem to work.  I'm not able to view the link in my view that utilizes this permission.
I have put load_authorize_resource at the top of my PlacesController.
def initialize(user)
    user ||= User.new  # Guest user
    if user.admin?
        can :manage, :all
    else
        can :read, :all
        if user.owner?
            can :create, Place
        end
    end

    # can :read, :all
end

I'm able to view this as an admin, but not as an owner...but I should be able to as an owner.
<% if can? :create, @place %>
    <%= link_to 'New place', new_place_path %>
<% end %>

A: You should write,
 <% if can? :create, Place %>
  <%= link_to 'New place', new_place_path %>
 <% end %>

Create works on class level rather than object.


text:
Q: How to crop part of the image outside of a collectionview cell in swift I have a simple design app where i have just a round image on the top right corner. I am trying to do something like what they have on the bloom app.

See how the edge of the image is getting cut off at the edge of the cell, I am trying to go for something like that, but I keep getting this.

I had a feeling that the entire cell is just an image so that it how it looks like that, but I don't know if making an entire cell image is what i want to do, since I plan to eventually be able to change the cell's color and the circle image's color at different times, and use different color, so it is not in my interest to use just a large image for the cell, since I might want to use different images too. It also seems to be easier to figure this out, than just create a couple dozen different images, which also increases it's app size.
I have looked at a few different posts, but none of them seems to work for me.
I tried:

*

*setting the frame of the image and background to the bounds

*using all the different content mode

*using clipsToBound, and masksToBounds and set them to either true and false.

this is what is in my cell:
    contentView.addSubview(cellBackgrounded)
        cellBackgrounded.addSubview(imgView)
//        imgView.frame = cellBackgrounded.bounds  set this to = self.bounds, contentView.frame
//        contentView.frame = self.bounds
//        cellBackgrounded.frame = self.bounds
//        imgView.layer.masksToBounds = false
        imgView.translatesAutoresizingMaskIntoConstraints = false
        imgView.image = UIImage(named: "Oval")?.withRenderingMode(.alwaysTemplate)
        imgView.clipsToBounds = true
        imgView.contentMode = .scaleToFill
        imgView.tintColor = .red

        cellBackgrounded.translatesAutoresizingMaskIntoConstraints = false
        cellBackgrounded.backgroundColor = .white
        cellBackgrounded.addSubview(cellName)
        cellName.translatesAutoresizingMaskIntoConstraints = false
        cellName.font = UIFontMetrics.default.scaledFont(for: UIFont.systemFont(ofSize: 50, weight: .bold))
        cellName.textColor = .black
        cellName.numberOfLines = 0
        cellName.textAlignment = .center

        darkShadow.frame = self.bounds
        darkShadow.cornerRadius = 15
        darkShadow.backgroundColor = UIColor.offWhite.cgColor
        darkShadow.shadowColor = UIColor.black.withAlphaComponent(0.2).cgColor
        darkShadow.shadowOffset = CGSize(width: 10, height: 10)
        darkShadow.shadowOpacity = 1
        darkShadow.shadowRadius = 15
        self.layer.insertSublayer(darkShadow, at: 0)

        NSLayoutConstraint.activate([
            cellBackgrounded.topAnchor.constraint(equalTo: topAnchor),
            cellBackgrounded.leadingAnchor.constraint(equalTo: leadingAnchor),
            cellBackgrounded.trailingAnchor.constraint(equalTo: trailingAnchor),
            cellBackgrounded.bottomAnchor.constraint(equalTo: bottomAnchor),
            imgView.topAnchor.constraint(equalTo: cellBackgrounded.topAnchor, constant: -40),
            imgView.trailingAnchor.constraint(equalTo: cellBackgrounded.trailingAnchor, constant: 40),
            cellName.centerXAnchor.constraint(equalTo: cellBackgrounded.centerXAnchor),
            cellName.centerYAnchor.constraint(equalTo: cellBackgrounded.centerYAnchor),
            cellName.leadingAnchor.constraint(equalTo: cellBackgrounded.leadingAnchor, constant: 10),
            cellName.trailingAnchor.constraint(equalTo: contentView.trailingAnchor, constant: -10),
            imgView.heightAnchor.constraint(equalTo: cellBackgrounded.heightAnchor, multiplier: 0.7),
            imgView.widthAnchor.constraint(equalTo: cellBackgrounded.widthAnchor, multiplier: 0.7)
        ])

if there is anything else i can help with please ask,
Thank you

A: Use clipToBounds
According to apple docs :

When the value of this property is true, Core Animation creates an
implicit clipping mask that matches the bounds of the layer and
includes any corner radius effects

You must do clipsToBound to the containerView to solve this problem
containerView.clipsToBound = true


text:
Q: facebook FQL query performance within foreach loop? I'm trying to request some information from facebook's FQL, but the request is a little slow.
$friend = "SELECT uid2 FROM friend WHERE uid1 = me() LIMIT 30";

  $friendSQL = $facebook->fql($friend);
  foreach ($friendSQL as $friends_id){
    $uid2 = $friends_id['uid2'];
     $query = "SELECT uid,username,name,pic_small FROM user WHERE uid='".$uid2."'";
     $friend_info = $facebook->fql($query);
    echo "<pre>";
    print_r($friend_info);
    echo "</pre>";
  }

So basically, I'm getting a list of 30 friends and I'm trying to use a foreach loop to get other information from uid2 (which is my friend)
I've noticed that the request is slow. Is there another way of getting information of my friends?
Thanks!

A: Your select statement could look something like:
SELECT uid,username,name,pic_small FROM user WHERE uid IN (SELECT uid2 FROM friend WHERE uid1 = me() LIMIT 30)

So you won't have to use the loop anymore. This is pretty much the same as FQL Multiquery.

A: Your script is slow because it makes new HTTP request in each iteration and every new request takes a lot of time. Correct way to do this is using FQL.multiquery. With multiquery you can get all info you want in one HTTP request without using foreach.


text:
Q: Is there any case in which the `cd .` (single dot) command could be useful? This should theoretically just be redundant since it changes into the current working directory. Anyway, is there any scenario in practice, where this command could be useful?

A: At least two cases comes immediately to my mind where cd . can be useful:

*

*Update the inode number of the current directory
Let's say in terminal1 you are inside some directory and in another terminal2 you delete this directory and create new directory with the same name as deleted one. Then to be able to do whatever useful inside this directory (e.g. create a file) in termminal1 you can do cd . what will update the inode number of this directory.

*Resolve directories physically
If directory name is a symbolic link, you can cd -P . to resolve link components physically. This feature comes directly from POSIX. Yes, this requires -P option, so its not bare cd ., but still...

A: There's another minor effect, it sets $OLDPWD.
That variable should be empty when you start a new terminal until you cd to somewhere.
And there's one possible usage that I can think of, which might not be very useful (and a bit naive) but here it is:
cd - navigates to $OLDPWD, so you can use in combination with cd . to navigate forth and back to the same directory after some operation:
cd .; for i in {1..100}; do cd -;mkdir "d$i"; cd "d$i"; touch a; done

Not something I'd do in a script, but maybe directly in the command line or some code golfing...

A: While cd . is essentially a null operation, I can see a case where pushd . might presumably be relevant.
Also, in a script where a target directory is specified interactively, procedurally, or from an argument, a command such as:
cd $destinationpath

may evaluate to
cd .

should the variable be so assigned.


text:
Q: Send a email with content my domain to inbox Gmail When i send a email with content my domain, it putting in spam gmail. my domain is neginph.com and ip it is 50.115.44.157.
How cand put this email (content my domain) in inbox gmail. what do i do?

A: I your e-mail is being put in SPAM, you won't be able to do anything. The mailbox server controls the SPAM with its own algorithm.
Try to add your email@domain to trusted senders list and write e-mails with less content.
Read more about best pratices to prevent SPAM: http://msg.wikidoc.info/index.php/Spam_best_practices


text:
Q: Unix: File have 28 columns separated by space, print column 8 unique values with sum of column 16 to column28 Sample File.txt:

"Object_Type" "710" "30" "14" "Partner" "Rpt" "Cool" "0ICPRP900" "Des_Space" "HBBREX" "soon_Type" "FY28" "Jan" "50" "USD_US" #Mi #Mi #Mi 0.006641 0 0 0 0 0 0 0 0 0
"Object_Type" "710" "30" "14" "Partner" "Rpt" "Cool" "0ICPRP 900" "Des_Space" "HBBREX" "soon_Type" "FY28" "Jan" "50" "USD_US" #Mi #Mi #Mi 0.01 0 0 0 0 0 0 0 0 0
"Object_Type" "710" "30" "14" "Partner" "Rpt" "Cool" "0ICPRP A&B_900" "Des_Space" "HBBREX" "soon_Type" "FY28" "Jan" "50" "USD_US" #Mi #Mi #Mi 0.641 0 0 0 0 0 0 0 0 0

Looking for output line:
0ICPRP900 0.006641
0ICPRP 900 0.01
0ICPRP A&B_900 0.641

I have tried below command and it's printed column 8 (column not printed after have space special char )
awk '{a[$8]+=$17+$18+$19+$20+$21+$22+$23+$24+$25+$26+$27+$28}END{for (i in a)
print i,bc a[i]}' File.txt

Output:
"0ICPRP900" 0.006641
"0ICPRP 0.01
"0ICPRP 0.641

Any suggestions how to get unique column8 (column8 with in "") with sum of column 16 to Column 28

A: With GNU awk, you could try following. Written and tested with your shown samples.
awk -v FPAT='"[^"]+"|[^"]*' '
{
  sum=0
  num=split($NF,arr," ")
  for(i=1;i<=num;i++){
    sum+=arr[i]
  }
  gsub(/"/,"",$15)
  print $15,sum
}
' Input_file

Explanation: Adding detailed explanation for above.
awk -v FPAT='"[^"]+"|[^"]*' '  ##Starting awk program from here, setting FPAT to set fields as per requirement.
{
  sum=0                        ##Nullifying sum here.
  num=split($NF,arr," ")       ##Splitting last field into array here.
  for(i=1;i<=num;i++){         ##Traversing through all elements of arr here.
    sum+=arr[i]                ##Creating sum from array elements.
  }
  gsub(/"/,"",$15)             ##Removing all " here
  print $15,sum                ##Printing 15 field along with sum here.
}
' Input_file                   ##mentioning Input_file name here.

Output will be as follows:
0ICPRP900 0.006641
0ICPRP 900 0.01
0ICPRP A&B_900 0.641

A: You really have there is a form of CSV and it would serve well to use a proper parser for CSV. It is a surprisingly complex format...
The lightest weight CSV parser commonly available at the command line is Ruby (but Python, Perl work well too...)
Here is a Ruby:
ruby  -r csv -lane '
   BEGIN{ options={:col_sep=>" ", :quote_char=>"\""} }
   CSV.parse($_, **options)
    { |r| puts "#{r[7]} #{r[18..27].inject(0){|s,x| s+x.to_f}}" }' file

Prints:
0ICPRP900 0.006641
0ICPRP 900 0.01
0ICPRP A&B_900 0.641

A: Using any awk:
$ awk -F'"' '{n=split($31,f," "); sum=0; for (i=4; i<=n; i++) sum+=f[i]; print $16, sum}' file
0ICPRP900 0.006641
0ICPRP 900 0.01
0ICPRP A&B_900 0.641

Or using GNU awk for FPAT and gensub():
$ awk -v FPAT='"[^"]*"|[^ ]+' '{sum=0; for (i=19; i<=NF; i++) sum+=$i; print gensub(/"/,"","g",$8), sum}' file
0ICPRP900 0.006641
0ICPRP 900 0.01
0ICPRP A&B_900 0.641

or if by unique column8 you mean you want to sum the values for multiple occurrences of the same $8 value across the input file you can do either of:
any awk:
awk -F'"' '
    {
        n = split($31,f," ")
        for (i=4; i<=n; i++) {
            sum[$16] += f[i]
        }
    }
    END {
        for (key in sum) {
            print key, sum[key]
        }
    }
' file

GNU awk:
awk -v FPAT='"[^"]*"|[^ ]+' '
    {
        for (i=19; i<=NF; i++) {
            sum[gensub(/"/,"","g",$8)] += $i
        }
    }
    END {
        for (key in sum) {
            print key, sum[key]
        }
    }
' file


text:
Q: How to get VHost Server Name with Java? Hello Stackoverflow Community,
i'm getting a bit confused with getting the Servername of a Vhost. Im working with my apache and a Tomcat. The Apache is redirecting the Requests to my Tomcat to start a Function.
The Point is that i have to identify the Servername. The purpose is to get the Servername and decide like if the servername is like office23.de then the server has to load the configuration for office23 if other office then load other configurations. I hope i could explain it a bit.
What i did so far:
i added into Tomcat's server.xml :

also added in Apache's httpd.conf:
ProxyRequests on

ProxyPass         /getTest/  http://localhost:8080/Test/
ProxyPassReverse  /getTest/  http://localhost:8080/test/

and the lines to load the mod_proxy stuff.
additional i configured the httpd-vhosts.conf like this:

    ServerName js.local.test.de
DocumentRoot "D:/downloads/xampp/tomcat/webapps"

<Directory />
    Require all granted
    Options Indexes FollowSymLinks Includes ExecCGI
    AllowOverride All
    Order allow,deny
    Allow from all
</Directory>

ErrorLog "D:/downloads/xampp/apache/logs/virtualHost.log"
CustomLog "D:/downloads/xampp/apache/logs/customLog.log" common

i can reach my application through the vhost adress but when i try to get the Host Header it says that its localhost:8080.
I also changed the windows hostfile.
Does any opurtunity excist that allows me to get the vhost name?

A: If you enable ProxyPreserveHost on the reverse proxy, the Host: header is kept in the request to the proxy, instead of being replaced with the hostname specified in the ProxyPass (localhost, in your case).  That should help you get the right name on the back-end.
Mangling the hosts file won't do you any good, and if you forget you did that, it'll probably come back to haunt you, later on.


text:
Q: ImageIO.write strange behaviour: different runs, different compression I was trying to get some stats about the compression performance of java ImageIO compression with PNG files, and I was bitten by this crazy behaviour.
I have a bank of PNG (say) 150 test images, and I fed with them this simple code:
for (File ori : files) {
   BufferedImage img = ImageIO.read(ori);
   File dest = new File("C:/temp/x.png"); // whatever
   OutputStream nos = new FileOutputStream(dest)
   ImageIO.write(img, "PNG", nos);
   nos.close();
   long size = dest.length();
   // report size
}

(I've stripped down the exception handling and some unimportant code - also, in my real implementation I don't write to a File but to a dummy outputstream that just count bytes - all that has no influence). This is call from a console Java program, nothing much more than the a main() that calls that. Running from Eclipse, JRE 1.7.0_55-b14 (32bits).
My problem is that this gives quite different results in different runs. Actually, it gives two different sets of results. In one of them, let's call it the "good" case, the compressed sizes are quite smaller (average ~ 87%) thant the "bad" case. I get always these precise two set of results, and only these, and never mixed.
When I get one of the two results seems random, I could not find a pattern. If I run this with only one file, instead of with a long list, I only get one result (the bad one). I could reproduce this with only one image, though the "good" case happens more sporadically, see update below.
I've examined some pairs of good/bad images, and they are OK, no strange things, it just seems as if they were encoded by different encoders.
Can anyone explain this?

Update: this is a pair of "good" and "bad" images.
Update2: Ok, I could reproduce this with only one image. Here's the code:
import java.awt.image.BufferedImage;
import java.io.*;
import java.util.Locale;

import javax.imageio.ImageIO;

public class ImageIoTest {

    public static void main(String[] args) throws Exception {
    Locale.setDefault(Locale.US);
    for (int i = 0; i < 3; i++)
        testWith(new File("C:/temp/m0550.png"));
}

private static long testWith(File f) throws Exception {
    File dest = new File(f.getParent(), "new" + f.getName());
    BufferedImage img = ImageIO.read(f);
    OutputStream nos = new FileOutputStream(dest);
    ImageIO.write(img, "PNG", nos);
    nos.close();
    long size = dest.length();
    System.out.printf("%s\t%d\n", dest, size);
    return size;
}

Set you image path appropiately. I use this image (1103429 bytes), though that should not be critical (but at this time I don't trust any "should"). IF I run the above repeteadly, the 4 calls inside the loop return always the same value. But that same value varies from run to run. Sometimes it gives 1099207 sometimes it gives 1498218 (more strangely even, commenting the Locale line sometimes I get the alteration)... Puzzling.

Final update and explanation: @anonymous, in the accepted answer, got it. The issue was having two ImageWriters (I think this is because once I installed JAI). And it seems that, in that situation, Java selects the prefered one based on... God knows what, perhaps at random.
Here we get again the deterministic behaviour we all appreciate:
public class ImageIoTest {

    public static void main(String[] args) throws Exception {
        Iterator<ImageWriter> iter = ImageIO.getImageWritersByFormatName("PNG");
        for(;iter.hasNext();) {
            ImageWriter iw = iter.next();
            testWith(new File("C:/temp/m0550.png"),iw);
        }
    }

    private static long testWith(File f, ImageWriter iw) throws Exception {
        File dest = new File(f.getParent(), "new" + f.getName());
        BufferedImage img = ImageIO.read(f);
        OutputStream nos = new FileOutputStream(dest);
        ImageOutputStream ios = ImageIO.createImageOutputStream(nos);
        iw.setOutput(ios);
        iw.write(img);
        ios.close();
        nos.close();
        long size = dest.length();
        System.out.printf("%s\t%d\t%s\n", dest, size,iw.getOriginatingProvider().getPluginClassName());
        return size;
    }

}

Which in my case prints:
C:\temp\newm0550.png    1099207 com.sun.media.imageioimpl.plugins.png.CLibPNGImageWriter
C:\temp\newm0550.png    1498218 com.sun.imageio.plugins.png.PNGImageWriter

A: I am running Java 1.8.0.
But then I remember I read that javadoc mentioning about using arbitrary ImageWriter. So I wrote the following code and it printed only 1 ImageWriter. Maybe you have multiple ImageWriter in your system and this could explain the different results you get on each run. `
For Java 8
ImageIO.getImageWritersByFormatName("PNG").forEachRemaining(System.out::println);

For pre Java 1.8
for(Iterator<ImageWriter> iter=ImageIO.getImageWritersByFormatName("PNG");iter.hasNext();) {
    System.out.println(iter.next());
}

Try and see how many ImageWriters you get. If it only list one ImageWriter for you, I am afraid I'm out of ideas.
Just a thought. Let's just say you have multiple ImageWriter, each call to ImageIO.write should give you a different result because an arbitrary ImageWriter is chosen. Unless it only does that on the first call and subsequent calls just re-use it rather than trying to find another "random" ImageWriter to use. Then your result could be explained.

A: Cannot reproduce. I ran your code 100 times with a set of images varying from 1k to 2.5M, and then 1000 times with your image, and always got the same results. My counting output stream:
class CountingOutputStream extends OutputStream
{
    int  size;

    public int  size()
    {
        return size;
    }

    @Override
    public void write(int b) throws IOException
    {
        size++;
    }

    @Override
    public void write(byte[] b) throws IOException
    {
        size += b.length;
    }

    @Override
    public void write(byte[] b, int offset, int length) throws IOException
    {
        size += length;
    }
}

Your counting may vary ;-) I don't see what the Locale has to do with it. There are mysterious references to it localising compression settings but I don't know what that would mean.
java -version:
java version "1.7.0"
Java(TM) SE Runtime Environment (build 1.7.0-b147)
Java HotSpot(TM) Client VM (build 21.0-b17, mixed mode, sharing)