Q: MVC3 gives a Blank chart My LoggedUserHome.Controller has this action for chart
 public ActionResult GetGender()
    {

        var AllGender = new List<string>(from c in db.tbl_Profile select c.sex).ToList();
        var Groping = AllGender
           .GroupBy(i => i)
           .Select(i => new { sex = i.Key, CountGet = i.Count() }).ToArray(); //get a count for each

        var key = new Chart(width: 300, height: 300)
            .AddSeries(
            chartType: "pie",
            legend: "Gender Popularity",
            xValue: Groping, xField: "sex",
            yValues: Groping, yFields: "CountGet")
            .Write("gif");
        return null;

    }

and in my view I have given

Thanks to Nexuss ToArray() suggestion I manage to populate the chart by reading the database.. Thanks a lot Nexuzz

A: Simple solution is to try to replace your

in the view with
@{
    var d = new PrimeTrekkerEntities1();
    var AllGender = new List<string>(from c in d.tbl_Profile select c.sex).ToList();
    var Groping = AllGender
        .GroupBy(i => i)
        .Select(i => new { sex = i.Key, Count = i.Count() }); //get a count for each

    var key = new Chart(width: 600, height: 400)
        .AddSeries(
        chartType: "pie",
        legend: "Gender Popularity",
        xValue: Groping, xField: "sex")
        .Write("gif");
}

And "yes" you don't need action GetGender in this case.
More complex solution would be to leave

in the view, but make GetGender() action return chart image URL. So, what you can do in GetGender() is somehow render chart into image file and return response that contains the image's path.
update:
I've updated your example a bit, so it displays data in the chart. Here is what I've got:
@{
    var AllGender = new List<string>() { "Male", "Female", "Male"};
    var Groping = AllGender
        .GroupBy(i => i)
        .Select(i => new { sex = i.Key, Count = i.Count() }).ToArray(); //get a count for each

    var key = new Chart(width: 600, height: 400)
        .AddSeries(
        chartType: "pie",
        legend: "Gender Popularity",
        xValue: Groping, xField: "sex",
        yValues: Groping, yFields: "count")
        .Write("gif");
}

There are two main differences with your example:

*

*Groping is now an array. As far as I understand Chart expects data to be enumerated

*I added yValues and yFields parameters, so chart knows what values to use on Y axis


Q: Xamarin Android load local html file with routing How can I load local html file with routing in Android Webview?
The url looks like this:
file:///android_asset/Content/index.html/#/first-view
file:///android_asset/Content/index.html/#/second-view

I tried with this code but it's not working:
AppWebView.LoadUrl("file:///android_asset/Content/index.html/#/first-view");


Q: Calling base component's methods/features Having Base.vue
<template><div>{{ name }}</div></template>
<script>
  export default {
    data() {
      return {name: 'Example Component'};
    }
  };
</script>

And Extended.vue:
<script>
  import Base from './Base.vue';
  export default {
    extends: Base,
    data() {
      return {name: 'Extended Example Component'};
    }
  };
</script>

Is it possible to reuse data from base one instead of hardcoding Extended Example Component? Some kind of super from OOP? Looking for generic solution involving stuff like mount, methods, computed, etc.
UPDATE
When using OOP we use such approach (Python example):
class Base:
   def __init__(self):
       self.name = 'Example Component'

class Extended(Base):
   def __init__(self):
       super().__init__()
       self.name = f'Extended {self.name}'

This way we reuse self.name field.

A: extends and mixins merge options in a specified way, this is the official way to inherit component functionality. They don't provide full control over the inheritance.
For static data that may change between component definitions (Base and Extended) custom options are commonly used:
export default {
  myName: 'Component',
  data() {
    return { name: this.$options.myName };
  }
}

and
export default {
  extends: Base,
  myName: `Extended ${Base.options.myName}`
}

Notice that name is existing Vue option and shouldn't be used for arbitrary values.
Any reusable functions can be extracted from component definition to separate exports.
For existing components that cannot be modified data and other base component properties can be accessed where possible:
  data() {
    let name;

    name = this.$data.name;
    // or
    name = Base.options.data.call(this).name;

    return { name: `Extended ${name}` };
  }

This approach is not future-proof and not compatible with composition API, as there's no clear distinction between data, etc, and this is unavailable in setup function. An instance can be accessed with getCurrentInstance but it's internal API and can change without notice.

A: The data object is a kind of state for a single component, hence the data object inside a component can only be accessed in that component and not from outside or other components.
For your specific requirement, you can use Vuex. It helps you access the state in multiple components. Simply define a state in the vuex store and then access the state in the component.
If you don't want to use Vuex, then another simple solution is to store the data in localStorage and then access the data in multiple components.

A: You can access your data, from child component. You can do that by this.$parent.nameOfTheDataYouHave.
This cheatsheet can help you with the basics of the component anatomy and lifecycle hooks(mounted,created,etc..).
And last this is the proper way of two-way binding data (parent-child).


Q: I get "IndexError: list index out of range" when installing Pandas in python So, I installed pandas with cmd :

but when I try to import it i get this error:

Traceback (most recent call last):   File
  "C:/Users/Uros/Desktop/fasda.py", line 1, in
      import pandas  ModuleNotFoundError: No module named 'pandas'

and when I try to install it in setting I get this error:

A: As the second screenshot shows, you need to install pandas for your the python interpreter that you use, like this:
C:\Users\Uros\untitled\Scripts\python.exe -m pip install -U pandas


Q: Generate TIE cells with Yosys? I am using Yosys to synthesise my RTL design which includes a couple of literal constants, such as tied output ports as in the following code:
module my_module (
    input a,
    input b,
    output c,
    output d);

    assign c = a & b;
    assign d = 1'b1;
endmodule

In this case, output d will obviously always be a logical one. The flow I am using includes the abc -liberty my_stdcells.lib call to map the combinatorial logic to the standard cells provided by the library, followed by the clean and write_verilog calls.
The cell library I am using also provides TIELO and TIEHI cells, but the synthesised Verilog netlist doesn't include any instances of those cells but instead still shows literal constants like in the example above.
I could probably write a script to post-process the synthesised netlist to replace these literals with TIE* cell instances from the library, but I am wondering if I could get Yosys to do that for me somehow, resulting in something like
TIEHI tiehi_d_inst(.Y(d));

for the assign d = 1'b1 line in the code above.

A: The command you are looking for is hilomap. For example, to map to TIEHI and TIELO cells with Y outputs use something like:
hilomap -hicell TIEHI Y -locell TIELO Y

This will create an individual TIEHI/TIELO cell for each constant bit in the design. Use the option -singleton to only create single TIEHI/TIELO cells with a higher fan-out.


Q: Python Pandas match exact pattern I'm trying to match a pattern with a column of a dataframe
pattern='pgk'
df = pd.DataFrame([['merged_pgk', 10], ['merged_Pgk', 3], ['merged_pgk_stim', 12], ['merged_Scp1', 5]], columns=['condition','count'])

I want the row where pattern is in the column condition.
df[df['condition'].str.lower().str.contains(pattern)]

