text:
Q: Image and Button title in VStack button Code below in xcode swiftui will generate the BEFORE screen but I want to move the House image just above the "Houses" text (see AFTER screen), I have spent a full day on this and I can't figure out how to make it possible, if anyone is willing to step in for help will be much appreciated! Full code provided below...
Before and After VStack button
import SwiftUI

struct LightGreenButton: View {
    var body: some View {
        VStack {

            Image(systemName: "house")
              .resizable()
              .frame(width: 50, height: 50, alignment: .center)
              //.opacity(0.6)
              .clipped()
              .foregroundColor(Color(#colorLiteral(red: 0.005, green: 0.4422248602, blue: 0.3870742321, alpha: 1)))
              .offset(x: 0, y: 0)

            Text("Houses")
                .font(.system(size: 20, weight: .semibold, design: .rounded))
                .frame(width: 150, height: 100)
                .foregroundColor(Color(#colorLiteral(red: 0.005, green: 0.4422248602, blue: 0.3870742321, alpha: 1)))
                .background(
                    ZStack {
                        Color(#colorLiteral(red: 0.6574724317, green: 0.8923466802, blue: 0.8671938181, alpha: 1))

                        RoundedRectangle(cornerRadius: 16, style: .continuous)
                            .foregroundColor(.white)
                            .blur(radius: 4)
                            .offset(x: -8, y: -8)

                        RoundedRectangle(cornerRadius: 16, style: .continuous)
                            .fill(
                                LinearGradient(gradient: Gradient(colors: [Color(#colorLiteral(red: 0.6574724317, green: 0.8923466802, blue: 0.8671938181, alpha: 1)), Color.white]), startPoint: .topLeading, endPoint: .bottomTrailing)
                        )
                            .padding(2)
                            .blur(radius: 1)
                    }

                )

                .clipShape(RoundedRectangle(cornerRadius: 16, style: .continuous))
                .shadow(color: Color(#colorLiteral(red: 0.8696053624, green: 0.8697276711, blue: 0.8695667386, alpha: 1)), radius: 20, x: 20, y: 20)
                .shadow(color: Color(#colorLiteral(red: 1, green: 1, blue: 1, alpha: 1)), radius: 20, x: -20, y: -20)
        }
        .frame(maxWidth: .infinity, maxHeight: .infinity)
        .background(Color(#colorLiteral(red: 0.9447055279, green: 0.954059048, blue: 0.954059048, alpha: 1)))
        .edgesIgnoringSafeArea(.all)
    }
}

struct LightGreenButton_Previews: PreviewProvider {
    static var previews: some View {
        LightGreenButton()
    }
}

A: Here is a solution. Tested with Xcode 11.4 / iOS 13.4.

struct LightGreenButton: View {
    var body: some View {
        VStack {

            Image(systemName: "house")
              .resizable()
              .frame(width: 50, height: 50, alignment: .center)
              //.opacity(0.6)
              .clipped()
              .foregroundColor(Color(#colorLiteral(red: 0.005, green: 0.4422248602, blue: 0.3870742321, alpha: 1)))
              .offset(x: 0, y: 0)

            Text("Houses")
                .font(.system(size: 20, weight: .semibold, design: .rounded))
                .foregroundColor(Color(#colorLiteral(red: 0.005, green: 0.4422248602, blue: 0.3870742321, alpha: 1)))
        }
        .frame(width: 150, height: 100)
        .background(
            ZStack {
                Color(#colorLiteral(red: 0.6574724317, green: 0.8923466802, blue: 0.8671938181, alpha: 1))

                RoundedRectangle(cornerRadius: 16, style: .continuous)
                    .foregroundColor(.white)
                    .blur(radius: 4)
                    .offset(x: -8, y: -8)

                RoundedRectangle(cornerRadius: 16, style: .continuous)
                    .fill(
                        LinearGradient(gradient: Gradient(colors: [Color(#colorLiteral(red: 0.6574724317, green: 0.8923466802, blue: 0.8671938181, alpha: 1)), Color.white]), startPoint: .topLeading, endPoint: .bottomTrailing)
                )
                    .padding(2)
                    .blur(radius: 1)
            })

            .clipShape(RoundedRectangle(cornerRadius: 16, style: .continuous))
            .shadow(color: Color(#colorLiteral(red: 0.8696053624, green: 0.8697276711, blue: 0.8695667386, alpha: 1)), radius: 20, x: 20, y: 20)
            .shadow(color: Color(#colorLiteral(red: 1, green: 1, blue: 1, alpha: 1)), radius: 20, x: -20, y: -20)
        .frame(maxWidth: .infinity, maxHeight: .infinity)
        .background(Color(#colorLiteral(red: 0.9447055279, green: 0.954059048, blue: 0.954059048, alpha: 1)))
        .edgesIgnoringSafeArea(.all)
    }
}


text:
Q: building a tensorflow based android app with tensorflow as a repository This is like a follow up question from Build an android app using Tensorflow. I'd like to separate the android example project from tensorflow git repo and be able to build it separately with tensorflow as a dependency. This is my folder structure
my_project
|-- WORKSPACE
|-- android
|   |-- BUILD
|   `-- ...
|-- tensorflow
|   |-- tensorflow
|   |   |   |-- workspace.bzl
|   |   |   |-- tensorflow.bzl
|   |   |   `-- ...
|   |-- WORKSPACE
|   |-- BUILD
.    `-- ...

where android app is just a copy of Tensorflow Android example.
The root WORKSPACE file has following contents:
workspace(name = "my_android_app")

local_repository(
     name = "org_tensorflow",
     path = "tensorflow", # Relative path to the tensorflow workspace
 )

load('//android:workspace.bzl', 'android_workspace')
android_workspace()

 # Specify the minimum required bazel version.
load("@org_tensorflow//tensorflow:tensorflow.bzl", "check_version")
check_version("0.3.1")

android/workspace.bzl looks like this
load('@org_tensorflow//tensorflow:workspace.bzl', 'tf_workspace')

def android_workspace():
  tf_workspace()

and android/BUILD has the same contents as Tensorflow Android example BUILD except that I've prefixed @org_tensorflow to //tensorflow everywhere, for example
"@org_tensorflow//tensorflow:tensorflow.bzl"
  "@org_tensorflow//tensorflow/contrib/android:android_tensorflow_inference_jni",
"@org_tensorflow//tensorflow/core:android_tensorflow_lib",

when I try to build the main target tensorflow_demo, it gives this error
no such package 'tensorflow': Package crosses into repository @org_tensorflow and referenced by '//android:libtensorflow_demo.so'.
ERROR: Analysis of target '//android:tensorflow_demo' failed; build aborted.

EDIT:
I was able to decouple Tensorflow Android demo from Tensorflow source, thanks to Kristina. You can use the following git as a template for your Tensorflow Android projects.
https://github.com/devinsaini/tensorflow_android

A: Ah, okay, I see what you're doing. Thanks for elaborating.
The problem here is a bit subtle: copts = tf_copts() calls a function in @org_tensorflow that looks like this:
def tf_copts():
  return (["-DEIGEN_AVOID_STL_ARRAY",
           "-Iexternal/gemmlowp",
           "-Wno-sign-compare",
           "-fno-exceptions"] +
          if_cuda(["-DGOOGLE_CUDA=1"]) +
          if_android_arm(["-mfpu=neon"]) +
          if_x86(["-msse4.1"]) +
          select({
              "//tensorflow:android": [
                  "-std=c++11",
                  "-DTF_LEAN_BINARY",
                  "-O2",
              ],
              "//tensorflow:darwin": [],
              "//tensorflow:windows": [
                "/DLANG_CXX11",
                "/D__VERSION__=\\\"MSVC\\\"",
                "/DPLATFORM_WINDOWS",
                "/DEIGEN_HAS_C99_MATH",
                "/DTENSORFLOW_USE_EIGEN_THREADPOOL",
              ],
              "//tensorflow:ios": ["-std=c++11"],
              "//conditions:default": ["-pthread"]}))

Basically a switch statement to use different flags on different platforms. However, because load()s are evaluated before select()s, your BUILD file suddenly "contains" references to //tensorflow.
To fix, the easiest options are to either hard-code the copts you need or redefine tf_copts in your local repository.
How to track down incorrect references in general
I was actually pretty baffled by the error you were getting, so here's a brain dump of how one usually goes about debugging this kind of thing.
The usual way to track down this kind of cross reference is 1) to examine your BUILD file (maybe the deps are just wrong) or 2) print out how Bazel actually "sees" the BUILD file. For example, if you wanted to print the evaluated build rule in this case, you could do:
$ bazel query --output=build //:libtensorflow_demo.so
# /home/kchodorow/gitroot/so41153199/BUILD:18:1
cc_binary(
  name = "libtensorflow_demo.so",
  tags = ["manual", "notap"],
  deps = ["//:demo_proto_lib_cc", "@org_tensorflow//tensorflow/contrib/android:android_tensorflow_inference_jni", "@org_tensorflow//tensorflow/core:android_tensorflow_lib", "@org_tensorflow//tensorflow/contrib/android:jni/version_script.lds"],
  srcs = ["//:jni/box_coder_jni.cc", "//:jni/imageutils_jni.cc", "//:jni/object_tracking/config.h", "//:jni/object_tracking/flow_cache.h", "//:jni/object_tracking/frame_pair.cc", "//:jni/object_tracking/frame_pair.h", "//:jni/object_tracking/geom.h", "//:jni/object_tracking/gl_utils.h", "//:jni/object_tracking/image-inl.h", "//:jni/object_tracking/image.h", "//:jni/object_tracking/image_data.h", "//:jni/object_tracking/image_neon.cc", "//:jni/object_tracking/image_utils.h", "//:jni/object_tracking/integral_image.h", "//:jni/object_tracking/jni_utils.h", "//:jni/object_tracking/keypoint.h", "//:jni/object_tracking/keypoint_detector.cc", "//:jni/object_tracking/keypoint_detector.h", "//:jni/object_tracking/log_streaming.h", "//:jni/object_tracking/object_detector.cc", "//:jni/object_tracking/object_detector.h", "//:jni/object_tracking/object_model.h", "//:jni/object_tracking/object_tracker.cc", "//:jni/object_tracking/object_tracker.h", "//:jni/object_tracking/object_tracker_jni.cc", "//:jni/object_tracking/optical_flow.cc", "//:jni/object_tracking/optical_flow.h", "//:jni/object_tracking/sprite.h", "//:jni/object_tracking/time_log.cc", "//:jni/object_tracking/time_log.h", "//:jni/object_tracking/tracked_object.cc", "//:jni/object_tracking/tracked_object.h", "//:jni/object_tracking/utils.h", "//:jni/object_tracking/utils_neon.cc", "//:jni/rgb2yuv.cc", "//:jni/rgb2yuv.h", "//:jni/yuv2rgb.cc", "//:jni/yuv2rgb.h"],
  linkopts = ["-landroid", "-ljnigraphics", "-llog", "-lm", "-z defs", "-s", "-Wl,--version-script", "@org_tensorflow//tensorflow/contrib/android:jni/version_script.lds"],
  linkstatic = True,
  linkshared = True,
)

However, this doesn't actually help you in this case, because it doesn't show the copts!
So, after running the query, I ended up "binary searching" the BUILD rule: I commented out everything but the srcs, tried building, then gradually uncommented parts until I got the error.

redpajama_set_name: RedPajamaStackExchange


text:
Q: add static time in calendars without timezone is there any chance to add a event in major calendars without checking timezone of calendar settings?
Like if event is from another country which is in different timezone at 10:00:00 than it should be add in my calendar at 10:00:00
Like this:
https://outlook.live.com/owa/?path=/calendar/action/compose&subject=Afspraak%20uitnodiging&startdt=2019-06-29T10:00:00.000+0530&enddt=2019-06-29T10:30:00.000+0530&body=Bijgevoegd%20vind%20u%20de%20online%20uitnodiging%20voor%20uw%20afspraak.&location=Straatnaam%202B,%20A12BC3,%20Stad&allday=false&addcalendarlink=true
This event created from Netherlands which has timezone (+02:00) but right now i am in india timezone is (+05:30) but it is adding in my calendar in different time.
So i want to add a static time. Can anyone help please?

A: You should always

*

*store utc time

*represent local time

For example, .. now is 12:45 circa. But I am living in Italy (UTC+1) and with Legal time, .. this means that in Italy the time is 14:45. In Tokyo (UTC+9) 20:45 and so on.

A: No, Outlook always uses UTC.
Tasks are the only exception, but they are timeless.


text:
Q: SwiftUI view sometimes creates Thread 1: EXC_BAD_ACCESS (code=1, address=0x6002005b8368), when I put array as a parameter SwiftUI View file
struct NoteListView: View {
    @EnvironmentObject var presenter: NoteListPresenter
    var body: some View {
        NavigationView{
            AddNoteButton()
            Text(presenter.noteViewModels[0].title)
        }
    }
}

struct NoteListView_Previews: PreviewProvider {
    static var previews: some View {
        NoteListView()
    }
}

I first got this error when I finished writing the logic and started to writing Views. After add my custom button AddNoteButton() to main view, it gave the following error, although it worked before I added this button. I tried to rewrite my views, but although it works at the beginning at some random point of time it throws this error again(by other words sometimes it works, but when i add some irrelevant code it stops working and discarding changes doesn't solve the problem). It always highlights line, where I use noteViewModels array inside of the NoteListView.
Also I added method which prints array to presenter and it always prints everything.
func printAll(){
    for element in self.noteViewModels{
        print(element.title)
    }
}

I can not add other files to question, because there is too many of them. But i hope that I gave enough information, If you think that there is not enough information you are free to ask me or you can check out github:
https://github.com/ShynggysSaparbek/ViperNotesWithRealm/
Xcode version 11.3
Mac OS version Catalina 10.15.2


text:
Q: change detection angular 2 model's property I need to call a JQuery function each time if my model's propery got changed.
person = {firstName:firstName, lastName:lastName}

as an example If I changed the firstName property of person object, every time I need to trigger a function. Actually I need a something like subscription to this object's property.
How is it possible?
thanks in advance.

A: It sounds like you are looking for the DoCheck (link to docs) life cycle hook. It is an event that will be triggered after every completed round of change detection. Keep in mind though that it will potentially be triggered a lot, and doing heavy operations in that hook could have a major negative impact on performance.
Here is an example that looks for changes on the person.firstName property, and logs it to the console if changes are found:
import { Component, DoCheck } from '@angular/core';

@Component({
  selector: 'app-root',
  template: `<input type="text" [(ngModel)]="person.firstName">`,
  styleUrls: ['./app.component.css']
})
export class AppComponent implements DoCheck {
  person = { firstName: 'Donald', lastName: 'Duck' };
  oldFirstName: string;

  ngDoCheck() {
    if (this.person.firstName !== this.oldFirstName) {
      console.log(`Change first name from "${this.oldFirstName}" to "${this.person.firstName}"`);
      this.oldFirstName = this.person.firstName;
    }
  }
}


text:
Q: Clip/Control scrolling of table view Sorry: My problem is little lengthy and may be complicated:
I have a UITableView with a row section header view and a cell. There is a background image (blurred) on the whole UITableView. The image is visible from section header as well. And I achieved that by making background color of section header and cell to be clearColor. There is some text on the cell. When I scroll the cell, the text on cell gets into the section header as well (because section view is clearColor).
What I want is that the cell text should not be seen when entering into header section (It is same as if section header has non-clear color with alpha 1) but if I do that I cannot see my original background image from the section header view which I want to see.
How can I achieve this effect?  Is there a way to apply some kind of transparent mask on section header view so that the image below is visible but the text from cell is not seen on it when scrolling?

A: I'm not completely clear on how your UITableView is set up, but you could try the masksToBounds property of CALayer. Make sure you add the QuartzCore framework then import the header:
#import "QuartzCore/QuartzCore.h"
Then setting the masksToBounds property would look something like this:
yourView.layer.masksToBounds = YES;


text:
Q: Is it possible to customize the color scheme of a Google Map? I'm using the Google Maps API and would like it to render a very simple image of countries/continents.
I also want to draw them in a suitable color that will work well with my site's color scheme.
Would I need to create my own tile-server? Or can I customize this somehow through the API?

A: No, when using the Google Maps API, you cannot change the maps themselves in any way. What you can customize, though, are the icons, logos, etc that you use.
EDIT: Google has since release the Styled Maps API, which will probably give you exactly what you want. Take a look at the wizard to get started quickly.

A: Google recently announced support for Styled Maps in the Google Maps API. You can extensively customize the color scheme used by Google Maps.

A: It is possible now with the Google maps V3 API. It comes as a custom map style.
Google made a style wizard:
https://mapstyle.withgoogle.com/

A: Google Maps API v3.
Working jsFiddle:
jsFiddle ---------------------------------------> http://jsfiddle.net/SQvej/
styles:[
    { featureType: "water", stylers: [ { hue: "#F4B741"} ] },
    { featureType: "road", stylers: [ { hue: "#ff0000" } ] }
]

Less words, more fiddles: http://24.media.tumblr.com/tumblr_m0i1emsdP31qaebp2o1_400.gif

A: I don't think you can customise this through the Google Maps API. However, the Google Chart API has a map chart type that has customisable colours.
You might also want to investigate OpenLayers, which is an open source web-based mapping engine.

A: I recently stumbled over this: http://cloudmade.com/products/style-editor
They have a complete color editor an lot's of API stuff.
I didn't found something about pricing. But you can have a look into the editior here: http://maps.cloudmade.com/editor/

A: I try this API and is so easy to install, and the skins are fine: http://codecanyon.net/item/colorful-google-maps-api/5432242?WT.ac=new_item&WT.seg_1=new_item&WT.z_author=MaGeekLab

A: Here is a collection of color schemes for Google Maps: link
Actually JSON properties for the API


text:
Q: Как сделать появление рекламы при каждом 5 касаний экрана смартфона Добрый день!
Я добавил рекламу во весь экран,всё работает только при первом касаний на конкретную UIView.
Как показать рекламу при каждом 5-ом касаний любой части экрана
-(void) viewDidLoad {
UITapGestureRecognizer * BanerAppear =[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(bannerApearAdMob)];
[self.selfBannerAdMob addGestureRecognizer:BanerAppear];
self.interstitial = [[GADInterstitial alloc] initWithAdUnitID:@"ca-app-pub-xxxxxxxxx/xxxxxx"];
request1 = [GADRequest request];
request1.testDevices = @[ kGADSimulatorID ];
[self.interstitial loadRequest:request1];
}

- (void)bannerApearAdMob{
    if (self.interstitial.isReady) {
        [self.interstitial presentFromRootViewController:self];
    }
}

A: Добавьте счетчик и по нему показывайте рекламу. Например так:
- (void)bannerApearAdMob{
    if (_counter >= 5) {
        if (self.interstitial.isReady) {
            _counter = 0;
            [self.interstitial presentFromRootViewController:self];
            //запрос загрузки новой рекламы, если не реализовано в методе делегата закрытия баннера/еще где.
        }
    } else {
        _counter += 1;
    }
}


text:
Q: How to use nodejs cluster to ensure more cores are used for processing I have a nodejs app that simply copies data from an SD card to a network location. I am running this on a raspberry pi 4 and depending how the workload is spread across the cpu cores the process can maximise the network connection and run at around 115MBps or it can be cpu bound and only run at around 65MBps.
In my tests I run 2 separate copy operations at the same time. These 2 copy operations run on separate nodejs cluster workers:
{"context":"CopyService (worker:2)","level":"info","message":"Copying /media/usb0 -> /mnt/videos/2022/May/2022_05_31/Cam1"}
{"context":"CopyService (worker:1)","level":"info","message":"Copying /media/usb1 -> /mnt/videos/2022/May/2022_05_31/Cam2"}

Despite them running on separate workers the 1st cpu core is often at 100% whilst the others are doing very little:

There are other examples where core 1 is at 100% and the others are all at 30% but I was unable to get a screenshot.
Based on the fact that I have 2 workers in play here I would expect 2 cores to be at 100% and the rest to be under very little load but I suspect that workers are not tied to cores.
How do I ensure that I can distribute the load from my nodejs programme to make sure that teh copy process does not become CPU bound?
My cluster is created as so:
if (cluster.isPrimary && !isNaN(clusterLimit) && clusterLimit > 1) {
    const nodeCount = Math.min(cpus().length, clusterLimit);
    logger.log(`Primary node  starting ${nodeCount} workers...`);

    for (let index = 0; index < nodeCount; index++) {
        cluster.fork();
    }

    return;
}

and I am creating 4 workers.


text:
Q: Child Element 100% size of Parents contents What i have:
A Block element with fixed size, but dynamic content size and overflow: scroll;.
What i want:
A transparent layer over the content, so no matter how far the parent is scrolled the layer covers the content.
What i tried:
.layer {
  position: relative;
  width: 100%;
  height: 100%;
  bottom: 100%;
  z-index: 20;
}

inside the parent after the content.
The issue:
The layer covers the parent properly, but as soon as i scroll it doesn't cover the content.
Fiddle:
http://jsfiddle.net/wYgWh/2/
Red should cover everything, but not too much;

A: Height: 100%; give the element the same height as it's parent.
The parent you have defined is not as high as the content you want to cover.
If you put the "layer" inside your "content" in your markup, you can then absolute position it relative to the "content". So now the height: 100% will relate to the content instead of the "parent" (scroll window).
Also, when you want to position something absolute, that element will relate to it's closest non-static parent.
Here is the fiddle.

A: Try this:
HTML:

   Content that gets covered!

CSS:
.coverable {
  position: relative;
}
.coverable .layer {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  bottom: 100%;
  z-index: 20;
}

A: to need to make
.layer {
position: fixed;
}


text:
Q: How to get a hash value by numeric index Have a hash:
h = {:a => "val1", :b => "val2", :c => "val3"}

I can refer to the hash value:
h[:a], h[:c]

but I would like to refer by numeric index:
h[0] => val1
h[2] => val3

Is it possible?

A: So you need both array indexing and hash indexing ?
If you need only the first one, use an array.
Otherwise, you can do the following :
h.values[0]
h.values[1]

A: h.values will give you an array requested.
> h.values
# ⇒ [
#  [0] "val1",
#  [1] "val2",
#  [2] "val3"
# ]

UPD while the answer with h[h.keys[0]] was marked as correct, I'm a little bit curious with benchmarks:
h = {:a => "val1", :b => "val2", :c => "val3"}
Benchmark.bm do |x|
  x.report { 1_000_000.times { h[h.keys[0]] = 'ghgh'} }
  x.report { 1_000_000.times { h.values[0] = 'ghgh'} }
end

#
#       user     system      total        real
#   0.920000   0.000000   0.920000 (  0.922456)
#   0.820000   0.000000   0.820000 (  0.824592)

Looks like we're spitting on 10% of productivity.

A: h = {:a => "val1", :b => "val2", :c => "val3"}
keys = h.keys

h[keys[0]] # "val1"
h[keys[2]] # "val3"


text:
Q: What is reputation supposed to be? A tool to gauge quality/improve the community, or a competition between rivals? Note that I am asking what it should be, not how it works, and not how people feel about it.  It's all too obvious how people feel about it.
What is the purpose of Stack Overflow reputation?
sounds like a duplicate, but it didn't get answered there.
I thought I read somewhere that it was to make it easier to find better questions and better answers.
Yet I see numerous complaints, even some whin(g)ing, about losing points or not getting them, with words like "penalized" or "punished."  (I'm not talking about the far fewer curious questions trying to understand an anonymous unexplained downvote.)
So which is it?  A tool to gauge quality/improve the community, or a competition between rivals?

A: imo it would depend on who you ask. Since we are all humans (least I assume we are) some would see it as a challenge to others a haha I have more points than you. I win, you loose!!! While others would see it as measurement of how much the community trusts you. I would view it as the latter one (although tbh I know another user on SO and would ask them the odd time how many points would they have and if I have more I'm happy but if not I would be a bit jealous, but I am ultimately here to (try) help the community and learn, not to compete with someone).


text:
Q: Sending an image through the body of a PUT request Title says it all. I need to send an image through the body of a PUT request. This is the code I currently have.
    static class Request
    {
        private readonly static HttpClient client = new HttpClient();
        public static async Task<UploadRequest> Upload(string uri, string path)
        {

            FileStream fileStream = File.Open(path, FileMode.Open, FileAccess.Read);
            StreamContent streamContent = new StreamContent(fileStream);
            MultipartContent content = new MultipartContent();
            content.Add(streamContent);

            Debug.WriteLine("Making a PUT request");
            var response = await client.PutAsync(uri, content);
            var result = await response.Content.ReadAsStringAsync();
            var deserializedResult = JsonConvert.DeserializeObject<UploadRequest>(result);

            fileStream.Close();
            Debug.WriteLine("Request made, returning result");

            return deserializedResult;
        }
}

Instead of using MultipartContent I instead passed in streamContent directly into client.PutAsync like so.
FileStream fileStream = File.Open(path, FileMode.Open, FileAccess.Read);
StreamContent streamContent = new StreamContent(fileStream);

Debug.WriteLine("Making a PUT request");
var response = await client.PutAsync(uri, streamContent);

However they both produce the same error on my api. Which is "message": "You did not upload an image.". I've checked the actual content of what I've passed in, in both cases when I passed in MultipartContent or streamContent into PutAsync.
The respective output (in order of which I've mentioned them) is System.Net.Http.MultipartContent and System.Net.Http.StreamContent so what exactly am I passing into the body?
Note
I previously asked the wrong question. This is the appropriate one.


text:
Q: AsyncTask without thread i am using AsyncTask for some part of my code but i have a jobSchedulerIntentService and i want to send data to server and receive some responses. i want to do same action without AsyncTask thread because my jobSchedulerIntentService have a thread. can i use AsyncTask without thread or i have to use another library ? witch library you can suppose me ? here is my code :
MyHttpClient.post("example.com/?", requestParams, new AsyncHttpResponseHandler() {
        @Override
        public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
            try {
                JSONObject jsonObject = new JSONObject(new String(responseBody));
                message = jsonObject.getString("user_id"        );
            } catch (JSONException e) {
                Log.i(TAG, "error");
            }
            switch (message){
                case "success_data":{
                    //do something
                    break;
                }
                case "failed_data":
                case "failed_timer":
                default:
                    Log.i(TAG, "error , try again");
            }
        }

        @Override
        public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) {
            Log.i(TAG, "error"+statusCode);
        }

        @Override
        public void onFinish() {
            super.onFinish();
        }
    });


text:
Q: Make CSS Drop Down Menu 2 Columns I currently have a CSS

 dropdown menu that uses the following code.  Unfortunately I want the sub menus to display in 2 columns as there are about 16 items in that submenu.  Does anyone know how to use the following code to make this drop down menu 2 columns?

.menu {
  border: none;
  border: 0px;
  margin: 0px;
  padding: 0px;
  font: 67.5% "Lucida Sans Unicode", "Bitstream Vera Sans", "Trebuchet Unicode MS", "Lucida Grande", Verdana, Helvetica, sans-serif;
  font-size: 18px;
  font-weight: bold;
}

.menu ul {
  background: #006633;
  height: 35px;
  list-style: none;
  margin: 0;
  padding: 0;
}

.menu li {
  float: left;
  padding: 0px;
}

.menu li a {
  background: #006633 url("../images/seperator.gif") bottom right no-repeat;
  color: #ffffff;
  display: block;
  font-weight: normal;
  line-height: 35px;
  margin: 0px;
  padding: 0px 25px;
  text-align: center;
  text-decoration: none;
}

.menu li a:hover,
.menu ul li:hover a {
  background: #003f20 url("../images/hover.gif") bottom center no-repeat;
  color: #FFFFFF;
  text-decoration: none;
}

.menu li ul {
  background: #006633;
  display: none;
  height: auto;
  padding: 0px;
  margin: 0px;
  border: 0px;
  position: absolute;
  width: 225px;
  z-index: 200;
  /*top:1em;
    /*left:0;*/
}

.menu li:hover ul {
  display: block;
}

.menu li li {
  background: url('../images/sub_sep.gif') bottom left no-repeat;
  display: block;
  float: none;
  margin: 0px;
  padding: 0px;
  width: 225px;
}

.menu li:hover li a {
  background: none;
}

.menu li ul a {
  display: block;
  height: 30px;
  font-size: 12px;
  font-style: normal;
  margin: 0px;
  padding: 0px 10px 0px 15px;
  text-align: left;
}

.menu li ul a:hover,
.menu li ul li:hover a {
  background: #003f20 url('../images/hover_sub.gif') center left no-repeat;
  border: 0px;
  color: #ffffff;
  text-decoration: none;
}

.menu p {
  clear: left;
}

Main Item 1

Main Item 2

Test Sub Item

Test Sub Item

Test Sub Item

Test Sub Item

Test Sub Item

Test Sub Item

Test Sub Item

Test Sub Item

Test Sub Item

Test Sub Item

Test Sub Item

Test Sub Item

Test Sub Item

Test Sub Item

Test Sub Item

Test Sub Item

Test Sub Item

Test Sub Item

Main Item 3

Main Item 4

Main Item 5

Main Item 6

Test Sub Item

Test Sub Item

Test Sub Item

A: 2018 edit
Hey, 7 years later the columns css property is well supported

ul{
  columns: 2;
}

first item

second item

third item

fourth item

fifth item

You could probably get a similar effect with the very robust grid

2011 original answer
Make the ul twice as wide as the li's and float the li's left
http://www.behemothdan.com/2011/05/faux-mega-menu-in-wordpress/

A: To make the listings display alpha down instead of across, wrap half of the
's in a div, and the other half in another div. Then float the divs left.

A: I have just wrote a short tute on that http://www.prowebdesign.ro/wordpress-sub-menu-items-split-in-2-columns-the-easy-way/. Basically, it expands the answer of Michael Jasper, but offers a tad more flexibility: you can have 2 columns for selected sub-menus only.


text:
Q: How to convert a CString to an array of strings in MFC C++? In MFC C++, I'm trying to read a text line by line, and show it in listcontrol.
The text file is of the format:
Name Address Rollno Class
So the text will contain
John England 25 4
and so on.
I want to display them in listcontrol.
I however, read the files using this code
if (myFile.Open(_T("c:\\Users\\blabla\\Desktop\\bla.txt"), CFile::modeRead))
    {
        while (myFile.ReadString(strLine))
        {
            strMsg += strLine + '\n';

            int lengtha = (strLine).GetLength();
            //SetDlgItemText(IDC_LIST3, strLine);

            char myString[256];

            AfxMessageBox(strLine, MB_ICONINFORMATION);

            //How do I iterate through strLine?

        }

    }

    else
    {
        AfxMessageBox(_T("Nope"));
    }

In the above, strLine would print "John England 25 4"
I want to convert this into an array like ["John", "England", "25", "4"] and then iterate through this array to insert into listcontrol.
I'm new to MFC C++, and I can't seem to understand how to do this at all. If anyone can help, that'd be great.
Edit: I saw that you can tokenize, so this is what I've come up so far
void CMFCTask2Try2Dlg::OnBnClickedButton1()
{
    // TODO: Add your control notification handler code here
    CStdioFile myFile;
    CString strLine;
    CString strMsg;

    if (myFile.Open(_T("c:\\Users\\blabla\\Desktop\\nana.txt"), CFile::modeRead))
    {
        while (myFile.ReadString(strLine))
        {
            strMsg += strLine + '\n'

            char myString[256];

            CAtlString str(strLine);
            CAtlString resToken;

            int curPos = 0;
            resToken = str.Tokenize(_T(" "), curPos);
            int i = 0;
            int nItem;
            while (resToken != _T(""))
            {
                _tprintf_s(_T("Resulting token: %s\n"), resToken);

                AfxMessageBox(resToken, MB_ICONINFORMATION);
                nItem = mcontrolz.InsertItem(i, resToken);

                resToken = str.Tokenize(_T(" "), curPos);
                break;
                //Here resToken prints
            }
        }
    }
    else
    {
        AfxMessageBox(_T("Nope"));
    }

    //myFile.Close();
}

so if my text file  has only
hey how are you

In this line of code
AfxMessageBox(resToken, MB_ICONINFORMATION);

The messagebox would give me only "hey"  works great so far but if my text file is
hey how are you
hi how are you

The resToken here AfxMessageBox(resToken, MB_ICONINFORMATION); at this line would be give two messagebox alerts, one being hey and one being hi no idea why it gives me that. Can someone help me to figure this out?

A: CString::Tokenize can be used to split a string at arbitrary delimiters. In your use case you would pass _T(" ") for the delimiter.


text:
Q: How do I read unicode and a number arguments from the command line in C for windows? I have this code:
#include "stdafx.h"
#include <windows.h>
#include <conio.h>

int _tmain(int argc, _TCHAR* argv[])
{
    LPCTSTR f = argv[1];
    DWORD n = atoi(argv[2]);
    return 0;
}

I want to read a unicode string and a number. This is what I get after I compile:

error C2664: 'atoi' : cannot convert parameter 1 from '_TCHAR *' to 'const char *'

A: Instead of using atoi you need use _ttoi. This is because atoi accepts only ASCII strings where as you are trying to pass a UTF-16 string to it. BTW, do not include conio.h it is not a standard header file.


text:
Q: Why does the sum of residuals equal 0 from a graphical perspective? I've seen the proof for why in least squares regression the sum of residuals is always equal to 0, and I kind of understand why from that algebraic perspective. Basically, you're finding the minimum of the least squares equation, so you take the partial derivative and set it equal to 0, right?
To make things more confusing, I've heard from some sources that the sum doesn't necessarily equal 0, but it's expected value is 0, so there's some variation. (That makes more sense to me, because you're dealing with random variables that naturally have random variation in the points.)
What I can't wrap my head around is that from a graphical perspective, if I imagine a set of points with a regression line through them, how can you guarantee that the sum of residuals ends up being 0? Can someone help me understand from a point of view that isn't necessarily the algebraic proof?

A: To fit $\hat y = b_1 + b_2 x$ by OLS we minimise the residual sum of squares, $RSS = \sum_{i=1}^n e_i^2$. As the question states, we can do this analytically by setting
$$\frac{\partial RSS}{\partial b_1}=0 , \qquad \frac{\partial RSS}{\partial b_2}=0 $$
and solving the resulting normal equations. Note that from the normal equations we can deduce $\sum_{i=1}^n e_i = 0$ and $\sum_{i=1}^n x_i e_i = 0$; the latter is equivalent (think about the inner or "dot" product) to stating that the vector of observations $\mathbf{x} = (x_1, x_2, \dots, x_n)^t$ in $\mathbb{R}^n$ is orthogonal (perpendicular) to the vector of residuals $\mathbf{e} = (e_1, e_2, \dots, e_n)^t$, and analogously your requirement that the sum of residuals is zero is equivalent to the statement that $\mathbf{e}$ is orthogonal to the vector of ones, $\mathbf{1}_n=(1,1,\dots,1)^t$.

Both these results can be seen geometrically from knowing the design matrix $\mathbf{X}$ includes a column of ones to represent the intercept term and another column for the $x_i$ data, and that the vector of residuals is orthogonal to each column of the design matrix because the hat matrix $\mathbf{H}$ is an orthogonal projection onto the column space of $\mathbf{X}$. For more on how to interpret the diagram, see Geometric interpretation of multiple correlation coefficient $R$ and coefficient of determination $R^2$. But that takes place in the $n$-dimensional subject space; it would be nice to develop some intuition from the scatter plot itself.

To illustrate OLS geometrically, draw a vertical line segment from each point $(x_i, y_i)$ to its fitted value on the regression line $(x_i, \hat y_i)$, then draw a square with this side. The length of this segment is the magnitude of the residual $|e_i$| (note $e_i$ is positive for points above the line, e.g. with the blue square, negative for points below, e.g. with the red square) and the area of the square is $e_i^2$. I have illustrated two examples points, and for convenience placed the squares on whichever side avoids overlapping the regression line. The RSS is the sum of the areas of all the squares (both red and blue squares counting as positive area), and to find the OLS solution we seek $b_1$ and $b_2$ that minimise this area.
Now take any regression line (not necessarily the OLS one) and consider translating its intercept up by $\delta b_1$. I have drawn the new regression line as dotted, and overlaid the residual squares based on both new and original fitted values.

For the point on the left with a positive residual, this shift in the regression line has reduced the area of the residual square — this is logical since the observed point lay above the line, and the regression line has moved up closer to it, so the fit is better. Two $\color{blue}{\text{blue}}$ rectangular strips (which I consider to extend the whole length of the larger, original $e_1$ by $e_1$ square) have been cut off the left and bottom sides. But these overlap (the grey square at bottom left) so subtracting both rectangles has double-counted the grey square, and we need to add this area back on once again. Overall the new (reduced) residual square is found from the original square, minus the two blue rectangular strips, plus the grey square.
For points below the line with a negative residual, raising the line has worsened the fit and made the residual more negative; the residual square has grown by two $\color{red}{\text{red}}$ rectangular strips (running across the sides of the smaller, original $e_2$ by $e_2$ square) plus the grey square in the upper right.

If we dissect the residual squares for all data points in this way, then total the results,
$$\color{Gold}{\text{New RSS}} = \text{Old RSS} + \sum \color{red}{\text{red rectangles}} - \sum \color{blue}{\text{blue rectangles}} + \sum \color{grey}{\text{grey squares}}$$
From the diagram it's clear $\delta e_i = - \delta b_1$ for all points — raising the intercept increases each fitted $\hat y_i$ by $\delta b_1$ so $e_i = y_i - \hat y_i$ falls by $\delta b_1$. Each $\color{grey}{\text{grey}}$square has area $(\delta b_1)^2$. Each horizontally-aligned rectangles is as tall as the intercept was shifted, and as wide as the original residual for that point. The corresponding vertically-aligned rectangles are congruent, just rotated by a right angle. So I can line up all the $\color{blue}{\text{blue}}$ rectangles to form a single rectangle as high as the change in intercept and twice as wide as the sum of the positive residuals. The $\color{red}{\text{red}}$ rectangles form a single rectangle just as high, and twice the width of the sum of the (absolute values of the) negative residuals.
Now suppose the original $\hat y = b_1 + b_2 x$ satisfied $\sum_{i=1}^n e_i=0$, which occurs (prove it!) if the line passes through the centroid $(\bar x, \bar y)$. Since the positive and negative residuals cancel out, the blue and red rectangles must too:
$$\color{Gold}{\text{RSS after change in intercept}} = \text{RSS of line through centroid} + \color{grey}{n(\delta b_1)^2}$$
Whatever the gradient of our original line, adjusting the intercept so it avoids the centroid will make the RSS worse, by the area of the grey squares. The least-squares line must therefore pass through the centroid and have  $\sum_{i=1}^n e_i=0$.
This does not tell us anything about which gradient minimises the RSS, but we can adapt our approach to consider a fixed intercept $b_1$ and a change in slope of $\delta b_2$. This time, the fitted values $\hat y_i$ rise by $x_i \delta b_2$, so fitted values rise (and residuals fall) by more the further $x_i$ lies to the right: the rectangles do not all have the same height, nor the grey squares the same area. But otherwise the dissection is much as before.

We find the area of a $\color{grey}{\text{grey}}$ square is $(x_i \delta b_2)^2$ and the area of a rectangle is proportional (by $\pm \delta b_2$) to $x_i e_i$. For the same reasons as before we want the $\color{blue}{\text{blue}}$ and $\color{red}{\text{red}}$ rectangles to balance out, which would require the positive and negative values of $x_i e_i$ to cancel, i.e. $\sum_{i=1}^n x_i e_i =0$. Totalling,
$$\color{Gold}{\text{RSS after change in slope}} = \text{RSS of line for which }\sum_{i=1}^n x_i e_i \text{ is zero} + \color{grey}{(\delta b_2)^2\sum_{i=1}^n x_i^2}$$
Regardless of the intercept, if we draw a line with a slope such that $\sum_{i=1}^n x_i e_i = 0$, then any changes to the slope will result in an RSS which is worse (higher) by the area of the grey squares. The least-squares line
must therefore satisfy $\sum_{i=1}^n x_i e_i = 0$.

The diagrams oversimplify things: I didn't consider cases like a point with positive residual that develops a negative residual after the line sweeps above it, or where $x_i$ was negative. But we can verify the intuition algebraically:
$$\sum_{i=1}^n (e_i+\delta e_i)^2 = \sum_{i=1}^n e_i^2 + 2 \sum_{i=1}^n e_i \delta e_i + \sum_{i=1}^n (\delta e_i)^2 \tag{1}$$
The middle term represents the rectangular areas; note that the red and blue rectangles will take opposite signs since $e_i$ was positive for the blue case and negative for the red. Writing RSS as a function of $b_1$ and $b_2$,
$$RSS(b_1, b_2) = \sum_{i=1}^n e_i^2 = \sum_{i=1}^n (y_i - b_1 - b_2 x_i)^2 \tag{2}$$
Translating the regression line from $\hat y = b_1 + b_2 x$ to $\hat y = (b_1 + \delta b_1) + b_2 x$ reduces the residuals by the change in the intercept, $\delta e_i = -b_1$, so $(1)$ yields
$$
\begin{align}
RSS(b_1 + \delta b_1, b_2) &= RSS(b_1, b_2) + 2 \sum_{i=1}^n e_i (-\delta b_1) + \sum_{i=1}^n (-\delta b_1)^2 \\
RSS(b_1 + \delta b_1, b_2) &= RSS(b_1, b_2) - 2 \delta b_1 \sum_{i=1}^n e_i + n(\delta b_1)^2 \tag{3}
\end{align}
$$
Switching from $\hat y = b_1 + b_2 x$ to $\hat y = b_1 + (b_2 + \delta b_2) x$ gives $\delta e_i = -x_i \delta b_2$, and $(1)$ yields
$$
\begin{align}
RSS(b_1, b_2 + \delta b_2) &= RSS(b_1, b_2) + 2 \sum_{i=1}^n e_i (-x_i \delta b_2) + \sum_{i=1}^n (-x_i \delta b_2)^2 \\
RSS(b_1, b_2 + \delta b_2) &= RSS(b_1, b_2) - 2 \delta b_2 \sum_{i=1}^n x_i e_i + (\delta b_2)^2 \sum_{i=1}^n x_i^2 \tag{4}
\end{align}
$$
The argument can then proceed as before. Note that $(2)$ shows RSS is a quadratic function of both slope and intercept, so the expansions $(3)$ and $(4)$ could alternatively be derived by using the Taylor expansion
$$f(a+h) = f(a) + f'(a) h + \frac{1}{2} f''(a) h^2$$
with the partial derivatives
$$\frac{\partial RSS}{\partial b_1}= -2 \sum_{i=1}^n e_i, \quad \frac{\partial^2 RSS}{\partial b_1^2}=2n, \quad \frac{\partial RSS}{\partial b_2}=-2\sum_{i=1}^n x_i e_i, \quad \frac{\partial^2 RSS}{\partial b_2^2}= 2\sum_{i=1}^n x_i^2 $$
The $h$ represents our change $\delta b_1$ or $\delta b_2$. Note that setting the coefficient of the linear term in the change to zero (which we did by getting the red and blue rectangles to cancel out) is equivalent to putting $f'(a)=0$, i.e. ensuring the point we are expanding about satisfies the first order conditions to be a turning point. Checking that the coefficient of the quadratic term in the change is positive is equivalent to verifying $f''(a)>0$, which is the second order condition for this turning point to be a minimum: this is equivalent to our argument that, because the grey squares were being added on, the RSS was lower before the change.

Note that we were considering the residuals, $e_i = y_i - \hat y_i$, and not the errors, $\varepsilon_i = y_i - (\beta_1 + \beta_2 x_i)$ (where the betas are the "true" population regression parameters). Both residuals and errors are stochastic, in that if we re-sampled we would get a whole new bunch of random errors, a new OLS regression estimate, and a whole new set of residuals (we'd be fitting a different line to different points). The total of the residuals (as measured from the new OLS line) would still be zero. There's no restriction on the sum of the error terms, though. How could there be, remembering that the errors are generally assumed to be independent (or at least uncorrelated)? However, since the expected value of each error term is zero, the expected value of their sum is zero.
The arguments above should indicate that the sum of residuals would no longer be guaranteed to be zero if the intercept is removed from the model. Nor need the residuals sum to zero if the line was fitted by a method other than OLS. A vivid example of that is provided by Least Absolute Deviations: when moving an outlier up and down, you'll find (try it) that the LAD regression line remains "latched" to other points, and won't budge to take account of this change. The fact you can vary one residual while the others stays constant illustrates very dramatically that the sum of residuals is not invariant.

A: One geometrical answer that might or might not resonate with you is that

two legs of any right triangle are perpendicular.

It applies here because the "constant" or "intercept" in the regression results in projecting the response $y$ onto the vector $\hat{y}=\bar{y}(1,1,\ldots,1)$, which is one leg, and the residuals are the other leg $y-\hat{y} = (e_1, e_2, \ldots, e_n)$.

This picture shows a response $y$ regressed against $x_1 = (1,1,\ldots,1)$. The coefficient is $\alpha = \bar{y}$ and the residual is $y_{\cdot 1}$.  It is geometrically obvious that $y_{\cdot 1}$ and $x$ are perpendicular.
Their perpendicularity, expressed in terms of the dot product, says the sum of the residuals is zero, because
$$\eqalign{
0 &= y_{\cdot 1} \cdot x_1 = (e_1, e_2, \ldots, e_n)\cdot (1, 1, \ldots, 1) = e_1(1) + e_2(1) + \cdots + e_n(1) \\ &= e_1+e_2+\cdots+e_n.}$$
Notice

*

*This is exact, not an expectation.  After all, it's just geometry!  We did not need to make any probabilistic assumptions about $y$.

*The result requires that the regression include a constant.

*The result is true for all multiple regressions that span a constant, because they can be carried out by first regressing $y$ against the constant and then performing a multiple regression of its residuals.

The image is taken from a longer document I have posted on how to control for variables.  It elaborates on point (3).

A: You must keep in mind the difference between the true values of the parameters and your estimates of them. Graphically, you can think of the situation as the true line and the estimated line.
The usual way of returning the estimated line from the data just happens to correspond to the sum of residuals being zero. The residuals are deviations from the estimated line and the errors are deviations from the true line, the sum of errors doesn't necessarily equal zero but that is its expected value.
So if you knew what the true line and you generated observations from that you would see that the expected value of the distribution of sum of errors would be zero.
I.e. you would see the sum of errors distributed around zero if you ran multiple simulations.
All of linear regression theory is predicated on the true line existing.


text:
Q: How much memory (heap size) is required to be set in JMeter Let's take a very simple jmeter script which downloads a file of 128MB in an HTTP request (GET). Purpose is to stress out the server under test so there is no necessity for file to be stored locally or in memory of the jvm for future use. The file should be completely downloaded as it maintains a connection with the sever.
Scenario:
10 threads or more running concurrently with a pacing of say 5 seconds. Assume unlimited network bandwidth.
File location: https://storage.googleapis.com/videos12/dummy.txt
Question is - how much memory would you set for the heap size of the jmeter's jvm so that you do not get java OOM error? What would be the approach to do a basic calculation?
set HEAP=-Xms512m -Xmx512m --> this can be set in jmeter.bat file.

A: *

*Quick answer: 512 Mb is too low for 10 threads downloading a 128Mb file. Increase the heap to 80% of your total physical available RAM.

*Longer answer: read the material about Java Performance Tuning, Profiling, and Memory Management, quit your tester job and become JVM expert.

*Good answer: don't ask or guess it, measure it. Using i.e. JVisualVM:

*

*Run your test with 1 virtual user. Measure heap used

*Run your test with 2 virtual users. Measure heap used.

*Run your test with 4 virtual users. Measure heap used.

*Do complex arithmetic calculations

*Set JMeter heap accordingly to results

*Correct answer: Given you don't care in the slightest about the response don't use HTTP Request sampler and go for JSR223 Sampler instead. Example code:
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;

HttpClient client = HttpClientBuilder.create().build();
HttpGet get = new HttpGet("https://storage.googleapis.com/videos12/dummy.txt");
HttpResponse response = client.execute(get);
SampleResult.setResponseCode(String.valueOf(response.getStatusLine().getStatusCode()));
SampleResult.setResponseMessage(response.getStatusLine().getReasonPhrase());
HttpEntity entity = response.getEntity();
SampleResult.setBodySize(Math.round(entity.getContentLength()));
EntityUtils.consume(entity);

Very important bits:

*

*Make sure you select groovy in the "language: dropdown

*Make sure you tick Cache compiled script if available box

*Make sure you don't forget the EntityUtils.consume(entity); line - it does all the magic

For better understanding of the "correct answer" see HttpClient Tutorial for Apache HTTP Components API explained and Beanshell vs JSR223 vs Java JMeter Scripting: The Performance-Off You've Been Waiting For! article for scripting best practices.

A: The new Apache JMeter 3.1 addresses this problem and handles the big responses well.
http://jmeter.apache.org/changes.html#Improvements

Bug 53039 - HTTP Request : Be able to handle responses which size
exceeds 2147483647 bytes (that is 2GB)
JMeter is now able to handle in terms of metrics responses bigger than
2GB, limit has been increased to 9223372 TB. To handle such big
responses, it can also now truncate part of the response to avoid
overflooding memory. See httpsampler.max_bytes_to_store_per_request
property.


text:
Q: How do I sync my swift --version to my xcrun swift --version? The version of swift Xcode is using is different from the one I have when I run swift --version. Its because I tried to download Swift 4 from swift.org. I want to sync both of them. I can use swiftenv to update the global version but I prefer to use a Apple supported versioning system.
xcrun swift -version
Apple Swift version 4.0.3 (swiftlang-900.0.74.1 clang-900.0.39.2)
Target: x86_64-apple-macosx10.9

swift --version
Apple Swift version 4.0 (swift-4.0-RELEASE)

A: Try reinstalling the command line tool by :
xcode-select --install
this should overwrite the current swift version to the default apple one.

A: You can use the swiftenv tool to manage all the swift versions on your machine. Use the tool to list all the swift versions, and set the global version which you want.
Good Luck.


text:
Q: Unable to follow Feynman Lectures reading on opacity Feynman is explaining the phenomenon of opacity in terms of classical electrodynamics.

Let us first ask: "What is an opaque screen?" Suppose we have a completely opaque screen between a source S and an observer at P, as in Fig. 31–6(a). If the screen is "opaque" there is no field at P. Why is there no field there? According to the basic principles we should obtain the field at P as the field Es of the source delayed, plus the field from all the other charges around. But, as we have seen above, the charges in the screen will be set in motion by the field Es, and these motions generate a new field which, if the screen is opaque, must exactly cancel the field Es on the back side of the screen. You say: "What a miracle that it balances exactly! Suppose it was not exactly right!" If it were not exactly right (remember that this opaque screen has some thickness), the field toward the rear part of the screen would not be exactly zero. So, not being zero, it would set into motion some other charges in the material of the screen, and thus make a little more field, trying to get the total balanced out. So if we make the screen thick enough, there is no residual field, because there is enough opportunity to finally get the thing quieted down.

Here is the source (with diagram, which I can't embed here for some reason).
I want to understand this entirely from the perspective of electromagnetic fields and charges (for example, the concept of "photon" hasn't yet been introduced).
I lose Feynman at "trying to get the total balanced out." Why is it necessarily the case that additional electrons moving will cause the field to be canceled out on the far side of the screen? For example, I could imagine a case where the resonance induced by the wave amplifies the existing wave and it comes out the other side at double strength.
What am I missing?

A: A really thin piece of the material reducing the field is what it means for the material to be opaque.
To see why it at the very least does not amplify the wave, we can look to conservation of energy. To get the charge moving, the field offloads some energy into the charge, and in turn the moving charge produces EM waves. However, the charge can't produce more EM energy than what was offloaded, so in the worst case, the EM field will simply pick back up the energy it lost. For an opaque material, it just happens that this goes in the other direction, where energy is lost to the material (or perhaps reflected).


text:
Q: How to select Document Mode in Firefox and Chrome without setting a DOCTYPE? I am working on converting a web page that was creating using old web standards to support modern web browsers. The web page currently renders in Quirks Mode within Internet Explorer 9, Firefox, and Chrome.
In IE9, I am able to select the "Document Mode" in which I would like the web page I am viewing to render in. This makes things easier, as I can jump between Quirks Mode and IE9 Standards Mode. I do not have to add/modify the DOCTYPE tag within the code of the web page.
Can I do the same in Firefox and Chrome?

A: No. In most browser–except IE–there are three different modes:
Quirks mode
This is where browsers wilfully do not follow certain standards in order to be compatible with broken content. IE < 10 is frozen in IE5.5 era quirks mode. Other browser's quirks mode, including IE10 have evolved to be interoperable with each other, so they break in more predictable ways.
The usual method of setting quirks mode is not not include a doctype, or include content before the doctype.
It is highly recommended not to rely on quirks mode rendering.
Almost standards mode
This renders like standards mode, except the behaviour of vertical sizing of table cells.
Triggered with a doctype of:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

Standards mode
This is the mode developers should be using, with browsers behaving to the defined standards. Triggered by using a valid doctype such as <!DOCTYPE html>
There is no way to set any other modes in Non-IE browsers. You can find out more at http://hsivonen.iki.fi/doctype/
I'd advise just to try to update the site to standards mode if you can, as it will only cause more issues the longer it is left in legacy rendering modes. It will also not take advantage of enhancements in modern versions of IE, such as performance improvements.


text:
Q: Chrome Browser run twice during specifying the file to be downloaded using Selenium Webdriver c# Nunit I am running my test case on 2 different browser "Chrome" and "Firefox".I am trying specified the path of my file to be downloaded during the [test] is running for "Chrome". All the code work as expected, I am able to save my file in the specified path. My "Firefox" is working fine but not for "Chrome". It just that every time when I run my script,it will open 2 "Chrome" browser , ( (1st) just open and do nothing ) , (2nd)(run the script as expected)). So on every test case i run , it will run all the test case on the 2nd "Chrome" browser.Furthermore, I couldnt use the [TearDown] method to close the browser, because it run on the 2nd "Chrome" browser , instead of the 1st "Chrome
 [TestFixture(typeof(ChromeDriver))]
[TestFixture(typeof(FirefoxDriver))]

public class Program<TWebDriver> where TWebDriver : IWebDriver, new()

{
    IWebDriver driver;
    IWebElement element;

    [SetUp]
    public void StartBrowser1()
    {

        driver = new TWebDriver();

        ICapabilities caps = ((RemoteWebDriver)driver).Capabilities;
        string browserName = string.Empty;
        if (caps.HasCapability("browserName"))
        {
            browserName = caps.GetCapability("browserName").ToString();

            if (browserName.Equals("chrome"))
            {
                String myDownloadFolder = @"c:\temp\GoogleChrome\";
                var options = new ChromeOptions();
                options.AddUserProfilePreference("download.default_directory", myDownloadFolder);
                driver.Manage().Window.Maximize();
                driver = new ChromeDriver(options);
            }

            }
            // For firefox
            else if (browserName.Equals("firefox"))
            {
                String myDownloadFolder = @"c:\temp\MozillaFirefox\";
                FirefoxProfile fp = new FirefoxProfile();
                fp.SetPreference("browser.download.folderList", 2);
                fp.SetPreference("browser.download.dir", myDownloadFolder);
                fp.SetPreference("browser.helperApps.neverAsk.saveToDisk", "application/pdf");
                // disable Firefox's built-in PDF viewer
                fp.SetPreference("pdfjs.disabled", true);}

                Base.Login(driver);  //  base class , the code for the base class

                /* public static void Login(IWebDriver driver)
                 {
                driver.Manage().Window.Maximize();
                driver.Manage().Timeouts().ImplicitWait = TimeSpan.FromSeconds(5);
                driver.Navigate().GoToUrl("http://192.163.0.1/admin/Login/Login.aspx");
                driver.FindElement(By.Id("ctl00_MainContent_ucLogin_txtUserID")).SendKeys("abc");
                driver.FindElement(By.Id("ctl00_MainContent_ucLogin_txtPassword")).SendKeys("123456");
                driver.FindElement(By.Id("ctl00_MainContent_ucLogin_cmdLogin")).Click();
                }
                */
            }

[TearDown]
    public void CloseBrowser()
    {
        Base.Logout(driver);
    }


text:
Q: SQL query slow calculating cumulative totals We are storing data readings at 5 minute intervals for a large number of gauges.
The data tables involved are:
Table1 - GaugeData
Columns -
    GaugeID (int, primary key)
    Timestamp (datetime, primary key)
    Value (decimal)

Table2 - GaugeSummaryData
Columns -
    GaugeID (int, primary key)
    DayTimestamp (date, primary key)
    DayTotal (decimal) - total for the current date/day
    CumulativeTotal (decimal) - total up to and including the current date

Without changing the table structure in any way, what would be the most efficient way to copy and aggregate data from GaugeData into GaugeSummaryData?
I have attempted this two ways already. Using a cursor takes 40 minutes to copy all data from GaugeData to GaugeSummaryData. Using insert/update statements took 2hrs+.
Could somebody please suggest the most efficient way? Pseudocode or SQL appreciated.

A: 5GB is not that much data. I would say that your tables could use some new indexes.  Once those are in place, insert triggers should do the job very nicely.
CREATE TRIGGER trig_INS_GaugeData ON GaugeData FOR INSERT AFTER
AS
BEGIN
    -- create new GaugeSummaryData rows for dates that are not in table yet
    INSERT GaugeSummaryData (GaugeID, DayTimestamp, DayTotal, CumulativeTotal)
    SELECT I.GaugeID, CONVERT(date, I.TimeStamp), 0, SUM(GT.DayTotal)
    FROM INSERTED AS I
    INNER JOIN GaugeSummaryData GT ON I.GaugeID = GT.GaugeID AND convert(date, I.TimeStamp) < GT.DayTimestamp
    GROUP BY I.GaugeID, convert(date, I.TimeStamp)
    -- update GaugeSummaryData rows with totals
    UPDATE GSD
    SET DayTotal = DayTotal+I.Value, CumulativeTotal = CumulativeTotal + I.Value
    From INSERTED AS I
    INNER JOIN GaugeSummaryData GT ON I.GaugeID = GT.GaugeID
          and convert(date, I.TimeStamp) = GT.DayTimestamp
END

A: Is it necessary to update the GaugeSummaryData at the end of each day only once? If its not, then probably applying an after insert trigger on Gauge Data should make the whole process real time and less time consuming. As soon as an entry is made in Gauge Data, the trigger will update the corresponding entry in GaugeSummaryData. If its the first entry for the day, then trigger should reset the Day Total to 0 before updating.


text:
Q: TeXnicCenter quick build I use TeXnicCenter to build my LaTeX documents under Windows 7.
I usually have 3-4 tabs open in TeXnicCenter corresponding to the different sections of my document.
To build my document I have to go to the first tab (the index of my file), build, and then go back to the old tab where I was editing (one of the sections).
Is there a smarter way of doing this?
I would like a hotkey that just move to the first tab and compile.
F5 only compiles the current tab, it is not aware if it is the index or not.

A: You can also convert a regular TeX input file to a project as follows.
Step 1
Let trash.tex be your regular TeX input file. Open it as shown in the following figure.

Step 2
Choose Project and click Create with active file as main file as follows.

Step 3
Click OK and done!

Now you can TeXify the project with one-click.

A: You can create a project rather than just working with regular files. Each project has a "main file", so that when you "build the project", it builds the main file, which may be different from the actively selected window/tab.
Start a new project (menu option File > New Project) and specify the main file or change the main file for an existing project (menu option Project > Properties):

Now use the "Build and View Output" Ctrl+F5 rather than the usual "Build and View Current File" Ctrl+Shift+F5.


text:
Q: Get Model and id of the Model you are adding a note to Basically,
I have a notes table with a polymorphic relationship with videos and users and want to determine how on my store method in my NotesController I get which model I am added a note to, and the id in that table. This is my create query on my store method
       $note = Note::query()->create([
            'body' => $request->get('body'),
            'user_id' => \Auth::id(),
            'noteable_id' => 1, **(needs to be dynamic)**
            'noteable_type' => Video::class, **(needs to be dynamic)**
        ]);

Blade
                    <form action="{{route('admin.note.store'}}" method="post">
                        {{csrf_field()}}

                            <input id="btn-input" name="body" required="true" type="text" class="form-control input-sm" placeholder="Type your message here...">

                                <button type="submit" class="btn btn-warning btn-sm" id="btn-chat">
                                    Submit
                                </button>

                    </form>

Essentially I want to know how I can retrieve the noteable_type = (Model I'm updating) and the noteable_id (id of the record I'm adding a note to)
Is there any way of retrieving this dynamically on the request?
Thanks

A: You need to get the video or any other model some way. If your route contains the video id then you can use that in your controller. Here are some ways you can do this.
//Get your video model
$video = Video::find(...);

$note = \Auth::user()->create([
    'body' => $request->get('body'),
    'noteable_id' => $video->id,
    'noteable_type' => get_class($video),
]);

// OR

$note = new Note([
    'body' => $request->get('body'),
    'user_id' => \Auth::id(),
]);

$video->note()->save($note);

Run php artisan route:list and post it so that i can advise you on how to fetch the model.


text:
Q: How to build-run vNext application from Windows Powershell? I'm trying to build a console application in .NET vNext from Windows PowerShell. So far I have upgraded the package by

kvm upgrade

from which I got package version "KRE-svr50-x86.1.0.0-alpha3-10070" and also checked the "alias" to conform the version.
Now, I wrote a console app contains following lines:
using System;

public class Program
{
    public static void Main()
    {
        Console.WriteLine("Why Soo serious!!!! ");
    }
}

and bellow the project.json
{
  "dependencies": {
    "System.Console": "4.0.0.0"
  },
  "configurations": {
    "net45": {},
    "k10": {}
  }
}

And now, whenever I try to run this from Windows Poweshell it lists out missing dll (specifically namespace System) bellow the build output:
(both json and cs files in a same folder so no error related to json)

kpm build

(1,12): error CS0246: The type or namespace name 'System' could not found (are you missing a using directive or an assembly reference?)
How to refer the library.
Please help me to find where(what) I'm missing and how to fix it...

A: If you're still having this issue, and I was under 10.10, try changing your project.json file to this:
"dependencies": {
  "System.Console": "4.0.0-beta-22210"
},

(mind you, that will have to be updated as System.Console is changed, but at least you'll be able to compile today).

A: Your problem is related to nuget configuration.
To see the way it works go to your project.json folder and do a "kpm restore". you will see:

Unable to locate System.Console >= 4.0.0.0

This happends because the kpm uses a different nugget repository namely: https://www.myget.org/F/aspnetvnext/
That repository has no nuget package for System.Console
To solve this you need a NuGet.Config file just outside your project.json folder in which you will specify the standard nuget repository (to get the System.Console package) and the asp.net vnext repository so you can get the asp.net vnext specific repositories.
That file should look something like this:
<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <packageSources>
    <add key="AspNetVNext" value="https://www.myget.org/F/aspnetvnext/" />
    <add key="NuGet.org" value="https://nuget.org/api/v2/" />
  </packageSources>
  <packageSourceCredentials>
    <AspNetVNext>
      <add key="Username" value="aspnetreadonly" />
      <add key="ClearTextPassword" value="4d8a2d9c-7b80-4162-9978-47e918c9658c" />
    </AspNetVNext>
  </packageSourceCredentials>
</configuration>

Also look out for your folder structure:
/ - root folder
- NuGet.config
- your project folder
-- project.json
-- source code files

After you have created the folder structure as exemplified and put the NuGet.config in the right place you do a "kpm restore" and you will see that System.Console is resolved and then issuing "kpm build" all is building correctly


text:
Q: Why is Ruby more suitable for Rails than Python? Python and Ruby are usually considered to be close cousins (though with quite different historical baggage) with similar expressiveness and power. But some have argued that the immense success of the Rails framework really has a great deal to do with the language it is built on: Ruby itself. So why would Ruby be more suitable for such a framework than Python?

A: Because Rails is developed to take advantage of Rubys feature set.
A similarly gormless question would be "Why is Python more suitable for Django than Ruby is?".

A: Those who have argued that

the immense success of the Rails
  framework really has a great deal to
  do with the language it is built on

are (IMO) mistaken. That success probably owes more to clever and sustained marketing than to any technical prowess. Django arguably does a better job in many areas (e.g. the built-in kick-ass admin) without the need for any features of Ruby. I'm not dissing Ruby at all, just standing up for Python!

A: The python community believes that doing things the most simple and straight forward way possible is the highest form of elegance. The ruby community believes doing things in clever ways that allow for cool code is the highest form of elegance.
Rails is all about if you follow certain conventions, loads of other things magically happen for you. That jives really well with the ruby way of looking at the world, but doesn't really follow the python way.

A: I suppose we should not discuss the language features per se but rather the accents the respective communities make on the language features. For example, in Python, re-opening a class is perfectly possible but it is not common; in Ruby, however, re-opening a class is something of the daily practice. this allows for a quick and straightforward customization of the framework to the current requirement and renders Ruby more favorable for Rails-like frameworks than any other dynamic language.
Hence my answer: common use of re-opening classes.

A: Personally, I find ruby to be superior to python in many ways that comprise what I'd call 'consistent expressiveness'. For example, in ruby, join is a method on the array object which outputs a string, so you get something like this:
numlist = [1,2,3,4]
#=> [1, 2, 3, 4]
numlist.join(',')
#=> "1,2,3,4"

In python, join is a method on the string object but which throws an error if you pass it something other than a string as the thing to join, so the same construct is something like:
numlist = [1,2,3,4]
numlist
#=> [1, 2, 3, 4]
",".join([str(i) for i in numlist])
#=> '1,2,3,4'

There are a lot of these little kinds of differences that add up over time.
Also, I cannot think of a better way to introduce invisible logic errors than to make whitespace significant.

A: Is this debate a new "vim versus emacs" debate?
I am a Python/Django programmer and thus far I've never found a problem in that language/framework that would lead me to switch to Ruby/Rails.
I can imagine that it would be the same if I were experienced with Ruby/Rails.
Both have similar philosophy and do the job in a fast and elegant way. The better choice is what you already know.

A: There are probably two major differences:
Ruby has elegant, anonymous closures.
Rails uses them to good effect. Here's an example:
class WeblogController < ActionController::Base
  def index
    @posts = Post.find :all
    respond_to do |format|
      format.html
      format.xml { render :xml => @posts.to_xml }
      format.rss { render :action => "feed.rxml" }
    end
  end
end

Anonymous closures/lambdas make it easier to emulate new language features that would take blocks. In Python, closures exist, but they must be named in order to be used. So instead of being able to use closures to emulate new language features, you're forced to be explicit about the fact that you're using a closure.
Ruby has cleaner, easier to use metaprogramming.
This is used extensively in Rails, primarily because of how easy it is to use. To be specific, in Ruby, you can execute arbitrary code in the context of the class. The following snippets are equivalent:
class Foo
  def self.make_hello_method
    class_eval do
      def hello
        puts "HELLO"
      end
    end
  end
end

class Bar < Foo # snippet 1
  make_hello_method
end

class Bar < Foo; end # snippet 2
Bar.make_hello_method

In both cases, you can then do:
Bar.new.hello

which will print "HELLO". The class_eval method also takes a String, so it's possible to create methods on the fly, as a class is being created, that have differing semantics based on the parameters that are passed in.
It is, in fact, possible to do this sort of metaprogramming in Python (and other languages, too), but Ruby has a leg up because metaprogramming isn't a special style of programming. It flows from the fact that in Ruby, everything is an object and all lines of code are directly executed. As a result, Classes are themselves objects, class bodies have a self pointing at the Class, and you can call methods on the class as you are creating one.
This is to large degree responsible for the degree of declarativeness possible in Rails, and the ease by which we are able to implement new declarative features that look like keywords or new block language features.

A: The real answer is neither Python or Ruby are better/worse candidates for a web framework. If you want objectivity you need to write some code in both and see which fits your personal preference best, including community.
Most people who argue for one or other have either never used the other language seriously or are 'voting' for their personal preference.
I would guess most people settle on which ever they come in to contact with first because it teaches them something new (MVC, testing, generators etc.) or does something better (plugins, templating etc). I used to develop with PHP and came in to contact with RubyOnRails. If I had have known about MVC before finding Rails I would more than likely never left PHP behind. But once I started using Ruby I enjoyed the syntax, features etc.
If I had have found Python and one of its MVC frameworks first I would more than likely be praising that language instead!

A: Python has a whole host of Rails-like frameworks. There are so many that a joke goes that during the typical talk at PyCon at least one web framework will see the light.
The argument that Rubys meta programming would make it better suited is IMO incorrect. You don't need metaprogramming for frameworks like this.
So I think we can conclude that Ruby are not better (and likely neither worse) than Python in this respect.

A: Some have said that the type of metaprogramming required to make ActiveRecord (a key component of rails) possible is easier and more natural to do in ruby than in python - I do not know python yet;), so i cannot personally confirm this statement.
I have used rails briefly, and its use of catchalls/interceptors and dynamic evaluation/code injection does allow you to operate at a much higher level of abstraction than some of the other frameworks (before its time).  I have little to no experience with Python's framework - but i've heard it's equally capable - and that the python community does a great job supporting and fostering pythonic endeavors.

A: I think that the syntax is cleaner and Ruby, for me at least, is just a lot more "enjoyable"- as subjective as that is!

A: All of this is TOTALLY "IMHO"
In Ruby there is ONE web-application framework, so it is the only framework that is advertised for that language.
Python has had several since inception, just to name a few: Zope, Twisted, Django, TurboGears (it itself a mix of other framework components), Pylons (a kinda-clone of the Rails framework), and so on. None of them are python-community-wide supported as "THE one to use" so all the "groundswell" is spread over several projects.
Rails has the community size solely, or at least in the vast majority, because of Rails.
Both Python and Ruby are perfectly capable of doing the job as a web applications framework. Use the one YOU (and your potential development team) like and can align on.

A: Two answers :
a. Because rails was written for ruby.
b. For the same reason C more suitable for Linux than Ruby


text:
Q: Driving parallel arrays of LEDs from a single constant current supply I'm looking at using a single constant current, DC-DC boost converter to power several (6 - 8) parallel strings of 3 LEDs, like the drawing below. This is powered by a single li-ion battery.

To control each string of LEDs, I'm proposing using a MOSFET like in the diagram below.

Each MOSFET would be driven by a separate microcontroller pin either high or low.
As I understand it, provided the set current is high enough to drive all of the strings simultaneously this will work but might have some side effects:

*

*When disabling any string, the current will be shared by the remaining enabled strings, i.e. the remaining strings will increase in brightness. This means when only one string is enabled, it must be capable of being driven at the full current (8 x the current in the above diagram).

*If I used the MOSFETs to dim each string individually using PWM, it may be a significant source of EMI as these will be driven by non-slew rate controlled ON signals.

*Dimming using PWM would be less efficient than other methods but would offer better chromacity and intensity control.

*The LEDs used in the feedback circuit will need to be illuminated and can't be switched on / off, unless the whole DC-DC converter is disabled.
My questions are:

*

*Are my assumptions correct above?

*Are there any other disadvantages to this approach?

*Could the three LEDs used in the feedback circuit be substituted with a zener diode and resistor? The feedback voltage for this driver IC is ~100mV.

Any other thoughts on this, or other potential solutions would be appreciated.

A: You could try setting up an array of BJTs to act as a current mirror.  That would balance your load currents in each leg.  Even if the transistors aren't matched sets in the same die, they should be similar enough to use for this purpose since the 10 ohm resistor is providing feedback on VBE.  The MOSFET RDSon must be well below 1 ohm to get good matching using this method.

simulate this circuit – Schematic created using CircuitLab

A: If you want to be able to turn off any or all of the strings, then a constant current drive simply does not work. As you've already discovered, if you turn off strings, then the current redistributes which will result in large variations of brightness.
I'd suggest you should drive the chains with a constant voltage. It's slightly less efficient, but may work for you.
All you need to do is make sure the voltage dropped across the series resistor is greater than the voltage change across all the LEDs (in one string) due to temperature changes.
For example:
If the voltage across the series resistor was say 2 V (the same as the LED's below) then you could turn off each LED string without impacting the current in other strings. Here the current is set at 20 mA.

simulate this circuit – Schematic created using CircuitLab

A: As already said, string 1 is operated with constant current which sets the overall voltage for all other strings. So all other strings operate at a given voltage. Therefore assumption 1 is not correct.
2 - assuming the PWM frequency is in no higher than double digit kHZ range, it would likely produce very little EMI due to "fast" edge rate. For example, a "10Mhz" edge would naturally have much reduced power with a 10kHz repeating (PWM) rate. There are always exceptions, one would be that the circuit is somehow resonant to the high frequency.
3 - dimming using PWM can theoretically approach 100% dimming efficiency, what are the "other methods"?
4 - correct.
If the feedback string is substituted with a zener, then the voltage matching would get worse. For example, the temp coefficient differences between a LED and a zener would be worse than between 2 LEDs of the same type. And typical zener diodes are not very good voltage reference (comparing to any built-in reference of a voltage regulator for example), then you might as well go constant voltage power supply.


text:
Q: How to find index of a value in an array ignoring index of a specified value Can Linq be used to find the index of a value from an array while ignoring indexes of a particular value?
Eg.
array = {1,2,3,4,0,5,0,6,7}
index of 6 is 7
if I choose to ignore the index of all zeros
and instead return 5 as the index of 6
by counting over zero but keeping 0 in the array.

A: FastReplaceFirstMatch is likely the fastest option for your very specific problem (mentioned in a comment to one of the other responses).
I've included some LINQ based solutions (which will be much faster than other ToList based solutions) to your specified question (in your question, not the comment clarification) as well.
using System;
using System.Collections.Generic;
using System.Linq;

namespace Test
{
    public static class GenericExtensions
    {
        public static int IndexExcludingValue<T>(this IEnumerable<T> test, T valueToFind, T valueToExclude) where T : struct
        {
            return test.Where(z => !Equals(z, valueToExclude))
                .Select((value, index) => new { value, index })
                .FirstOrDefault(z => Equals(z.value, valueToFind))?.index ?? -1;
        }

        public static T[] FastReplaceFirstMatch<T>(this T[] test, T valueToFind, T valueToReplace) where T : struct
        {
            var hasBeenReplaced = false;

            var index = Array.FindIndex(test, z => Equals(z, valueToFind));

            if (index != -1)
            {
                test[index] = valueToReplace;
            }

            return test;
        }

        public static IEnumerable<T> ReplaceFirstMatch<T>(this IEnumerable<T> test, T valueToFind, T valueToReplace) where T : struct
        {
            var hasBeenReplaced = false;

            return test
                .Select(value =>
                    {
                        if (!hasBeenReplaced && Equals(value, valueToFind))
                        {
                            hasBeenReplaced = true;
                            value = valueToReplace;
                        }
                        return value;
                    });
        }
    }

    public class Program
    {
        private static int[] bob = { 1, 2, 3, 4, 0, 5, 0, 6, 7 };

        static void Main(string[] args)
        {
            Console.WriteLine(bob.IndexExcludingValue(6, 0));
            Console.WriteLine(string.Join(",", bob.ReplaceFirstMatch(6, 8).ToArray()));
            Console.WriteLine(string.Join(",", bob.FastReplaceFirstMatch(6, 10)));

            Console.ReadLine();
        }
    }
}

A: e.g.,
var x = new[] { 0, 1, 3, 0, 4, 5, 6 };

using ToList()
x.Where(i => i != 0).ToList().IndexOf(5);

using ToArray()
Array.FindIndex(x.Where(i => i != 0).ToArray(), i => i == 5);

A: All i can think of at this moment is to use this to ignore specific elements on the array:
array.Where(e => e != 0);

And then this to get the index:
array.Where(e => e != 0).ToList().IndexOf(6);

A: Just to add another, in my opinion easier, solution: You can again eliminate the zeros, convert the resulting enumerable to a list then and use IndexOf on this list:
array.Where(x => x != 0)
   .ToList().IndexOf(6); //Results in 5 as well

As another, in my opinion more beautiful, solution, you could write an extension method like this:
public static class Extensions
{
    public static int IndexOfIgnoring<T> (this IEnumerable<T> collection, T indexOf, T toIgnore) =>
        collection.Where (arg => !Equals (arg, toIgnore)).ToList ().IndexOf (indexOf);
}

You can use this like that then:
static void Main (string [] args)
{
    Console.WriteLine ($"{new [] {1, 2, 3, 4, 0, 5, 0, 6, 7}.IndexOfIgnoring (6, 0)}");
    Console.ReadLine ();
}

You can read more about extension methods here.
EDIT As the comment of the OP asked me, here's a solution, to set items at the index, which ignored specific items.
Therefore I'd like to work with extension methods again:
public static class Extensions
{
    public static int IndexOfIgnoring<T> (this IEnumerable<T> collection, T indexOf, T toIgnore) =>
        collection.Where (arg => !Equals (arg, toIgnore)).ToList ().IndexOf (indexOf);

    public static int GetRealIndexOfIgnoring<T> (this IEnumerable<T> collection, int indexIgnored, T toIgnore)
        => collection.Select ((t, i) => new Tuple<T, int> (t, i)).Where (arg => !Equals (arg.Item1, toIgnore)).
                      ToList () [indexIgnored].Item2;

    public static IEnumerable<T> SetAtIndexOfIgnoring<T> (this IEnumerable<T> collection, int indexIgnored, T toIgnore, T toSet)
    {
        var enumerable = collection as IList<T> ?? collection.ToList ();
        return enumerable.Select ((t, i) => i == GetRealIndexOfIgnoring (enumerable, indexIgnored, toIgnore) ? toSet : t);
    }
}

Which we can use like this:
static void Main (string [] args)
{
    var collection = new [] {1, 2, 3, 4, 0, 5, 0, 6, 7};
    var ignoredIndex = collection.IndexOfIgnoring (6, 0);
    Console.WriteLine ($"{ignoredIndex}");
    collection = collection.SetAtIndexOfIgnoring(ignoredIndex, 0, 10).ToArray();
    Console.WriteLine(string.Join(", ", collection));
    Console.ReadLine ();
}

Which outputs:
5
1, 2, 3, 4, 0, 5, 0, 10, 7


text:
Q: PHPUnit report marks untested methods as tested I wrote two simple model classes in my Zend Framework 2 application: Catalog\Model\City Catalog\Model\CityTyble. For none of these any unit tests have been written yet. But when I create a report (user@machine:/path/to/project/module/Catalog/test# phpunit --coverage-html ./report), one of the classes is shown as tested:

...and the methods:

There are no test method for this class, not even the a class exists.
What is here wrong? Why is this untested classe / are these untested methods shown as tested?

A: This report does not exactly mean that the code is being tested. The report only says that those lines are being executed. So if you have tests that execute certain lines, you assume that they are being tested. To get this information, PHPUnit uses PHP_CodeCoverage
Do you have any code that could be being executed by PHPUnit? As said in the report, you have code somewhere that PHPUnit is executing, that is creating an instance of CityTable and calling the method fetchAll()
If you are using a configuration file, check if you are telling PHPUnit to execute the right files.


text:
Q: How Can I Find Good Resources to Learn About the $SU(5)$ and $SO(10)$ Grand Unified Theories Without an Extensive Background in the Field? I'm a first-year university student. My group and I have been tasked with finding out whether, given current scientific consensus, it looks like a viable Grand Unified Theory (GUT) can be found. We have been tasked to make a video, detailing our findings, targeted towards our peers. I am a part of the research team and we have decided to research the SU(5) and SO(10) theories as candidates for a GUT. I've been struggling somewhat to get through the complicated mathematical explanations of lie groups, gauge couplings and other technical concepts that I don't believe we have the time to fully research and comprehend.
I come here, asking the Physics Stack Exchange community for guidance on finding resources such as this one, which lay out a view of a scientific theory (String Theory as a Theory of Everything, in this case) in a way more friendly to non-experts. I understand that these sorts of resources are somewhat rudimentary for learning in that they cut out a lot of the important nuance present in more expert-targeted, robust, complicated texts or reviews. However, given the time constraint and our task, an extremely deep and nuanced understanding of GUTs seems like neither a realistic expectation nor an important one. What advice would you have that would help my team and I gain an understanding of the current scientific consensus on GUTs, such as the SU(5) and SO(10) theories, given our lack of expertise in the field?


text:
Q: Batch downloading time series of TIFF images using multi-polygons I have a working code to download a time series of (monthly) Landsat water surface rasters for a reference region of interest here. Copy-pasting the relevant lines below:
var selectCol = JRC_annual.filterDate("1984-1-1", "2019-1-1")
                   .filterBounds(geometry)
                   .map(function(img){
                     return img.clip(geometry);
                   })
                   .select("waterClass");
var region = geometry.toGeoJSONString();
var newImg = selectCol.toBands();
print(newImg.getDownloadURL({scale: 30, region: region, name:"Alaska_Annual_1984-2019"}));

I have been thinking of ways to scale this to multiple regions with a multi-polygon shapefile, without overloading Earth Engine.
Ideally, the output should be a CSV file with a list of download links with the structure (https://earthengine.googleapis.com/$ID) that can be downloaded with WGET, where ID is a unique identifier of the polygons (grids, for example, that contain not more than 10000 pixels each) in the multi-polygon shapefile.
Alternatively, is there a way to download the whole region (say the size of a continent), even if I have to do it one large image at a time, that exceeds the pixel limits of the getDownload function (i.e. "Pixel grid dimensions [...] must be less than or equal to 10000")?
Is it reasonable to expect GEE to do this without overloading it?


text:
Q: Access denied to http://repository.jboss.com/maven2/ I tried to add hibernate annotation to my Maven project but I had this following error :

*

*ArtifactDescriptorException: Failed to read artifact descriptor for hibernate-commons-annotations:hibernate-commons-annotations:jar:3.0.0.GA:
  ArtifactResolutionException: Failure to transfer hibernate-commons-annotations:hibernate-commons-annotations:pom:3.0.0.GA from http://
  repository.jboss.com/maven2/ was cached in the local repository, resolution will >not be reattempted until the update interval of JBoss repository has elapsed
  or updates are forced. Original error: Could not transfer artifact hibernate->commons-annotations:hibernate-commons-annotations:pom:3.0.0.GA from/to
  JBoss repository (http://repository.jboss.com/maven2/): Access denied to >http://repository.jboss.com/maven2/hibernate-commons-annotations/hibernate-
  commons-annotations/3.0.0.GA/hibernate-commons-annotations-3.0.0.GA.pom. Error >code 403, Forbidden

*

*ArtifactDescriptorException: Failed to read artifact descriptor for hibernate->annotations:hibernate-annotations:jar:3.3.0.GA:
  ArtifactResolutionException: Failure to transfer hibernate-annotations:hibernate->annotations:pom:3.3.0.GA from http://repository.jboss.com/maven2/ was
  cached in the local repository, resolution will not be reattempted until the >update interval of JBoss repository has elapsed or updates are forced. Original
  error: Could not transfer artifact hibernate-annotations:hibernate->annotations:pom:3.3.0.GA from/to JBoss repository (http://repository.jboss.com/
  maven2/): Access denied to http://repository.jboss.com/maven2/hibernate->annotations/hibernate-annotations/3.3.0.GA/hibernate-
  annotations-3.3.0.GA.pom. Error code 403, Forbidden

I use this code
<repository>
  <id>JBoss repository</id>
  <url>http://repository.jboss.com/maven2/</url>
</repository>

and
<!-- Hibernate annotation -->
<dependency>
    <groupId>hibernate-annotations</groupId>
    <artifactId>hibernate-annotations</artifactId>
    <version>3.3.0.GA</version>
</dependency>

<dependency>
    <groupId>hibernate-commons-annotations</groupId>
    <artifactId>hibernate-commons-annotations</artifactId>
    <version>3.0.0.GA</version>
</dependency>

A: According to the description of the JBoss Maven Repositories,
http://repository.jboss.com/maven2/ has been deprecated and should be replaced by http://repository.jboss.org/nexus/content/groups/public/.
You can read how developers should configure Maven to use the JBoss Repository.
So in your POM use :
<repositories>
  <repository>
    <id>jboss-public-repository-group</id>
    <name>JBoss Public Repository Group</name>
    <url>http://repository.jboss.org/nexus/content/groups/public/</url>
  </repository>
</repositories>

For the hibernate-annotations:hibernate-annotations:3.3.0.GA dependency, using the Maven Central repository won't help,
because it isn't hosted by it. But it is hosted by JBoss Repository in JBoss Deprecated.
However you will find it (renamed) in Maven Central at org.hibernate:hibernate-annotations:3.3.0.ga.
If you really want to use the deprecated repository :
<repositories>
  <repository>
    <id>jboss-deprecated</id>
    <name>JBoss Deprecated</name>
    <url>https://repository.jboss.org/nexus/content/repositories/deprecated/</url>
  </repository>
</repositories>

The different JBoss Maven Repositories / Groups are explained there.
See also :

*

*How To Add Remote Repository In Maven
Concerning JBoss, the deprecated groupIds (like hibernate-annotations) are published there.

A: Use the Maven Central repository instead. Have a look here.


text:
Q: Local Notifications showing more than once First of all, sorry for my english.
I've got a problem with an app that creates multiple local notifications. I'm scheduling them in a for loop :
for (int i = 0; i < 100 ; i++) {
    compteur++;

    UILocalNotification *prototypeNotification = [[UILocalNotification alloc] init];
    prototypeNotification.timeZone = [NSTimeZone defaultTimeZone];

    prototypeNotification.applicationIconBadgeNumber = 0;
    prototypeNotification.alertBody = @"ALERTE PILULE !!!!!";
    prototypeNotification.alertAction = @"Ok";
    [prototypeNotification setSoundName:UILocalNotificationDefaultSoundName];
    prototypeNotification.fireDate = itemDate;

    [[UIApplication sharedApplication] scheduleLocalNotification:prototypeNotification];
    [prototypeNotification release];

    itemDate = [[NSCalendar currentCalendar] dateByAddingComponents:comps toDate:itemDate options:0];

    if (compteur == 21) {
        compteur = 0;
        itemDate = [[NSCalendar currentCalendar] dateByAddingComponents:comps2 toDate:itemDate options:0];

    }
}

When the firedate has come, it works well but it shows not only one but 2 or 3 or 6 alerts sometimes... And I just can't find why... Can someone help me?
Thanks

A: - (void)applicationWillEnterForeground:(UIApplication *)application
{
    // Called as part of the transition from the background to the inactive state;
    //here you can undo many of the changes made on entering the background.
    UIApplication *APP =[UIApplication sharedApplication];
     NSArray *oldnotification = [APP scheduledLocalNotifications];
    if (oldnotification>=0)
    {
         [APP cancelAllLocalNotifications];
    }
}

Are you adding this code in above module.. to cancel old notifications??