I tried this but the problem here is that it will return pgk row (what I want) but I got also pgk_stim row (what I don't want)

A: try np.where with str.contains and case=False to ignore the case.
and $ to only match pgk at the end of a string.
df['check'] = np.where(df['condition'].str.contains('pgk$',case=False), True,False)

print(df)

         condition  count  check
0       merged_pgk     10   True
1       merged_Pgk      3   True
2  merged_pgk_stim     12  False
3      merged_Scp1      5  False

A: you can use endswith function
df[df['condition'].str.lower().str.endswith(pattern)]


Q: How to find duplicate items in list<>? I have:
List<string> list = new List<string>() { "a", "a", "b", "b", "r", "t" };

How can I get only "a","b"?
I tried to do like this:
List<string> list = new List<string>() { "a", "a", "b", "b", "r", "t" };
List<string> test_list = new List<string>();

test_list = list.Distinct().ToList();

Now test_list has {"a", "b", "r", "t"}
And then:
test_list = test_list.Except(list).ToList();

So that was my fail point, cause Except() deleted all elements.
Could you help me with solution?

A: Try this
var duplicates = list.GroupBy(a => a).SelectMany(ab => ab.Skip(1).Take(1)).ToList();

A: A simple approach is using Enumerable.GroupBy:
var dups = list.GroupBy(s => s)
               .Where(g => g.Count() > 1)
               .Select(g => g.Key);

A: List<string> list = new List<string>() { "a", "a", "b", "b", "r", "t" };

var dups = list.GroupBy(x => x)
    .Where(x => x.Count() > 1)
    .Select(x => x.Key)
    .ToList();

A: var list = new List<string> { "a", "a", "b", "b", "r", "t" };

var distinct = new HashSet<string>();
var duplicates = new HashSet<string>();

foreach (var s in list)
    if (!distinct.Add(s))
        duplicates.Add(s);

// distinct == { "a", "b", "r", "t" }
// duplicates == { "a", "b" }

A: var duplicates = list.GroupBy(s => s).SelectMany(g => g.Skip(1).Take(1)).ToList();

A: var duplicates = list.GroupBy(a => a).SelectMany(ab => ab.Skip(1).Take(1)).ToList();

It will be more efficient then the one using Where(g => g.Count() > 1) and will return only one element from every group.


Q: Differentiating the term "UI" and "HUD" in games
In video gaming, the HUD (head-up display) or Status Bar is the method
  by which information is visually relayed to the player as part of a
  game's user interface.
The HUD is frequently used to simultaneously display several pieces of
  information including the main character's health, items, and an
  indication of game progression (such as score or level).

(Wikipedia)
I assume menus aren't part of the HUD.
What's the difference?

A: UI (User Interface)

UI refers to the methods (keyboard control, mouse control) and
  interfaces (inventory screen, map screen) through which a user
  interacts with a game.

HUD (Head-Up Display)

In video gaming, the HUD (head-up display) or Status Bar is the method
  by which information is visually relayed to the player as part of a
  game's user interface.

Verdict
Looking at these definitions, the HUD is actually a part of the UI as it can have an effect on how the player interacts with the game.
For example, the Overwatch HUD which displays when an ultimate is ready to use:

Summary
When looking at the definitions and examples of how the HUD can impact the UI, it seems as though there is no right or wrong answer, as the phrases and the uses they hold in game, support each other.
Neither word should be used over the other, as they work together.
(I apologize if this answer is hard to understand, I tried to explain it as best as I could)

A: HUD is short for heads-up display, which is a method of displaying (usually graphical) information in a way that overlays normal vision. For example, icons or other info can be displayed on the window in front of a pilot in an aircraft. This allows a pilot to be notified of important information while not taking their eyes off the terrain or opponents while flying.
In video games, HUD usually refers to the graphical information around the edges (or if translucent across the entire screen) of the 'main' playing window. So in first person shooters the symbol for the weapon you are carrying, the ammo it is loaded with, and your health levels are usually part of the HUD.
UI, or user interface refers to all the methods for interacting with a system (or game), both system to user (vision, sound, tactile) and user to system (mouse/keyboard/other controls). Joysticks, mice, microphones, switches, buttons, keyboards, pedals, lights, speaker sounds, and anything displayed on a computer monitor are all part of the UI.  As James Smith says in his answer, a HUD is a (sub)part of the total UI.


Q: WPF GradientBrush? How Many type of gradient brushes are available like LinearGradientBrush, SolidColorBrush?
and when we create a GradientStop how the offset works?
        LinearGradientBrush LGB = new LinearGradientBrush();
        LGB.StartPoint = new Point(0, 0);
        LGB.EndPoint = new Point(0, 1);
        LGB.GradientStops.Add(new GradientStop(Color.FromRgb(255,251,255) , 0));
        LGB.GradientStops.Add(new GradientStop(Color.FromRgb(206,207,222), 1));
        LGB.GradientStops.Add(new GradientStop(Color.FromRgb(0, 247, 0), 2));
        rect.Fill = LGB;

Why the third one "Color.FromRgb(0, 247, 0)" is not reflecting?
Please suggest,where i am wrong?

A: The GradientStop.Offset property is a value which ranges from 0.0 to 1.0. From the MSDN documentation:

A value of 0.0 specifies that the stop is positioned at the beginning of the gradient vector, while a value of 1.0 specifies that the stop is positioned at the end of the gradient vector.

Change your second stop's offset to 0.5 and your third's to 1.0 and it should work.


Q: D-Link DWA-130 rev E1 RTL8191SU Wont Connect to Network (14.04) Having a problem with getting my  D-Link usb Wi-Fi dongle to connect to my wifi network.
The dongle works, it scans and gives back the SSID's that are available, however when I try to connect, it will not, it attempts connection and fails, then retries. Every once in a while it will work, but it seems completely random.
I tried this fix and my wifi connected, when I restarted, after a bit I shut the system down, came back the next day and my wifi dongle is back to the connection loop from hell

A: You can solve it by re-installing the driver and running
sudo update-initramfs -u

after that.


Q: GWT application generating IE insecure item warning Our service runs over HTTPS and we're currently experimenting with running a compiled GWT-application within it, only client side, no RPC:s.
It is included within an IFRAME, which seems to be recommended (here for example: http://developerlife.com/tutorials/?p=231 under the heading HTTPS and HTTP).
When doing certain operations within the GWT-app, IE it generates an insecure item warning.
http://bagonca.com/insecure_item.png
You may ask yourself why I don't use some nifty Firefox plugin to see what request might be over http. Or why I don't use HTTPWatch in Internet Explorer for the same reason. I have. There are no insecure requests that I can find, anywhere.
What I have read about on the other hand is that Internet Explorer throws this warning for iframes without the src attribute set. And that a potential fix is using src="javascript:false" for any iframe that is populated dynamically.
As I've said, the whole app is included via an IFRAME, and within it GWT itself generates a hidden IFRAME that looks like below.

I've tried hard coding the src attribute above to a blank page that actually exists and is called with HTTPS on the same domain. I've tried the javascript:false; approach. No luck. The app works like a charm, but IE throws the useless, and false warning.
The warning turns up when I do certain actions within the app, not when it is loaded. Actually when dragging and dropping appointments within the http://code.google.com/p/gwt-calendar/ component.
Has anyone tangled with a similar issue before? Any clues?

A:
Any clues?

I'm not sure in this case, but I did some experiments with iframes (on a somewhat similar topic) about a year ago. I would assume, that gwt-calendar tries to communicate with the host page via javascipt's parent reference. AFAIR, that's not allowed, when the host page isn't loaded from the same origin (including protocol).

A: There other snippets of Javascript that can also cause a problem. Please see:
http://blog.httpwatch.com/2009/09/17/even-more-problems-with-the-ie-8-mixed-content-warning/
Also, have a look through the pile of comments on:
http://blog.httpwatch.com/2009/04/23/fixing-the-ie-8-warning-do-you-want-to-view-only-the-webpage-content-that-was-delivered-securely/
Some of the commenters have found and fixed other causes of the warning too.

A: This can happen if you have your app running over HTTPS and are fetching images or some other resource over over plain HTTP. Check if you have image or css paths hardcoded to http://.
For example, if your app if running at https://example.com and you wish to load an image foo.jpg , the html you should be using is:

or (ideally)

and not

Note that the third example fetches the foo.jpg image over http instead of https. Hence it would cause the issue which you are facing.
To avoid such problems, the best practice is either to use ImageResources and relative URLs.


Q: Error retrieving data from a remote database in PHP
How can I solve the problem shown in the table? This happened while I was trying to retrieve data from my database. In my java code, the json array that I try to call is null.
db_connect.php
<?php
class DB_CONNECT{
// constructor
function __construct() {
    // connecting to database
    $this->connect();
}

// destructor
function __destruct() {
    // closing db connection
    $this->close();
}

/**
 * Function to connect with database
 */
function connect() {
    // import database connection variables
    require_once __DIR__ . '/db_config.php';

    // Connecting to mysql database
    $con = mysql_connect(DB_SERVER, DB_USER, DB_PASSWORD) or die(mysql_error());

    // Selecing database
    $db = mysql_select_db(DB_DATABASE) or die(mysql_error()) or die(mysql_error());

    // returing connection cursor
    return $con;
}

/**
 * Function to close db connection
 */
function close() {
    // closing db connection
    mysql_close();
}

}

?>'

retEqp.php
<?php

/*
 * Following code will list all the products
 */

// array for JSON response
$response = array();

// include db connect class
require_once __DIR__ . '/db_connect.php';

// connecting to db
$db = new DB_CONNECT();

// get all products from products table
$result = mysql_query("SELECT *FROM facilities_equipments where item_Type='Equipment'") or die(mysql_error());

// check for empty result
if (mysql_num_rows($result) > 0) {
    // looping through all results
    // products node
    $response["equipments"] = array();

    while ($row = mysql_fetch_array($result)) {
        // temp user array
        $equipment = array();
        $equipment["item_ID"] = $row["item_ID"];
        $equipment["item_Name"] = $row["item_Name"];

        // push single product into final response array
        array_push($response["equipments"], $equipment);
    }
    // success
    $response["success"] = 1;

    // echoing JSON response
        echo json_encode($response);
    } else {
        // no products found
        $response["success"] = 0;
        $response["message"] = "No products found";

    // echo no users JSON
    echo json_encode($response);
    }
    ?>

A: Replace your code
$con =  mysql_connect(DB_SERVER, DB_USER, DB_PASSWORD) or die(mysql_error());

with
$con =  mysqli_connect(DB_SERVER, DB_USER, DB_PASSWORD) or die(mysql_error());

Turn off all deprecated warnings including them from mysql_*:
error_reporting(E_ALL ^ E_DEPRECATED);


Q: Find Hours Between Startdate and Enddate of different table TimeSheetData timesheetdata = new TimeSheetData();
TimeSheet timeSheet = new TimeSheet();
TimeSheetData timesheetdata = new TimeSheetData();
                        timeSheet.StartDate = thisWeekStart;
                        timeSheet.EndDate = thisWeekEnd;
                        timesheetdata.Date = dt;

                        string HourData = item.Value;
                        string TaskID = item.ID.Split(':')[0];
                        timesheetdata.TaskID = Guid.Parse(TaskID);
                        timesheetdata.TimeSheet = timeSheet;
                        timesheetdata.Hours = Convert.ToDouble(HourData);
                        db.TimesheetData.Add(timesheetdata);
                        db.SaveChanges();

var TMS = db.TimeSheets.Where(t => t.StartDate == thisWeekStart
                                   && t.EndDate == thisWeekEnd).ToList();

My tables are:

*

*Timesheets (Guid, Startdate, Enddate)

*TimeSheetDatas (Guid, hours, Date, Task  GUID, Timesheet Guid)

I want to find hours (TimesheetDatas) between StartDate and EndDate (Timesheets).
 Hours find = var TMS

A: You didn't provide some details but do you want something like that;
var query = from ts in db.TimeSheets
join tsd in db.TimesheetDatas on ts.Guid equals tsd.TimesheetGuid
where ts.StartDate > thisWeekStart && ts.StartDate < thisWeekEnd
select tsd.hour


Q: How to know if email was sent from intent In my app, I'm creating an intenet to send an email... it looks like this
final Intent emailIntent = new Intent(Intent.ACTION_SEND)
                        .putExtra(Intent.EXTRA_EMAIL, new String[]{mBuilder.mEmail})
                        .putExtra(Intent.EXTRA_SUBJECT, mBuilder.mSubject)
                        .putExtra(Intent.EXTRA_TEXT, Html.fromHtml(getBody()))
                        .putExtra(Intent.EXTRA_STREAM, zipUri)
                        .setType("application/zip");
                mBuilder.mContext.startActivity(Intent.createChooser(
                        emailIntent, mBuilder.mContext.getString(R.string.send_using)));

I want to know if it's possible to know if the email was actually sent or not, so I can perform some actions after that happens.
If so, please explain me how and if possible add a code snippet, please.
Thanks in advance.

A:
I want to know if it's possible to know if the email was actually sent or not

No.
First, there is no requirement that the user chooses an email client for this startActivity() request.
Second, there is nothing in the ACTION_SEND protocol that lets the app offering to share the content know whether or not the user did anything with that content.

A: Maybe you could try startActivityForResult() and see whether the resultcode changes depending on what the user did


Q: Asp.net - Starting server with Kestrel on OS X I have not worked with Asp.net before. I'm trying to get an MVC Project running on my machine. I'm running OS X 10.9.3.
I tried following the instructions in this tutorial: http://docs.asp.net/en/latest/tutorials/your-first-mac-aspnet.html
But when I run $ dnx . kestrel in the projects directory I get the following error:
System.InvalidOperationException: Unable to resolve project 'XYZ' from /Users/jeff/Sites/XYZ/XYZ.com
  at Microsoft.Framework.Runtime.ApplicationHostContext..ctor (IServiceProvider serviceProvider, System.String projectDirectory, System.String packagesDirectory, System.String configuration, System.Runtime.Versioning.FrameworkName targetFramework, ICache cache, ICacheContextAccessor cacheContextAccessor, INamedCacheDependencyProvider namedCacheDependencyProvider, IAssemblyLoadContextFactory loadContextFactory, Boolean skipLockFileValidation) [0x00000] in <filename unknown>:0
  at Microsoft.Framework.Runtime.DefaultHost.Initialize (Microsoft.Framework.Runtime.DefaultHostOptions options, IServiceProvider hostServices) [0x00000] in <filename unknown>:0
  at Microsoft.Framework.Runtime.DefaultHost..ctor (Microsoft.Framework.Runtime.DefaultHostOptions options, IServiceProvider hostServices) [0x00000] in <filename unknown>:0
  at Microsoft.Framework.ApplicationHost.Program.Main (System.String[] args) [0x00000] in <filename unknown>:0
  at (wrapper managed-to-native) System.Reflection.MonoMethod:InternalInvoke (System.Reflection.MonoMethod,object,object[],System.Exception&)
  at System.Reflection.MonoMethod.Invoke (System.Object obj, BindingFlags invokeAttr, System.Reflection.Binder binder, System.Object[] parameters, System.Globalization.CultureInfo culture) [0x00000] in <filename unknown>:0
--- End of stack trace from previous location where exception was thrown ---
  at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw () [0x00000] in <filename unknown>:0
  at Microsoft.Framework.Runtime.Common.EntryPointExecutor.Execute (System.Reflection.Assembly assembly, System.String[] args, IServiceProvider serviceProvider) [0x00000] in <filename unknown>:0
  at dnx.host.Bootstrapper.RunAsync (System.Collections.Generic.List`1 args, IRuntimeEnvironment env, System.Runtime.Versioning.FrameworkName targetFramework) [0x00000] in <filename unknown>:0

What can I try to fix this?

A: It means that dnx cannot find Startup.cs file. Try to run dnx . kestrel inside folder which contains Startup.cs


Q: Abbreviating names that start with a vowel What are the rules about abbreviating names that start with a vowel? Would abbreviating "Alanis Morissette" to "A. Morissette" be correct or should it be "Al. Morissette"?

A: When abbreviating all kinds of names, the first letter is taken:

David Jones / D. Jones
  James McKenzie/ J. McKenzie
  Esther Hart / E. Hart
  Otis Witherspoon/ O. Witherspoon

A: In normal English usage, abbreviations of names are based only on the first letter as spelled. This is true for first, middle, and last names:

*

*John Edgar Hoover → J. Edgar Hoover

*Dwight David Eisenhower → Dwight D. Eisenhower

*John Smith → John S. (common for e.g. schoolchildren, if there is another John in the same class)

*John Fitzgerald Kennedy → John F. Kennedy → JFK

and regardless of pronunciation:

*

*Philip /ˈfĭlĭp/ → P. (whereas Felipe → F.)

Therefore, you would abbreviate your example as

*

*Alanis Morissette → A. Morissette

There are 2 exceptions I can think of.

*

*First, nicknames may be formed irregularly; for example "McDonald" → "McD".

*Second: in the most common transliteration scheme from Cyrillic to Latin, some Cyrillic letters get mapped to 2 or more Latin letters. When transliterating abbreviated names from Cyrillic, usually both are kept (only the first is capitalized).  Example: Цахиагийн Элбэгдорж → Ц. Элбэгдорж → Ts. Elbegdorj

This only applies to transliterations from foreign languages. So, for example, in text written originally in English, Russian-American Sergei Khrushchev's name would be abbreviated "K.", not "Kh.".

A: It's uncommon in the U.S. to use anything more than the first initial – consonant or vowel.  However, one rare but interesting exception is when two players on the same athletic team share the same last name, and the same first initial.  In such circumstances, sometimes the second letter is used to differentiate between, say, Michael and Martellus.


Q: Can someone explain this css margin behaviour? A friend of mine had a problem with this simple html/ css task: http://jsfiddle.net/kaHzY/6/
The problem was that the .headline 's margin-top was pushing down the #main div although it should directly follow the nav without any space between.
Adding a div .inner with a padding of 1px solved this issue. The .headline still had the margin but was not pushing down the #main div anymore.
I know this behaviour but I cant explain it. How can you explain that, especially to someone who is learning css? Why does it behave like that?
Thanks

A: This is classic collapsing margin behavior.
The people who wrote the CSS spec thought this was a good idea in order to prevent excessive white space from being created by margins.  Without this behavior, it would be a lot more work to control margin/whitespace between block elements.
References:
CSS2 Spec - http://www.w3.org/TR/CSS2/box.html#collapsing-margins
Andy Budd Article - http://andybudd.com/archives/2003/11/no_margin_for_error/
Eric Meyer Article - http://www.complexspiral.com/publications/uncollapsing-margins/
Why Collapsing Margins Are a Good Idea
Collapsing margins are a feature of the CSS Box Model, which forms the basic working unit for the Visual Formatting Model, which allows us to have a rational environment in which to develop web pages.
In designing the CSS specification, the authors had to balance how how rules would be written, for example: margin: 1.0em, and how these rules would work in a CSS formatting engine that needs to layout block of content from top-to-bottom and left-to-right (at least in Western European languages).
Following the train-of-thought from Eric Meyer's article cited above, suppose we have a series of paragraphs with margins styled according to:
p { margin: 1.00em; }

For those of us who used to seeing printed pages with regular spacing between paragraphs, one would expect the space between any two adjacent paragraphs to be 1.00em.  One would also expect the first paragraph to have a 1.00em margin before it and the last paragraph to have a 1.00em margin after it.  This is a reasonable, and perhaps simplified, expectation of how the simple CSS rule for p should behave.
However, for the programmers building the CSS engine that interprets the simple p rule, there is a lot of ambiguity that needs to be resolved.  If one is expecting the printed page interpretation of the CSS rule, then this naturally leads to the collapsing margin behavior.  So the programmers come up with a more complicated rule like: if there are two adjacent p tags with top and bottom margins, merge the margins together.
Now this begs the question, how do you "merge margins together"? min or max of the adjacent top and bottom margins, average of the two? margin of first element always?  And what if you have other block elements other than p's? and if you add a border or background? what next?
Finally, how do you compute all of these margin settings in such a way so that you don't have to iterate through the entire set of HTML elements several times (which would make complicated pages load slowly especially in early generations of browsers)?
In my opinion, collapsing margins offered a solution to a complicated problem that balanced the ease of writing CSS rules for margins, the user expectation of how printed pages are laid out in our typographic heritage, and finally, provided a procedure that could be implemented within the programming environment that browsers exist in.

A: I achieved your desired layout by:

*

*Resetting the default margins and padding on the p tags:
p{
  margin: 0px auto;
  padding: 0px;
 }
Make sure you add this to the top of your CSS.

*Then changed the .headline and .text classes to use padding instead of margin; using your same values.

*Removed the #main .inner CSS entirely.


Q: No internet, but can ping from cmd My internet was working fine, but one day it stopped working at all (I am using ethernet connection). It just says 'No internet'. I can ping www.google.com and ping 8.8.8.8. but when I launch the browser none of the websites works.
I am using Windows 10.
The cable is fine, I tried different ones and no effect.
What I have already tried:

*

*When ipconfig /all and for Ethernet adapter Ethernet it prints all the information. For all others (LAN, wifi) it says Media state..............: Media disconnected.

*I run Network adapter troubleshooter and it reset the adapter. That didn't help either.
Could you please help me with it?
PS: I also cannot browse through WI-FI, even though when I use wifi it doesn't say 'No internet' - just 'Connected, secured'.

A: This sounds like you have a proxy setup for the internet.
Open Powershell or CMD as Admin and run
netsh.exe winhttp show proxy

That should list any proxies setup. To remove run
netsh.exe winhttp reset proxy

Or check 'Internet Properties', CMD run
inetcpl.cpl

Go to the 'Connections' tab and look at the 'Dial-up/VPN settings'
See if you have anything setup and just select each and then click the 'remove' button.

A: My internet was working fine, but one day it stopped working at all
Try completely reinitialising all network states.
Run the following commands in an elevated cmd shell:

*

*Reset WINSOCK entries to installation defaults (reboot required):
netsh winsock reset catalog

*Reset TCP/IP stack to installation defaults:
netsh int ip reset reset.log

*Reset Firewall to installation defaults:
netsh advfirewall reset

*Flush DNS resolver cache:
ipconfig /flushdns

*Renew DNS client registration and refresh DHCP leases:
ipconfig /registerdns

*Flush routing table (reboot required):
route /f

A: If you see:
nslookup google.com
*** Request to UnKnown timed-out
DNS request timed out.
    timeout was 2 seconds.

Then set DNS servers to:
8.8.8.8
8.8.4.4

Manual: https://developers.google.com/speed/public-dns/docs/using

*

*open network connection settings

*set Google Public DNS
More images: https://www.windowscentral.com/how-change-your-pcs-dns-settings-windows-10


Q: Overcome VBA InputBox Character Limit The current function I use to collect text InputBox can't accept more than 255 characters apparently, and I need to be able to collect more than that? Is there a parameter or different function I can use to increase this limit?

A: To be pedantic, the Inputbox will let you type up to 255 characters, but it will only return 254 characters.
Beyond that, yes, you'll need to create a simple form with a textbox. Then just make a little "helper function" something like:
Function getBigInput(prompt As String) As String
    frmBigInputBox.Caption = prompt
    frmBigInputBox.Show
    getBigInput = frmBigInputBox.txtStuff.Text
End Function

or something like that...

A: Thanks BradC for the info that. My final code was roughly as follows, I have a button that calls the form that I created and positions it a bit as I was having some issues with the form being in the wrong spot the everytime after the first time I used.
Sub InsertNotesAttempt()
    NoteEntryForm.Show
    With NoteEntryForm
        .Top = 125
        .Left = 125
    End With
End Sub

The userform was a TextBox and two CommandButtons(Cancel and Ok). The code for the buttons was as follows:
Private Sub CancelButton_Click()
    Unload NoteEntryForm
End Sub

Private Sub OkButton_Click()
    Dim UserNotes As String

    UserNotes = NotesInput.Text

    Application.ScreenUpdating = False
    If UserNotes = "" Then
        NoteEntryForm.Hide
        Exit Sub
    End If

    Worksheets("Notes").ListObjects("Notes").ListRows.Add (1)
    Worksheets("Notes").Range("Notes").Cells(1, 1) = Date
    Worksheets("Notes").Range("Notes").Cells(1, 2) = UserNotes
    Worksheets("Notes").Range("Notes").Cells(1, 2).WrapText = True
    ' Crap fix to get the wrap to work. I noticed that after I inserted another row the previous rows
    ' word wrap property would kick in. So I just add in and delete a row to force that behaviour.
    Worksheets("Notes").ListObjects("Notes").ListRows.Add (1)
    Worksheets("Notes").Range("Notes").Item(1).Delete
    NotesInput.Text = vbNullString
    NotesInput.SetFocus ' Retains focus on text entry box instead of command button.
    NoteEntryForm.Hide
    Application.ScreenUpdating = True
End Sub

A: I don't have enough rep to comment, but in the sub form_load for the helper you can add:
me.AutoCenter = True

Outside of that form, you can do it like this:
NoteEntryForm.Show
Forms("NoteEntryForm").AutoCenter = True

My Access forms get all confused when I go from my two extra monitors at work to my one extra monitor at home, and are sometimes lost in the corner.  This AutoCenter has made it into the form properties of every one of my forms.


Q: Proper method to timing how long a sorting algorithm takes (Using Java)
I'm testing sorting arrays to see literally how fast different sorting arrays take.  I want to weed out the erroneous times, so ideally I would like to start a timer, run the sort in a loop of say 100 times, stop the timer, then divide by 100 to get a pretty accurate measure.
The problem is if I were to loop the same array, it'll sort properly the first time, then each sort after, it'll keep sorting the already sorted array, which isn't what I want.
Maybe I'm missing an obvious solution, but is there any way I can make it keep sorting the same initial randomized array?
I thought about reassigning the newly sorted array back to the initial random array each time, but that would mess up my timer..
thanks for any suggestions
what i would like to do:
        startTime = System.nanoTime();
        for(int i=0; i<cntr; i++) {
            sort array
        }
        endTime = System.nanoTime();
        time = (endTime - startTime)/cntr;

A: You can make a copy before you start sorting, and then copy from that stored copy into the array being sorted in each iteration of the loop.
int[] toBeSorted = new int[10000];
// fill the array with data
int[] copied = new int[10000];
System.arrayCopy(toBeSorted, 0, copied, 0, copied.length);
// prepare the timer, but do not start it
for (int = 0 ; i != 100 ; i++) {
    System.arrayCopy(copied, 0, toBeSorted, 0, copied.length);
    // Now the toBeSorted is in its initial state
    // Start the timer
    Arrays.sort(toBeSorted);
    // Stop the timer before the next iteration
}

A: You can use the System.currentTimeMillis() method to get the current time then subtract when the method finishes executing.
long totalRuntime = 0;

for(int i = 0; i < 100; i++)
{
   long startTime = System.currentTimeMillis();
   sortArrays()
   long endTime = System.currentTimeMillis();

   totalRuntime += (endTime - startTime);
}

System.out.println("Algorithm X on average took "
                    + totalRuntime/100 + " milliseconds);

If you want to do this X times just keep a counter for each algorithm and increment. Then you can divide by the total number of runs at the end and compare.

A: Generally you would stop and start the timer in between each run of the algorithm you're testing, adding up the individual times and then dividing by the number of runs. That way any "setup time" isn't included because the timer isn't running during the setup.

A: Go with something like this
new array equals random array,
start timer
sort new array
stop timer
add time to your list of times
repeat until necessary

As long as you copy the original array each time, you will never sort the original one

A: put the sorting algorithm in a function and keep calling the function with the same again and again and passing the array to the function after cloning it using the clone method.
You can call the current time function and print it out every time you run the loop.

A: If you're willing to blow memory, then just make 100 (or however many) copies of the same array before you start timing. If you're not, then time sorting and copying together, and then time just copying to see approximately how much of your sorting + copying time was spent copying.
Also, sidenote: look into using a benchmarking framework like Caliper instead of doing your own "manual" benchmarking. It's easier, and they've solved a lot of problems that you might not even know are going on that could screw up your timings.


Q: Getting graphics object to draw with buffer strategy I've made a JFrame with a canvas on it and I want to draw on that canvas. At a later date the canvas will be updating many times a second so I am using a buffer strategy for this. Here is the code:
package mainPackage;

import java.awt.Canvas;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.image.BufferStrategy;

import javax.swing.JFrame;

public class TickPainter {
    //just some presets for a window.
    public static JFrame makeWindow(String title, int width, int height) {
        JFrame mainWindow = new JFrame();
        mainWindow.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        mainWindow.setSize(width, height);
        mainWindow.setVisible(true);
        mainWindow.setLocationRelativeTo(null);
        mainWindow.setTitle(title);

        return mainWindow;
    }

    public static void main(String[] args) {

        JFrame mainWindow = makeWindow("Practice", 800, 600);
        Canvas mainCanvas = new Canvas();
        mainWindow.add(mainCanvas);
        mainCanvas.setSize(mainWindow.getWidth(), mainWindow.getHeight());
        mainCanvas.setBackground(Color.white);
        mainCanvas.createBufferStrategy(3);
        BufferStrategy bufferStrat = mainCanvas.getBufferStrategy();

        Graphics g = bufferStrat.getDrawGraphics();
        g.setColor(Color.black);
        g.fillRect(250, 250, 250, 250);
        g.dispose();
        bufferStrat.show();
    }
}

The program does not draw the black rectangle as intended, I feel like I've missed something really obvious here and I just can't see it. At the moment the program just makes a blank white canvas. I feel like part of the issue is that the buffer is just passing the frame with the rectangle faster than I can see, but there is no frame to load after that so I don't know why it's doing this.

A: A BufferStrategy has a number of initial requirements which must be meet before it can be rendered to. Also, because of the nature of how it works, you might need to repeat a paint phases a number of times before it's actually accepted by the hardware layer.
I recommend going through the JavaDocs and tutorial, they provide invaluable examples into how you're suppose to use a BufferStrategy
The following example uses a Canvas as the base component and sets up a rendering loop within a custom Thread.  It's very basic, but shows the basic concepts you'd need to implement...
import java.awt.Canvas;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.image.BufferStrategy;
import java.util.concurrent.atomic.AtomicBoolean;
import javax.swing.JFrame;
import javax.swing.SwingUtilities;

public class Test {

    public static void main(String[] args) {
        new Test();
    }

    public Test() {
        SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
                TestCanvas canvas = new TestCanvas();

                JFrame frame = new JFrame();
                frame.add(canvas);
                frame.setTitle("Test");
                frame.pack();
                frame.setLocationRelativeTo(null);
                frame.setVisible(true);

                canvas.start();
            }
        });
    }

    public class TestCanvas extends Canvas {

        private Thread thread;
        private AtomicBoolean keepRendering = new AtomicBoolean(true);

        @Override
        public Dimension getPreferredSize() {
            return new Dimension(200, 200);
        }

        public void stop() {
            if (thread != null) {
                keepRendering.set(false);
                try {
                    thread.join();
                } catch (InterruptedException ex) {
                    ex.printStackTrace();
                }
            }
        }

        public void start() {
            if (thread != null) {
                stop();
            }

            keepRendering.set(true);
            thread = new Thread(new Runnable() {
                @Override
                public void run() {

                    createBufferStrategy(3);

                    do {
                        BufferStrategy bs = getBufferStrategy();
                        while (bs == null) {
                            System.out.println("get buffer");
                            bs = getBufferStrategy();
                        }
                        do {
                            // The following loop ensures that the contents of the drawing buffer
                            // are consistent in case the underlying surface was recreated
                            do {
                                // Get a new graphics context every time through the loop
                                // to make sure the strategy is validated
                                System.out.println("draw");
                                Graphics graphics = bs.getDrawGraphics();

                                // Render to graphics
                                // ...
                                graphics.setColor(Color.RED);
                                graphics.fillRect(0, 0, 100, 100);
                                // Dispose the graphics
                                graphics.dispose();

                                // Repeat the rendering if the drawing buffer contents
                                // were restored
                            } while (bs.contentsRestored());

                            System.out.println("show");
                            // Display the buffer
                            bs.show();

                            // Repeat the rendering if the drawing buffer was lost
                        } while (bs.contentsLost());
                        System.out.println("done");
                        try {
                            Thread.sleep(100);
                        } catch (InterruptedException ex) {
                            ex.printStackTrace();
                        }
                    } while (keepRendering.get());
                }
            });
            thread.start();
        }

    }

}

Remember, the point of BufferStrategy is to give you full control over the painting process, so it works outside the normal painting process generally implemented by AWT and Swing
"At a later date the canvas will be updating many times a second so I am using a buffer strategy for this" - Before going down the "direct to hardware" solution, I'd consider using a Swing Timer and the normal painting process to see how well it works


Q: Async Loop seems to partially parallel I'm trying to implement a function, which slices a file into chunks and then sends them to my backend one after another.
The function has to hash each file & validate if the hash is already known before starting the upload.
The following code is the code part, where my problematic function is called.
        process: async (
          fieldName,
          file,
          metadata,
          load,
          error,
          progress,
          abort,
          transfer,
          options,
        ) => {
          // fieldName is the name of the input field - No direct relevance for us
          // logger.log(`fieldName: ${fieldName}`);

          // Usually Empty - Can be added with Metadata-Plugin
          // logger.log(metadata);

          const source = this.$axios.CancelToken.source();

          const abortProcess = () => {
            // This function is entered if the user has tapped the cancel button
            source.cancel('Operation cancelled by user');

            // Let FilePond know the request has been cancelled
            abort();
          };

          let chunks = [];

          const {
            chunkForce,
            chunkRetryDelays,
            chunkServer,
            chunkSize,
            chunkTransferId,
            chunkUploads,
          } = options;

          // Needed Parameters of file
          const { name, size } = file;

          if (chunkTransferId) {
            /** Here we handle what happens, when Retry-Button is pressed */
            logger.log(`Already defined: ${chunkTransferId}`);
            return { abortProcess };
          }

          this.hashFile(file)
            .then((hash) => {
              logger.log(`File Hashed: ${hash}`);
              if (hash.length === 0) {
                error('Hash not computable');
              }
              return hash;
            })
            .then((hash) => {
              logger.log(`Hash passed through: ${hash}`);
              return this.requestTransferId(file, hash, source.token)
                .then((transferId) => {
                  logger.log(`T-ID receieved: ${transferId}`);
                  return transferId;
                })
                .catch((err) => {
                  error(err);
                });
            })
            .then((transferId) => {
              transfer(transferId);
              logger.log(`T-ID passed through: ${transferId}`);

              // Split File into Chunks to prepare Upload
              chunks = this.splitIntoChunks(file, chunkSize);

              // Filter Chunks - Remove all those which have already been uploaded with success
              const filteredChunks = chunks.filter(
                (chunk) => chunk.status !== ChunkStatus.COMPLETE,
              );

              logger.log(filteredChunks);

              return this.uploadChunks(
                filteredChunks,
                { name, size, transferId },
                progress,
                error,
                source.token,
              ).then(() => transferId);
            })
            .then((transferId) => {
              // Now Everything should be uploaded -> Set Progress to 100% and make item appear finished
              progress(true, size, size);
              load(transferId);
              logger.log(transferId);
            })
            .catch((err) => error(err));

          return { abortProcess };
        },

uploadChunks is where the problem starts.
    async uploadChunks(chunks, options, progress, error, cancelToken) {
      const { name, size, transferId } = options;
      for (let index = 0; index < chunks.length; index += 1) {
        let offset = 0;
        const chunk = chunks[index];
        chunk.status = ChunkStatus.PROCESSING;
        // eslint-disable-next-line no-await-in-loop
        await this.uploadChunk(chunk.chunk, options, offset)
          .then(() => {
            chunk.status = ChunkStatus.COMPLETE;
            offset += chunk.chunk.size;
            progress(true, offset, size);
            logger.log(offset); // This is always chunk.chunk.size, instead of getting bigger
          })
          .catch((err) => {
            chunk.status = ChunkStatus.ERROR;
            error(err);
          });
      }
    },
    uploadChunk(fileChunk, options, offset) {
      const { name, size, transferId } = options;
      const apiURL = `${this.$config.api_url}/filepond/patch?id=${transferId}`;
      return this.$axios.$patch(apiURL, fileChunk, {
        headers: {
          'content-type': 'application/offset+octet-stream',
          'upload-name': name,
          'upload-length': size,
          'upload-offset': offset,
        },
      });
    },

As you can see uploadChunks takes an array of chunks, some options, two functions (progress & error) and a cancelToken (which I currently don't use, since I'm still stuck at this problem)
Each chunk in the array has the form of:
{
  status: 0, // Some Status indicating, if it's completed or not
  chunk: // binary data
}

The Function uploadChunks iterates over the chunk array and should in theory upload one chunk after another and always increment offset after each upload and then call progress. After this it should start the next iteration of the loop, where offset would be bigger than in the call before.
The calls themselves get executed one after another, but every call has the same offset and progress does not get repeatedly called. Instead my progress-bar locks until everything is uploaded and them jumps to 100%, due to the load-call in the first function right at the end.
So the upload itself works fine in the correct order, but all the code after the await this.uploadChunk... doesn't get called after each chunk and blocks somehow.

A: You are setting offset to 0 inside the loop. So offset is always 0. You should move this line:
let offset = 0;
before the for statement.


Q: Decoding an integer sequence I have an integer sequence that I am trying to replicate. The formula in the OEIS page is as follows:
$$
\sum_{n,k} T(n,k) \frac{x^n}{n!} y^k = 1+\log\left(\sum_0^\infty\left((1+y)^\binom{n}{2}\frac{x^n}{n!}\right)\right)
$$
I know what n and k in the formula are, however, I am not sure what $x$ and $y$ mean. What is $x$ and $y$?

A: This is a generating function.  (I believe OEIS should have marked it as such; many OEIS entries have indications "g.f." for "generating function", or "e.g.f." for "exponential generating function.)
What that means is that if the function on the right side of the equals sign is expanded in powers of $x$, then the coefficient of $x^n$ will be a polynomial in $y$, and the coefficient of $y^k$ in that polynomial will be $\frac{T(n,k)}{n!}$.  The sequence you want consists of the values of $T(n,k)$, so the coefficients in your expansion will have to be multiplied by $n!$.  (The $n!$ in the denominator makes this an exponential generating function, rather than simply a generating function.)


Q: A cycle $A$ homologous to another cycle $B$ is well disjoint with $B$? On Griffiths and Harris p.49, it says: Consider a standard torus $T$ and two $1$-cycles $A$ and $A'$, ... while a cycle homologous to $A$, for example $A'$, may be well disjoint from $A$.
I feel confused, because if $A,A'$ are homologous then $A-A'$ is a boundary of a $2$-chain, so $A,A'$ have to be connected (since the boundary of $\Delta^2$ is connected), then it's a contradiction from Griffiths and Harris. Where did I miss?

A: Here is some intuition, which can be formalized depending on what homology theory you are using specifically. Think of the following blue $1$ cycles, and think of the boundary of the pink $2$ cycle.


Q: Return Array from Function in Swift So im a bit new to swift and object-c as well and was wondering if someone could help me out a bit.
I'm used to creating usually a utils file where I have functions I use often in programming.
In this case im trying to call a function from another swift file and return an array of data.
For example in my mainViewController.swift im calling the function:
var Data = fbGraphCall()

In the Utils.swift file I have a function that Im trying to get it to return an array of data collected.
func fbGraphCall() -> Array<String>{

var fbData: [String] = [""]

if (FBSDKAccessToken.currentAccessToken() != nil){

    // get fb info
    var userProfileRequestParams = [ "fields" : "id, name, email, about, age_range, address, gender, timezone"]

    let userProfileRequest = FBSDKGraphRequest(graphPath: "me", parameters: userProfileRequestParams)

    let graphConnection = FBSDKGraphRequestConnection()

    graphConnection.addRequest(userProfileRequest, completionHandler: { (connection: FBSDKGraphRequestConnection!, result: AnyObject!, error: NSError!) -> Void in
        if(error != nil) {

            println(error)

        } else {

            // DEBUG
            println(result)

            let fbEmail = result.objectForKey("email") as! String

            // DEBUG
            println(fbEmail)

            fbData.append("\(fbEmail)")

            let fbID = result.objectForKey("id") as! String

            if(fbEmail != "") {
                PFUser.currentUser()?.username = fbEmail
                PFUser.currentUser()?.saveEventually(nil)
            }

            println("Email: \(fbEmail)")

            println("FBUserId: \(fbID)")

        }

    })

    graphConnection.start()
}

println(fbData)
return fbData
}

I can confirm that im getting the fbEmail and fbID back from facebook with my debug statements but as I said im still new on how to return data back.
Ideally I usually want an array back if its more than one value or the ability to get back data like Data.fbEmail, Data.fbID or an array maybe like ["email" : "email@gmail.com", "id" : "1324134124zadfa"]
When I hit the return statement its blank.. so not sure why the constants are not keeping values or passing values into my fbData array.. I'm trying fbData.append(fbEmail) for example ..
any thoughts on what might be wrong?

A: The graphConnection.addRequest is an asynchronous function and you are trying to synchronously return the array of strings back. This won't work because the graphConnection.addRequest is done in the background to avoid blocking the main thread. So instead of returning the data directly make a completion handler. Your function would then become this:
func fbGraphCall(completion: ([String]) -> Void, errorHandler errorHandler: ((NSError) -> Void)?) {
    if (FBSDKAccessToken.currentAccessToken() != nil) {
        // get fb info
        var userProfileRequestParams = [ "fields" : "id, name, email, about, age_range, address, gender, timezone"]

        let userProfileRequest = FBSDKGraphRequest(graphPath: "me", parameters: userProfileRequestParams)

        let graphConnection = FBSDKGraphRequestConnection()

        graphConnection.addRequest(userProfileRequest, completionHandler: { (connection: FBSDKGraphRequestConnection!, result: AnyObject!, error: NSError!) -> Void in
            if(error != nil) {
                println(error)
                errorHandler?(error!)
            } else {
                var fbData = [String]() // Notice how I removed the empty string you were putting in here.
                // DEBUG
                println(result)

                let fbEmail = result.objectForKey("email") as! String

                // DEBUG
                println(fbEmail)

                fbData.append("\(fbEmail)")

                let fbID = result.objectForKey("id") as! String

                if(fbEmail != "") {
                    PFUser.currentUser()?.username = fbEmail
                    PFUser.currentUser()?.saveEventually(nil)
                }

                println("Email: \(fbEmail)")

                println("FBUserId: \(fbID)")

                completion(fbData)
            }

        })

        graphConnection.start()
    }
}

I added the completion handler and the error handler blocks that get executed according to what's needed.
Now at the call site you can do something like this:
fbGraphCall( { println($0) // $0 refers to the array of Strings retrieved }, errorHandler:  { println($0) // TODO: Error handling  }) // Optionally you can pass `nil` for the error block too incase you don't want to do any error handling but this is not recommended.

Edit:
In order to use the variables you would do something like this at the call site
 fbGraphCall( { array in
      dispatch_async(dispatch_get_main_queue(), {  // Get the main queue because UI updates must always happen on the main queue.
             self.fbIDLabel.text = array.first // array is the array we received from the function so make sure you check the bounds and use the right index to get the right values.
             self.fbEmailLabel.text = array.last
      })
 }, errorHandler:  {
        println($0)
        // TODO: Error handling
  })


Q: RobotFramework - Handle 2 Browser tabs at the same time and test them I have this problem where i need to test a functionality of my web app with 2 tabs open and check if I update someting on tab 1 Tab 2 refreshes, I am trying to get this done using the Press key keyword.
I am targeting the body of and Using the Ascii number for CTRL+T to open a new tab, A new browser window opens rather than a New Tab i am using latests version of Chrome.
I have also tried to to use \\09  but that gives me the same result
Press Key  tag=body   \\20

Then i try to go back to the window using the  Select Window  MAIN Keyword but that doesn't work.
QUESTION: how can i open 2 tabs at the same time and test them using RobotFramework with SeleniumLibrary?

A: I think your test would be just as valid with two windows as it would with one window and two tabs.
You can call the open browser keyword multiple times, giving each window its own unique alias. You can then switch between them with the switch browser keyword and the appropriate alias.
Example
*** Settings ***
Library  SeleniumLibrary

Suite Teardown  close all browsers

*** Variables ***
${browser}  chrome

*** Test cases ***
Example using two windows
    open browser  http://www.example.com  ${browser}  alias=tab1
    open browser  http://www.w3c.org      ${browser}  alias=tab2

    switch browser  tab1
    location should be  http://www.example.com/

    switch browser  tab2
    location should be  https://www.w3.org/


Q: How to create CosmosDB User Defined Function programmatically I know how to create CosmosDB databases and collection using ARM templates. I have a UDF (User Defined Function) that I would like to deploy using an ARM template as well but it doesn't seem to be supported.
Am I missing something? Is there a different way to programmatically deploy/maintain a UDF?

A: You could consider using Cosmos Db sdk or REST API to deploy udf into your collection.
sample code:
string udfId = "Tax";
var udfTax = new UserDefinedFunction
{
    Id = udfId,
    Body = {...your udf function body},
};

Uri containerUri = UriFactory.CreateDocumentCollectionUri("myDatabase", "myContainer");
await client.CreateUserDefinedFunctionAsync(containerUri, udfTax);

A: Simple answer No, Stored procedures and User Defined Functions are not supported via Azure Resource Management Templates as of today.

A: This is now possible..
"type": "Microsoft.DocumentDB/databaseAccounts/sqlDatabases/containers/userDefinedFunctions",
"apiVersion": "2019-08-01",

https://learn.microsoft.com/en-us/azure/templates/microsoft.documentdb/2019-08-01/databaseaccounts/sqldatabases/containers/userdefinedfunctions


Q: Roslyn Refactor Find References to a method As part of a refactor project I am working on I need to replace calls to Obsolete methods with correct calls.  This has worked for other calls but I have hit a problem with my current one.
I need to replace all calls to the following:
[Obsolete("use string.IsNullOrWhiteSpace instead of this extension")]
public static bool IsNullOrWhiteSpace(this string s)
{
    return string.IsNullOrWhiteSpace(s);
}

with the simple string.IsNullOrWhiteSpace(string here) from the framework.  When run it did work in that it fixed all the instances that it found.  What I can't account for is the 200+ instances that it did not identify.
Here are two examples that it did not find, this one is from the same class.
public static string TrimToUpper(this string s)
{
    return !IsNullOrWhiteSpace(s) ? s.Trim().ToUpperInvariant() : s;
}

I thought perhaps because the method was called directly, but that doesn't make sense to me as far as finding the reference.  A second example is simple if in another class in a project in the same solution if (enterpriseCode.IsNullOrWhiteSpace()) The first past detected several other instances just like it but not this one.
Here is the code I am using to find all the references to the method I wish to replace:
public sealed class ReferenceFinder
{
    public ReferenceFinder(string solutionPath)
    {
        SolutionInfo = GetSolutionInfo(solutionPath).GetAwaiter().GetResult();
    }
    public ReferenceTree RetreiveSolutionReferences(string typeName, string methodName)
        => new ReferenceTree(typeName, methodName, GetReferenceLocationsByProject(GetReferenceSymbols(GetTypeSymbols(typeName), methodName)));
    private IEnumerable<INamedTypeSymbol> GetTypeSymbols(string typeName)
        => SolutionInfo.ProjectInfo.Select(pi => pi.Compilation.GetTypeByMetadataName(typeName)).Where(x => x != null);
    private IEnumerable<ReferencedSymbol> FindConstructorReferences(INamedTypeSymbol symbol)
        => symbol.Constructors.SelectMany(c => SymbolFinder.FindReferencesAsync(c, SolutionInfo.Solution).Result);
    private IEnumerable<ReferencedSymbol> FindMethodReferences(INamedTypeSymbol symbol, string methodName)
        => symbol.GetMembers(methodName).SelectMany(m => SymbolFinder.FindReferencesAsync(m, SolutionInfo.Solution).Result);
    private IEnumerable<ReferencedSymbol> GetReferenceSymbols(IEnumerable<INamedTypeSymbol> symbols, string methodName)
        => symbols.SelectMany(x => x.Name == methodName ? FindConstructorReferences(x) : FindMethodReferences(x, methodName));
    private ILookup<Project, ReferenceLocation> GetReferenceLocationsByProject(IEnumerable<ReferencedSymbol> symbols)
        => symbols.SelectMany(x => x.Locations).Distinct().ToLookup(x => x.Document.Project);
    private async Task<SolutionInfo> GetSolutionInfo(string path)
    {
        using (var workspace = MSBuildWorkspace.Create())
        {
            var solution = await workspace.OpenSolutionAsync(path);
            var compilations = await Task.WhenAll(solution.Projects.Select(async x => (x, await x.GetCompilationAsync())).AsEnumerable());
            return new SolutionInfo((solution, compilations));
        }
    }

    public readonly SolutionInfo SolutionInfo;
}

I am passing the RetreiveSolutionReferencs the following "DVWorkshop.StringExtensions" (the class and namespace of the method to replace) "IsNullOrWhiteSpace" (the method to replace).
I even wrote a short method to try step through and see what references were being picked up.
        public void GetReferencesForSpecificProject(string typeName, string methodName, string projectName)
    {
        var pi = SolutionInfo.ProjectInfo.First(x => x.Project.Name == projectName);
        var symbol = pi.Compilation.GetTypeByMetadataName(typeName);

        var members = symbol.GetMembers(methodName).ToList();
        var rList = new List<IEnumerable<ReferenceLocation>>();
        var cList = new List<IEnumerable<Location>>();
        foreach (var m in members)
        {
            var referenceLocations = SymbolFinder.FindReferencesAsync(m, SolutionInfo.Solution).Result.SelectMany(r => r.Locations);
            var callerLocations = SymbolFinder.FindCallersAsync(m, SolutionInfo.Solution).Result.SelectMany(r => r.Locations);

            rList.Add(referenceLocations);
            cList.Add(callerLocations);
        }
    }

I see several locations in the reference and callers collections, but not nearly enough and none of them are for the project I'm passing in "Application" even though I see the calls and go to definition takes me to my method.
What is causing me to miss references to my method?


Q: Python Scripts is not running after working C Project and VSCode IntelliSense is on Partial Partial Mode So I was just done editing my C project in VS Code, and I went to work back on my Python project in VS Code, but now Python scripts is not working or running anymore or even showing anything on the output window on VS Code (as shown in the figure below). I keep pressing Run & Run Python File in Terminal but everything remains exactly the same with no output.
I could see that the IntelliSense is mentioning that it's on Partial Mode which it was not the case before working on the C project.
I reset my settings.json file to reset everything as it was before but an it doesn't work. Even uninstall and install VS Code again was not helpful and Python script is still not working.
I have the "Python" extension installed (the one made by Microsoft).
Any recommendation or advice would be highly appreciated.

A: Partial Mode is relatively rare. According to the content you provide, I think it may be caused by the following reasons:
The project is currently loading. Once loading completes, you will start getting project-wide IntelliSense for it. In these cases, VS Code's IntelliSense will operate in partial mode. Partial mode tries its best to provide IntelliSense for any Python files you have open, but is limited and is not able to offer any cross-file IntelliSense features.
I think you could spend more time waiting for vscode to load. Of course, if it still doesn't work, you could reinstall the python extension.


Q: Sounds using audio in my simple javascript game won't play The following is an excerpt from my little game (which all works apart from the sound, no errors in Chrome either, console.log proves code is run)???
<!DOCTYPE html>
<html>
<head>
    <title> Final Game Code + HS RA</title>
</head>
<body>
<script>

var myAudio = new Audio();
myAudio.source = "Sounds/Impact_1.mp3";
myAudio.volume = 1;

// a bunch of code for the game that all works goes here including a function that calls the below...

nanonautTouchedARobot = true;
myAudio.load();
myAudio.play();  // play the sound #############################################
// below line is just test code to prove progress on the console
console.log('OUCH!');

// a bit more code for the game that all works goes here...

</script>
</body>
</html>

A: myAudio.source = "Sounds/Impact_1.mp3";

This is incorrect.  You want the src property:
myAudio.src = 'Sounds/Impact_1.mp3';

Additionally, you don't need .load() before .play() like that.  And, ensure that you're calling .play() on a user action so that you don't run afoul of autoplay policies.


Q: Unable to create scheduled event using AWS SAM I have a SAM template.yaml like below:
AWSTemplateFormatVersion: '2010-09-09'
Transform: 'AWS::Serverless-2016-10-31'

Resources:
  GathererFunction:
    Type: 'AWS::Serverless::Function'
    Properties:
      Handler: main.handler
      Runtime: nodejs14.x
      Events:
        GathererDataSchedule:
          Type: Schedule
          Properties:
            Schedule: 'rate(1 minute)'
  GathererBucket:
    Type: AWS::S3::Bucket
    Properties:
      BucketName: gatherer-bucket

I run sam validate and it comes back fine.
I try to run sam deploy and the deployment fails when creating the schedule. Error says:
ScheduleExpression is not valid. (Service: AmazonCloudWatchEvents; Status Code: 400; error code: ValidationException;
I've also tried Schedule: rate('1 minute') and Schedule: rate(1 minute)
Where am I going wrong?

A: For me this template is deploying fine using the SAM cli.

May you try to update your SAM cli? And also check if you have permissions to create Eventbridge events?


Q: Set values to an object of type NSObject after adding it to an NSMutableArray I created a class named as Tutoral which is a sub class of NSObject, and it has following synthesized properties Title and Url.Then in my viewcontroller I created an instance of the Tutorial class.I also Created an NSMutableArray object and initialised. I added my tutorial object instance to the array. Then I set the properties such as Title = "mytitle" and Url = "myurl". In another place I fetched the tutorial object instance from the array and NSLog its Title and Url property values.It shows "mytitle" and "myurl" respectively.
My confusion is that why tutorial object instance which is inside the arry shows its property values. The tutorial object properties are set after that object is added to the array. Follwing are my tested code.
NSMutableArray *newTutorials = [[NSMutableArray alloc] initWithCapacity:0];

Tutorial *tutorial = [[Tutorial alloc] init];

[newTutorials addObject:tutorial];

tutorial.title = @"mytitle";

tutorial.url = @"myurl";

Tutorial *objNew = [newTutorials objectAtIndex:0];

NSLog(@"Title %@",objNew.title);

NSLog(@"Url %@",objNew.url);

A: When you add an object to an array, the array just keeps a reference to that object (a pointer). It doesn't create a copy of that object.
So, in the code example above, you're always dealing with the same instance of Tutorial:

*

*First, you create a new Tutorial with alloc and init, and store a reference to it with the tutorial pointer.

*Then you add it to your array. Your array retains the object, which means it keeps a reference to it.

*Then you set the title and url properties of your existing object.

*Then you grab another reference to the same object, and call it objNew. You get this reference by asking the array for a pointer to its first object.

*You then print the properties of the object.

A: When the following line of code executed,
[newTutorials addObject:tutorial];

What it does is , it add the address (reference) of tutorial object which you created in the previous line to the array newTutorials.
Your confusion is this : " You haven't set the values for the tutorial object inside the array but why is it displaying mytitle and myurl when you NSLoged the propeties of tutorials?" The answer is simple "You've not stored the tutorial object inside the array but you have stored a reference to the tutorial object"
Since when you've stored the reference and you've done the following to tutorial object :
tutorial.title = @"mytitle";

tutorial.url = @"myurl";

When you try to print the properties of the reference stored in the array, it prints mytitle and myurl because that is what you've assigned to the actual object's properties.


Q: Gradle Android plugin generate R files for different product flavors? I am trying to merge my free app and paid app.  The productFlavors of Android's new build system seem to be a perfect fit for my problem.
I have the freeApp flavor working great, however when I build the paidApp flavor the R file that is being generated is in a package structure that is defined in the freeApp.
Here is a snippet from by gradle.build file:
productFlavors {
freeApp {
    versionCode 201308020
    versionName "2.0.13_free"
    packageName "com.flyingspheres.android"
}
paidApp {
    versionCode 201305110
    versionName "2.0.10_paid"
    packageName "com.flyingspheres.android.inventory"
}

I always believed the R file's location is defined by the package name in the manifest.  I verified that the manifest file is generating correctly.
The problem is that the R file for both flavors is located in the same location.  Gradle demands that a manifest lives within the main source tree so whatever version of the manifest I put in the main source tree that is where the R.java file will be generated at.
Assuming that I get the R files to generate in the correct location for each flavor; how are the import statements for the R file supposed to be managed so that each flavor references the correct R file?
Here is a screen shot of my project structure:

Each AndroidManifest.xml file is a full and complete manifest - according to the documentation the manifest in the main tree should completely overwrite the product flavor version.  Although, that is clearly not happening, because the activity that should be launched and the content providers aren't being overwritten.
Any insights to what I'm doing wrong would be most appreciated.  This has to be a very common situation that anyone overriding the packageName would run into.  I've been trying to figure it out for about a week now and can't seem to get there on my own.
Thanks,
-Aaron

A: Under android's gradle plugin 0.7.3, the generated R.java file is only made for the src/main's package name. It contains all the resources for the different flavors, it just puts them into one generated R.java file. I heard this from an IO talk.
What's your package name in the src/main/AndroidManifest.xml? My guess is that it's com.flyingspheres.android
Try importing R in your classes which need to access resources programatically using your src/main's package name.
E.g.
import com.flyingspheres.android.R;


Q: Best website for Programming Language Icons I was wondering to find icon packs for all programming language icons. Can anyone suggest which one is good website where I can find all icons (Either official or based on some similar theme) related to any programming language.

A: Well after lots of surfing I found a good webpage for programming language icons.
Programming Language Icons. Thank you guys!

A: I use FontAwesome for all types of icons.
There are various websites another is Flaticon

A: There is Devicon a set of icons representing programming languages, designing, and development tools. You can use it as a font or directly copy/paste the SVG code into your project.


Q: Using SUMIF with INDIRECT Values are in another sheet which is named as cell value"A3"
=SUMIF(INDIRECT(" ' "&A3&" '$B:$B"),D$2,INDIRECT(" ' "&A3&" '!$M:$M"))

do you see anything wrong with this formula ?
doesn't work #REF! is the response.

A: By enclosing A3 in ampersands you are referencing cell A3 in the current sheet. What you want is:
=SUMIF(INDIRECT("'A3'!$B:$B"),D$2,INDIRECT("'A3'!$M:$M"))

On second look, if you are intending to reference a sheet that is named what you have in cell A3 then you don't need the apostrophes around the cell reference:
=SUMIF(INDIRECT(A3&"!$B:$B"),D$2,INDIRECT(A3&"!$M:$M"))


Q: How to find-and-replace text with regular expression I have multiple lines like this(with multiple random numbers):
value:"200 text.text.text.text
value:"235437 text.text.11.text
value:"12835 text.text.17.text
value:"347783 text.text.text.text

I want to remove everything before the space text.text.text.text
To look like this(i want to remove the space too):
text.text.text.text
text.text.11.text
text.text.17.text
text.text.text.text

A: In your case there are a couple of easy solutions. This first solution uses only basic regex:
[\.\w]+$
This captures every word character \w or period \. from the end $, stopping when it reaches any other type of character. This works because the space is not a word character or a period.
If you would like to select the region you want to remove, you can just use:
.*
Read this as match every character .* until the last space  . The reason this matches until the last space, is because the star is a greedy quantifier. This means it matches everything it can, then starts giving back characters as needed for the rest of the pattern to match. To match until the first space, use .*? . The question mark next to the star makes the star lazy. This means the star will match as little as it has to in order for the next part of the expression to find a match.
However, capture groups are ideal for problems like this, where you would like to remove part of a line and keep the rest. A simple formula for this is:
^(.*)pattern_to_remove(.*)$
You can then recover the rest using backreferences. These store the capture groups (anything in parenthesis) from you regex into preset variables. In the pattern above, this would be \1\2 or $1$2 depending on the language you are using. This brings me to probably the easiest answer to your problem:
 (.*)
The first capture group contains everything after the space. This regex is very straightforward and easy to read. Move to the first space  , then capture everything after (.*).
For a comprehensive reference on regex, check out regular-expressions.info. Here is a link to the page on capture groups.

A: *

*Ctrl+H

*Find what: ^\S+\h+

*Replace with: LEAVE EMPTY

*CHECK Wrap around

*CHECK Regular expression

*Replace all
Explanation:
^         # beginning of line
  \S+       # 1 or more non spaces
  \h+       # 1 or more horizontal spaces

Screenshot (before):

Screenshot (after):


Q: installation path for sqlite database I am trying to access a database using python. The src folder is:
ptbl/
├── dialogue.py
├── elem_H.py
├── elems.db
├── __init__.py
├── __main__.py
├── main.py
├── menubar.ui
└── menu.py

with elem_H.py access elems.db database as:
sqlfile = "elems.db"
conn = sqlite3.connect(sqlfile)

Ofcourse, when I am running it from terminal, inside src dir(ptbl), everything works fine.
But, when I am outside the src dir,its giving error:
sqlite3.OperationalError: no such table: Overview

and same, if I install it using autotools.
For elems.db to be worked,I have to run it from a folder where elems.db is present.
How can I make it installed in a path?

A: Mixing python and SQLite files in one single directory is not a good pratice at all. You should fix it and extract elems.db from your libraries directory.
Moreover, as Lutz Horn said in comments, you should make it configurable and not trust that your database file will be always located in the exact same place.
But anyway, to fix your issue without updating these two points, you have to take care of the elem_H.py location. You know elems.db is next to it, so you can do:
import os.path
sqlfile = os.path.join(os.path.dirname(__file__), "elems.db")

*

*__file__ store the relative path to your file from the place where you run command.

*os.path.dirname remove the filename from the given path.

*os.path.join will concat the computed path and your filename.


Q: Django - Can I create a global variable that can be accessed/manipulated from different functions in different files? I'm trying to figure out a way I can avoid passing so many arguments to functions in my app. I'm using different databases for each table, so joining is not possible, so I need to create a primary key dictionary that has the objects I need for subsequent functions. I do this to make only two queries.
My example is below. Please note how I have to pass in the people_ref reference dictionary to each deform function. What I would like to do is set some sort of global people_ref variable that can be accessed from anywhere. That way I could just dump the People.in_bulk() response to the global pool, and then access it directly from inside the deform functions without having to pass in the reference. Is there a way to do that?
What I want to call:
>>> myapp.models.make_crazy_books([1,2,3])

From myapp/models.py:
import itertools
from django.db import models
from myapp.utils import deform

class People(models.Model):
    born = model.DateField()

class Book(models.Model):
    author = models.ForeignKey(People, related_name='author_set')
    editor = models.ForeignKey(People, related_name='editor_set')
    last_edition = model.DateField()

def make_crazy_books(book_ids):
    book_list = Book.objects.using("db1").filter(id__in=book_ids) #Query here, db1

    people_list = ((b.author_id, b.editor_id) for b in book_list)
    people_ids = set(itertools.chain(*people_list))
    people_ref = People.objects.using("db2").in_bulk(people_ids) #Query here, db2

    #Would like to not have to send people_ref to each function
    book_list = deform.deform_edition(book_list, people_ref)
    book_list = deform.deform_author(book_list, people_ref)
    """ ... do some other deforming functions """

    return book_list

From mayapp/utils/deform.py:
def deform_edition(book_list, people_ref):
    for book in book_list:
        author = people_ref[book.author_id] #Change to global lookup?
        b.last_edition = author.born
    return book_list

def deform_author(book_list, people_ref):
    for book in book_list:
        editor = people_ref[book.editor_id] #Change to global lookup?
        b.author = editor
    return book_list

I would try using Django's caching functionality, but with multiple threads running, the cached reference dictionary can be read/overwritten by other simultaneous requests.
EDIT: Perhaps local-memory caching would work since it's thread safe?

A: Generally, sharing data between a group of related functions is what OOP is for - define a class that contains the functions (as methods), then instantiate the class with the particular data.
In this case though there is a class already associated with the data - it's a QuerySet of People objects. So you could define a custom QuerySet subclass for People that contains the deform methods - unfortunately in Django to get that to work you also need to define a custom Manager, overriding get_query_set to return your QuerySet subclass.


Q: Procedure running slow in first attempt after migration SQLSERVER 2005 to 2012 Recently we have migrated SQLServer 2005 to 2012 and seen huge slowness in stored procedures execution.it's taking long time in first attempt but as on expected time in second attempt. I was under impression this may be due to caching but I have used "dbcc freeproccache" but When I'm executing all procedures again they are taking expected time, I don't have seen any performance issue on first attempt to nth times after executing "dbcc freeproccache". To improve the performance
I already did following things which are not working for me.

*

*Rebuild the indexes.

*Updated historic stats using 100% sampling data.


Q: Issue with bootstrap sub-menu hovering I am currently using a sub-menu implementation in twitter bootstrap. The lines of code are as follows -

  Edit

  Send

Javascript code: -
var subList = "

 Send Mail

 Notify

";
    $(".sendSettings").hover(function(e) {
            console.log("hello world");
            $('.sublist-remove').remove();
            e.stopPropagation();
            $(this).parent().append(subList);
        });

But when I am trying to hover on the submenu section, I can find the main dropdown element is being hovered on and hence its giving a flickering effect. And I am not able to click on the sub-menu.
Please help with the issue as in where have I gone wrong?

A: I suppose you are using Bootstrap 2? Submenus are removed in Bootstrap 3. An example of working submenus in Bootstrap 3 can be found at http://www.bootply.com/86684


Q: Changing result from line 2 to line 1 I have a vb.net application that is made to acquire a result  from a webpage to my alertbox.
The webpage's result however is on the second line and is spaced.
I can only see half the text which is inside the alertbox since it's on line 2.
How do i change it so that the result goes to line 1?
The webpage result is like this:
1
2                       Success: 127.0.0.1 works

However I want it to show up on my alertbox like this:
1 Success: 127.0.0.1 works

I've fixed the spacing so far, but I can't fix the lines.
Here's the code:
Dim Website2 As New WebClient
    Dim WebsiteIW As String = Website2.DownloadString("http://webpage.com/" + FlatTextBox1.Text)
    If WebsiteIW.Length > 37 Then WebsiteIW = WebsiteIW.Substring(0, 37)
    While WebsiteIW.Contains("                      ")
        WebsiteIW = WebsiteIW.Replace("                     ", "")
    End While
    FlatAlertBox1.Text = WebsiteIW

A: Instead of
While WebsiteIW.Contains("                      ")
  WebsiteIW = WebsiteIW.Replace("                     ", "")
End While

Use
WebsiteIW = WebsiteIW.trim

It's a lot faster, and will get rid of an stray newline characters.


Q: Intuition behind quantum CNOT gate applied to a pair of electrons I'm looking for some intuition behind how a cNOT gate works.  I think I understand the mathematics; but, I'm having trouble imagining how two electrons would interact to produce the predicted result.
If I understand correctly, the input to a cNOT gate is two unentangled electrons. I picture these as two Bloch spheres with vectors pointing in arbitrary directions.
To implement a cNOT gate, we would (1) bring these two electrons close enough to become entangled, (2) prevent electron x from rotating in the z direction (thereby preserving its state in that direction), and (3) allow electron y to rotate (which changes the probably of measuring it in the up state with respect to the z axis).
My understanding is that entanglement is a result of electrons rotating to align their spin axes into a lower energy state.  If that's the case, why is electron y affected more when electron x's axis is pointed up than when it's pointed down?   It would make sense if the effect was symmetric (large when the angle is close to either 0 or $\pi$, and small when it is close to $\frac{\pi}{2}$), but given that y can be oriented either up or down, I don't see how the effect of x can be small with oriented up and large when oriented down.
This post addresses the implementation of cNOT, but from a perspective that seems more mathematical than intuitive. How is CNOT operation realized physically?
This video gives the type of answer I was looking for: https://youtu.be/EjdIMBOWCWo?t=30 (I would have added this as the answer; but, I can't while the post is marked as a duplicate.)


Q: Get x left ,x right ,y top, y bottom from pdf.js we are using pdf.js
in order to drag drop image inside pdf and I want send coordinate to Aspose.PDF how i can get x left ,x right ,y top, y bottom instead of only (x,y)
  var pdfY = maxPDFy - param.posizioneY - offsetY;
        y = (pdfY * maxHTMLy) / maxPDFy;
        x = ((param.posizioneX * maxHTMLx) / maxPDFx) + paramContainerWidth;

https://codepen.io/ValerioEmanuele/pen/pGRZqe


Q: imageStore() operation on dimensions beyond buffer size I have compute shader in which I have uimage2d buffer and imageStore() operations on that buffer. I want to know what would be behaviour if i write to locations beyond the size of buffer. Would be there some wrap effect ? Or behaviour depends on driver ? Or will it undefined and anything can happen?

A: According to the specification, an access to a texel which doesn't exist has no effect.
See OpenGL 4.6 API Core Profile Specification - 8.26. TEXTURE IMAGE LOADS AND STORES; page 193:

If the individual texel identified for an image load, store, or atomic operation doesn’t exist, the access is treated as invalid. Invalid image loads will return zero.
  Invalid image stores will have no effect. Invalid image atomics will not update any texture bound to the image unit and will return zero. An access is considered invalid if:
[...]

*

*the selected texel doesn’t exist


Q: Loop the included array currently im building a filter and in this filter there is an array with dynamic values.
Im just one step away from finishing it but i dont get the right loop done. I already tried it with something like forEach but all the ways i tried it didnt work. Here is the code:

map(p => (!this.personTypeFilter) ? p:p.filter(((i:any) => this.getPersonTypesBezeichnung(i.personentyp)?.toLowerCase().includes(this.personTypeFilter.forEach((x:any) => { return console.log(this.personTypeFilter[x])))))

This way makes my code to explode
So the filter need to include all values step by step with a for loop or something like that
//EDIT
The goal of this situation is to filter a whole array for Example you have multiple checkboxes which will be pushed to an list after clicking the single checkboxes. Now i want to filter every single value of this list, so i thought about looping it with forEach. The correction solution instead was map.

A: Instead of a complex for loop or forEach you can just use a simple map.
Just handle it similiar to a for loop, the map will go for all your elements in your array like below.

map(p => (!this.personTypeFilter.map((x:any) => x)) ? p:p.filter(((i:any) => this.getPersonTypesBezeichnung(i.personentyp).includes(this.personTypeFilter.map((x:any) => x).join(', '))))),


Q: Does hapijs have something like overload protection? What will a hapi server do if it is overloaded and is there something like toobusy-js to prevent a fallout of the server by shortcutting some requests with errors.

A: Yes it's embedded in the framework, look at load on connections settings.
You have 3 options :

*

*maxHeapUsedBytes - maximum V8 heap size over which incoming requests are rejected with an HTTP Server Timeout (503) response. Defaults to 0 (no limit).

*maxRssBytes - maximum process RSS size over which incoming requests are rejected with an HTTP Server Timeout (503) response. Defaults to 0 (no limit).

*maxEventLoopDelay - maximum event loop delay duration in milliseconds over which incoming requests are rejected with an HTTP Server Timeout (503) response. Defaults to 0 (no limit).
`

And you must not forget to set a sample interval (time between 2 checks) on server.load config:

*

*sampleInterval - the frequency of sampling in milliseconds. Defaults to 0 (no sampling).

Example :
server configuration :
{
  "load": {
    "sampleInterval": 1000
  }
}

connection configuration :
{
  "load": {
    "maxHeapUsedBytes": 1073741824,
    "maxRssBytes": 1610612736,
    "maxEventLoopDelay": 5000
  }
}


Q: How do I remove or alter spaces between images in an inline heading in CSS? Here is my code. I haven't finished formatting anything under the heading yet. But I'm trying to get the h2(the one with images) centered and without spaces. I've tried messing with font spaces in parent and removing padding but nothing seems to be working. I only want to do this in CSS.
Code:

body {
  background-color: blue;
}
div {
  background-color: white;
  padding: 25px;
}
h1 {
  text-align: center;
}
h2 img {
  display: inline;
  height: 100px;
  margin-left: 100px;
}

        Float, Float, Float!

A: It seems like a minor tweak will get what you want.
First, there's space between the images because you put spaces between the images. Any whitespace between the HTML elements will be rendered as a space, so remove the line breaks:

Second, add h2 to the style that centers, and remove the left margin on h2:
h1, h2 {
    text-align: center;
}

h2 img {
    display: inline;
    height: 100px;
    //margin-left:100px;
}

That's all that's needed.

A: Maybe use:
  h2 img {
    display: inline-block;
    float: left;
    height: 100px;
    margin-left:100px;
  }


Q: Make Dialog in landscape or portrait orintation Hy,
i have got some trooubles in my dialog. If i want to use it on portrait orientation it behaves ok, but if its in landscape orinetation o can use only 4 seekbars.

A: Wrap your entire layout in a <ScrollView>, it just gets truncated because the screen isn't 'high' enough. If you layout would be bigger in height, the first screen would be cut off too.


Q: Merge [htmlhelpers], [html-helper] into [htmlhelper] The current distribution is the following one:

*

*htmlhelper (472)

*htmlhelpers (63)

*html-helper (56)

*html-helpers (0)

I have not enough reputation to propose a synonym (silly requirement, isn't it?), so please merge.

A: Good idea -- I decided to merge into html-helper in this case. We can pluralize later to taste.


Q: N * N matrix by Java This is what I written:
import javax.swing.JOptionPane;

public class JavaTest{
    public static void main(String[] args){
    String numberString = JOptionPane.showInputDialog(null, "Enter number here: ",
            null, JOptionPane.INFORMATION_MESSAGE);
        int number = Integer.parseInt(numberString);
        printMatrix(number);
    }

public static void printMatrix(int n){
    int[][] myList = new int[n][n];
    String output = "";

    for (int row = 1; row <= n; row++){
        for (int col = 1; col <= n; col++){
            myList[row][col] = (int) (Math.random() * 2);
        }
    }
    for (int row = 1; row <= n; row++){
        for (int col = 1; col <= n; col++){
            if (col == n){
                output += "\n" + myList[row][col];
            }
            else{
                output += myList[row][col] + " ";
            }
        }
    }

    if (n < 0){
        JOptionPane.showMessageDialog(null,
                "Invalid input!");
    }
    else{
        JOptionPane.showMessageDialog(null,
                output);
    }
    }
}

I run it and enter 3 in a dialog box, and the eclipse IDE shows that
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 3
    at JavaTest.printMatrix(JavaTest.java:17)
    at JavaTest.main(JavaTest.java:8)

I guess at line 17 and 8 the program goes wrong but I don't know how to improve it.
What can I do to improve my code? Thanks!

A: You're looping from 1 to n:
for (int row = 1; row <= n; row++){
    for (int col = 1; col <= n; col++){

Indexes begin at 0, not at 1.  The loops should be from 0 to n-1:
for (int row = 0; row < n; row++){
    for (int col = 0; col < n; col++){

(This same error may likely be in other places than just the first line that threw the exception.)


Q: win32 main loop interval issue C++ I'm making a keylogger that logs key strokes (duh..). Now when I've implemented the basic keylogger in C++, I wanted to add a new feature to the application: I want it to mail the logs to my email. So far so good, I found this open source email client that fits perfect for my needs. The only problem I have is to make the application send the logs in intervals of x minutes.
int main(int argc, char *argv[])
{
    //stealth();
    hHook = SetWindowsHookEx(WH_KEYBOARD_LL, MyLowLevelKeyBoardProc, NULL, 0);
    if(hHook == NULL)
    {
        cout << "Hook failed" << endl;
    }

    MSG message;
    while(GetMessage(&message, NULL, 0, 0))
    {
        TranslateMessage(&message);
        DispatchMessage(&message);
    }

    return 0;
}

Somehow I need to implement somekind of counter which will at some point use a function send();.
Anyone got any idea how to modify the MSG loop to execute the funktion send(); each and every 5 minutes?

A: Take a look at the SetTimer function, I think it does exactly what you need.
Before event loop you should call this function with desired interval and you have to pass to it a callback function. Alternatively you can use another function CreateTimerQueueTimer
VOID CALLBACK TimerProc(HWND hWnd, UINT nMsg, UINT nIDEvent, DWORD dwTime) {
}

UINT timer = SetTimer(NULL, 0, 500, &TimerProc);

MSG message;
while(GetMessage(&message, NULL, 0, 0))
{
    TranslateMessage(&message);
    DispatchMessage(&message);
}

KillTimer(NULL, timerId);

A: Make a new thread to sleep x milis and then send in a while(!interrupted) loop.
As you may know, accessing the same data for read and write from 2 separate threads simultaneously will cause an error.
http://msdn.microsoft.com/en-us/library/kdzttdcb(v=vs.80).aspx
To avoid that you can use critical section
http://msdn.microsoft.com/en-us/library/windows/desktop/ms686908(v=vs.85).aspx
Or just make your thread to sleep and turn a boolean value to true meaning 'yes we waited enough' and your main function always send data when that boolean is true then set it back to false.
edit:
I believe this is the simplier way to archieve this
while(!interrupted) { // Your thread will do this.
    sleep(60000);
    maysend = true;
}
[...]
if(maysend) { // Your main function will contain this
    send();
    maysend = false;
}


Q: Подскажите пожалуйста ,ошибка при циклическом сдвиге я попытался сделать

Все нечетные строки матрицы сдвинуть циклически на К элементов влево.

но получилось так что оно сдвигает вправо ,в чем моя ошибка ?Прошу прошения если мой вопрос оформлен не правильно ,но я новичок )
for(i=1;i<string;i+=2)
{
    for(shift=0;shift<K;shift++)
    {
        tmp=Matrix[i][column-1];
        for(j=column-1;j>0;j--)
        {
            Matrix[i][j]=Matrix[i][j-1];
        }
        Matrix[i][0]=tmp;
    }
}

A: Matrix[i][j - 1] = Matrix[i][j];

Соответствено, поправить диапазон значений счетчика и направление цикла.

ни как не могу понять что менять

tmp = Matrix[i][0];
for (j = 1; j < column; j++)
{
  Matrix[i][j - 1] = Matrix[i][j];
}
Matrix[i][column - 1] = tmp;