text:
Q: Google Discovery API The request is missing a valid API key We've been using the google discovery api for analytics setup to make the request: "https://analytics.googleapis.com/$discovery/rest?version=v4"
This has been working fine for over two years now, however just today it's started responding with:
googleapiclient.errors.HttpError: <HttpError 403 when requesting https://analytics.googleapis.com/$discovery/rest?version=v4 returned "The request is missing a valid API key.">

I cannot seem to find any status on this api but I feel as if something might have changed.
Manual testing has been performed and I've replicated the issue consistently.
>>> credentials = oauth2client.client.GoogleCredentials("<redacted>", "<redacted>", "<redacted>", "<redacted>", None, "https://accounts.google.com/o/oauth2/token", "UserAgentHere")

>>> credentials
<oauth2client.client.GoogleCredentials object at 0x7f533eaf60b8>

>>> import httplib2

>>> http = credentials.authorize(http=httplib2.Http())

>>> http
<httplib2.Http object at 0x7f533eaf6390>

>>> from apiclient.discovery import build

>>> build("analytics", "v4", http=http, cache_discovery=False)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/lib/python3.6/site-packages/googleapiclient/_helpers.py", line 130, in positional_wrapper
    return wrapped(*args, **kwargs)
  File "/usr/lib/python3.6/site-packages/googleapiclient/discovery.py", line 232, in build
    raise e
  File "/usr/lib/python3.6/site-packages/googleapiclient/discovery.py", line 224, in build
    requested_url, discovery_http, cache_discovery, cache, developerKey)
  File "/usr/lib/python3.6/site-packages/googleapiclient/discovery.py", line 277, in _retrieve_discovery_doc
    raise HttpError(resp, content, uri=actual_url)
googleapiclient.errors.HttpError: <HttpError 403 when requesting https://analytics.googleapis.com/$discovery/rest?version=v4 returned "The request is missing a valid API key.">
>>>

A: Try to change discoveryServiceUrl to
'https://analyticsreporting.googleapis.com/$discovery/rest?version=v4'
Example:
build("analytics", "v4", http=http, cache_discovery=False,
    discoveryServiceUrl='https://analyticsreporting.googleapis.com/$discovery/rest?version=v4'
)

but it only works for reporting, not for management api
Update:
You can also change service name from 'analytics' to 'analyticsreporting'.
build("analyticsreporting", "v4", http=http, cache_discovery=False,)

'analytics' service name was used for 'api version 3' and was the same for all scopes. If you're using a 'reporting core api v4', you should change the name to 'analyticsreporting'.

A: Whilst the answer from Andrey Avodov works, I believe it is more correct to replace 'analytics' with 'analyticsreporting'
i.e. replace
build("analytics", "v4", http=http, cache_discovery=False)

with
build("analyticsreporting", "v4", http=http, cache_discovery=False)

The 'analytics' version had been working for me for years, but stopped working this morning. Replacing it with the new code has fixed that.
This is as per the v4 quickstart guide https://developers.google.com/analytics/devguides/reporting/core/v4/quickstart/service-py
It also ties up with the discovery code which already has a discovery url in the correct format (so long as you pass analyticsreporting
V2_DISCOVERY_URI = ('https://{api}.googleapis.com/$discovery/rest?'
                    'version={apiVersion}')

...
snip
...

for discovery_url in (discoveryServiceUrl, V2_DISCOVERY_URI,):
    requested_url = uritemplate.expand(discovery_url, params)

from https://github.com/googleapis/google-api-python-client/blob/b854ff13c801b98f97ff3b9a2ddbd9af54724b9a/googleapiclient/discovery.py
I assume the analytics version has been deprecated / broken somehow, but given the quickstart uses the analyticsreporting version this feels like a safer / more complete change than updating the discovery url.


text:
Q: Cant add item to ListView C# Hello I have this code in C# to get the files and list them in ListView but nothing happens
string[] files = Directory.GetFiles("plugins/");
foreach (string file in files)
{
    string fileName = Path.GetFileNameWithoutExtension(file);
    ListViewItem item = new ListViewItem(fileName);
    item.Tag = file;
    listView1.Items.Clear();
    listView1.Items.Add(item);

}

I even tried to insert a different one with single line of code
listView1.Items.Clear();
listView1.Items.Add("item");

but it does not add the item
Thank You

A: ListViewItem.Tag is the only property you are setting and that property is not going to be visible in the UI.  Try this:
string[] files = Directory.GetFiles("plugins/");
            foreach (string file in files)
            {

                string fileName = Path.GetFileNameWithoutExtension(file);
                ListViewItem item = new ListViewItem(fileName);
                item.Text= file;
                listView1.Items.Add(item);

            }

A: This code in your foreach loop:
listView1.Items.Clear();

always clears the list view everytime the foreach statement is executed leaving you with only 1 item added in the view after the execution of the foreach statement.
I suggest removing that. If you need to need to clear it out, create a method that will clear the list and call the method somewhere, but should not definitely be in the foreach statement.
Your instantiation of the list view must not be in the foreach loop. You may instantiate it on the method level or in the class level so that your separate method that will clear the items in the list will be able to reference it.
class Program
{
    static ListView listView1 = new ListView();
    static void Main(string[] args)
    {
        string[] files = Directory.GetFiles("C:\\testfiles");

        foreach (string file in files)
        {

            string fileName = Path.GetFileNameWithoutExtension(file);
            ListViewItem item = new ListViewItem(fileName);
            item.Tag = file;
            listView1.Items.Add(item);

        }
    }

    static void ClearList()
    {
        listView1.Items.Clear();
    }
}

A: Try below code
        string[] files = Directory.GetFiles("plugins/");
        string fileName = "";
        foreach (string file in files)
        {
            fileName = Path.GetFileNameWithoutExtension(file)
            var item = new ListViewItem();
            item.Tag = file;
            item.Text = fileName;
            listView1.Items.Add(item);
        }

redpajama_set_name: RedPajamaStackExchange


text:
Q: mysql: do left join on certain table if column has value I have a few tables:  devices, acccessories and repairs.
Repairs has a field in it called: item_type and one called ref_id
item_type can have value of '1' meaning it's a device or '2' meaning it's an accessory.
If repairs.item_type = 1 I want to do a join on that table where repairs.ref_id = devices.id.
If repairs.item_type = 2 I want to do a join on that table where repairs.ref_id = acccessories.id.
I'm not sure how to do that.
SELECT *
FROM repairs
LEFT JOIN repairs.ref_id = (if repairs.item_type = 1 then devices.id; if repairs.item_type = 2 then accessories.id)

Is there a way to do this, or do I need to do a UNION ALL like:
SELECT *
FROM repairs
LEFT JOIN repairs.ref_id = devices.id
WHERE repairs.item_id = '1'

UNION ALL

SELECT *
FROM repairs
LEFT JOIN repairs.ref_id = accessories.id
WHERE repairs.item_id = '2'

A: join devices and accessories tables to repair table.
select t1.*
from repairs t1
left join devices t2 on t2.id =  t1.ref_id
left join accessories t3 on t3.id = t1.ref_id
and t1.item_type in (1, 2)


text:
Q: How to get actual value from HttpResponse in view? Views.py
def process_view(request):
    dspAction = {}
    try:
        google = google(objectId) #google = google(requst, objectId)
        if google['status'] == int(1):
            #some function
    except:
        dspAction['Google Status'] = "Google Action Completed"
    return HttpResponse(json.dumps(dspAction),content_type='application/json')

The above function is pretty basic and it's working very well with this google function:
def google(objectId):
    googelAction = {}
    google['status'] = 1
    return google

But for some reason I want request in google function. If I do this:
def google(request, objectId):
    googelAction = {}
    google['status'] = 1
    return HttpResponse(google)

and return a HttpResponse object, how can I get the status value ?

A: So what you are saying is you need to return two things (an HttpResponse and the status value) from your google function instead of just one thing.
In this case you should return a tuple, eg:
def google(request, objectId):
    google = {}
    google['status'] = 1
    response = HttpResponse(json.dumps(google))  # <-- should be string not dict
    return response, google

def process_view(request):
    dspAction = {}
    try:
        response, google = google(request, objectId)
        if google['status'] == int(1):
            #some function
    except:
        dspAction['Google Status'] = "Google Action Completed"
    return HttpResponse(json.dumps(dspAction),content_type='application/json')

A: return HttpResponse(google.status)
EDIT from comment:
To use the other attributes in the dictionary you need to pass the context variables, usually with render.
# view.py
from django.shortcuts import render
...
return render(request, "template.html", {'google':google})

# template.html
# you can then access the different attributes of the dict
{{ google }} {{ google.status }} {{ google.error }}


text:
Q: Soap version mismatch in magento I am new to SOAP. Below code works fine in my local environment, my php version is php-5.3.3 and soap client version 1_1.
`

    require_once "../app/Mage.php";
    Mage::app();
    $client = new SoapClient('https://mydomain/api/soap?wsdl&type=soap');
    $session_1 = $client->__getFunctions();
    echo '<pre>'; print_r($session_1);echo '</pre>';

    $session = $client->login('user', 'password');
    // If you don't need the session anymore
    $client->endSession($session);

`
When I try to execute this code in server(php-5.3.29 and soap client 1_1),
I am getting an error as following
` Fatal error: Uncaught SoapFault exception: [WSDL] SOAP-ERROR: Parsing WSDL: Couldn't load from ..`

Then we tried the code with some changes in server as
require_once "../app/Mage.php";
Mage::app();
$client = new SoapClient('http://mydomain/api/soap?wsdl&type=soap', Array(
                            'location' =>   'http://mydomain/api/soap?wsdl&type=soap',
                            'cache_wsdl' => WSDL_CACHE_NONE,
                            'soap_version' => SOAP_1_1));
                            var_dump($client);
$session = $client->login('user', 'password');

I got this  error
Fatal error: Uncaught SoapFault exception: [VersionMismatch] Wrong Version in ..
Also when we tried curl http://mydomain/api/soap?   wsdl&type=soap , it worked fine.
Can any one help on this?

A: Not really sure if this is a help to you, but as there's a difference in PHP versions between the local and server environments, I thought it might help.
There's a PHP bug that was fixed in 5.3.11 that caused me to get a Version Mismatch error when trying to connect to the Royal Mail Shipping API in OpenCart.
Here's details of the bug: https://bugs.php.net/bug.php?id=49853
Basically, the stream_context part of the http header is being ignored, and that contains the client ID and secret.
Contained within is a workaround:
ini_set('user_agent', 'PHP-SOAP/' . PHP_VERSION . "\r\n" . $str_auth_header);

where
$str_auth_header = "Authorization: Bearer ". $str_token;

$arr_context = array('http' =>array('header' => $str_auth_header));

$obj_context = stream_context_create($arr_context);


text:
Q: Cannot read property 'getAttribute' of null : Angular and d3.select I'm building a series of d3 graphs within angular 5. I'm graphing the same d3 multiple times with different data each time, so I'm assigning a variable to the id. The problem is, the id is assigned at the same time that 'd3.select()' is looking for it, therefore it hasn't been assigned yet and I get error Cannot read property 'getAttribute' of null
How can I assign the 'id' of my intended 'svg' a variable from the same data that I use to graph it? Right now it's all in an 'onInit' function in my component.
In my precipitation.component.ts:
this.input_id += this.data.id

var svg = d3.select("#"+this.input_id)

My html looks like:
<svg width="180" height="100"[attr.id]="input_id" > </svg>

The whole precipitation.component.ts for reference:
import { Component, OnInit, Input } from '@angular/core';
import { DataService } from '../data.service';
import { Http } from '@angular/http';
import * as d3 from 'd3';

@Component({
 selector: 'app-precipitation',
 templateUrl: './precipitation.component.html',
 styleUrls: ['./precipitation.component.css']
})

export class PrecipitationComponent implements OnInit {
  @Input() site1;

constructor(private _dataService: DataService, private http: Http) { }

date: Date;
dates: any;
value: Number;
eachobj: any;
data: any;
values: any;
average: any;
myClasses: any;
name: any;
input_id;

ngOnInit() {
  this.name = this.site1.name;

  var parse = d3.timeParse("%Y-%m-%d")
  this.data = this.site1
  this.input_id = ""
  this.input_id += "precipitation"
  this.input_id += this.data.id

  this.dates = Object.keys(this.data.historical_data)

  this.values = Object.values(this.data.historical_data)
  this.values.forEach((obj, i) => obj.date = this.dates[i]);

  this.data = this.values

  var svg = d3.select("#"+this.input_id)

  // svg = svg.select("." + this.name)
  var margin = { top: 20, right: 20, bottom: 30, left: 0 },
  width = +svg.attr("width") - margin.left - margin.right,
  height = +svg.attr("height") - margin.top - margin.bottom,
  barPadding = 5,
  barWidth = (width / this.data.length);
  var last = this.data[0].date
   var first = this.data[(this.data.length) - 1].date

  var g = svg.append("g")
    .attr("transform", "translate(" + margin.left + "," + margin.top + ")");

  var x = d3.scaleBand().rangeRound([0, width]).padding(0.1)
   .domain(this.data.map(function (d) { return d['date']; }));
  var y = d3.scaleLinear().rangeRound([height, 0])
   .domain(<[Date, Date]>d3.extent(this.data, function (d) { return d['precipitation']; }));

  g.selectAll(".bar")
  .data(this.data)
  .enter().append("rect")
  .attr("class", "bar")
  .attr("x", function (d) { return x(d['date']); })
  .attr("y", function (d) { return y(d['precipitation']); })
  .attr("width", barWidth - barPadding)
  .attr("height", function (d) { return height - y(d['precipitation']); });

  var line = d3.line()
  .x(function (d) { return x(d['date']); })
  .y(function (d) { return y(d['precipitation']); });

  svg.append('g')
  .attr("class", "axis--x")
  .append("text")
  .attr("fill", "#000")
  .attr("x", (width / 2) - 80)
  .attr("y", height + 40)
  .text(first)
  .style("font-size", "09")
  .style("font-family", "Roboto")
  .style('fill', '#5a5a5a');
  svg.append('g')
  .attr("class", "axis--x")
  .append("text")
  .attr("fill", "#000")
  .attr("x", (width / 2) + 45)
  .attr("y", height + 40)
  .text(last)
  .style("font-size", "09")
  .style("font-family", "Roboto")
  .style('fill', '#5a5a5a');

  svg.append("path")
  .data(this.data)
  .attr("class", "line")
  .attr("d", line);
 }

}

By the way I receive the data through the parent component:
<app-precipitation [site1]="site"></app-precipitation>


text:
Q: tt_news - where is the register "newsMoreLink" be defined? The extension tt_news is very useful for me but there is this little thingy called "register:newsMoreLink". This register does contain the singlePid of the contentelement (defined a single view page) and the uid of the newsarticle from the news extension.
This is the typoscript section of the "new ts" of the extension tt_news
As you can see there is "append.data = register:newsMoreLink"...
plugin.tt_news {
displayLatest {
subheader_stdWrap {
# the "more" link is directly appended to the subheader
      append = TEXT
  append.data = register:newsMoreLink
      append.wrap = |
      # display the "more" link only if the field bodytext contains something
      append.if.isTrue.field = bodytext
      outerWrap =
|

}
}
}

What is "register:newsMoreLink"? Is this like a function or something? I do not know. But "register:newsMoreLink" produces a strange link if I use this on "append.data". It produces are "More >" link. The "More >" link after a news article teaser looks like this:

http://192.168.1.29/website/index.php?id=474&tx_ttnews%5Btt_news%5D=24&cHash=95d80a09fb9cbade7e934cda5e14e00a

474 is the "singlePid" (this is what it calls in the database
24 is the "uid" of the news article (the ones you create with the tt_news plugin in the backend)
My question is: Where is the "register:newsMoreLink" defined? Is it defined generally or do I miss a fact of Typo3..? How can I add an anchor link at the end of this "More >" href? Like:

http://192.168.1.29/website/index.php?id=474&tx_ttnews%5Btt_news%5D=24&cHash=95d80a09fb9cbade7e934cda5e14e00a#myAnchor1

A: register:newsMoreLink is not a function. It's one of the data types. In other words a type of data that you can access with stdWrap.data. register is set with LOAD_REGISTER. Though, in case of tt_news this is set in the PHP code with $this->local_cObj->LOAD_REGISTER().
I'm afraid you cannot easily add an anchor to that link. However, you can set the append to create your own custom link to the news record using typolink:
append = TEXT
append {
  value = text of the link
  typolink {
    # ...typolink configuration...
  }
}

You shall be interested in the typolink's attributes parameter, additionalParams and section.

A: this is the code I use to link to an pid with a anchor target:
        displayList.plugin.tt_news.subheader_stdWrap {

        append = TEXT
        append.data >
        append {
            value = mehr
            typolink{
                parameter = 47 // pid
                section  = entry_{field:uid} // anchor name
                section.insertData = 1
            }
        }


text:
Q: Pass object that contains objects to Activity via Intent I have an Object that I need to pass via the Intent to another Activity via the onclick method.
I was following this answer here How to send an object from one Android Activity to another using Intents?
Which works fine however my Object has within it an Array of objects.
How do I pass this object with its Array of Objects?
Below are the classes before using Parcelable
List (the object to be passed)
public class List  {

    private String Name;
    private ArrayList<ListItem> items;

    public List(){
        items = new ArrayList<ListItem>();
    }

    public void addItem(String title, String d, String s, int p){
        ListItem i = new ListItem();
        i.setDecription(d);
        i.setPrice(p);
        i.setSite(s);
        i.setTitle(title);
        items.add(i);
    }

    public String getName() {
        return Name;
    }
    public void setName(String Name) {
        this.Name = Name;
    }
    public int getCount() {
        return items.size();
    }

    public ArrayList<ListItem> getList(){
        return items;
    }
}

ListItem
public class ListItem {

    private String  title;
    private String  decription;
    private String  site;
    private int     price;

    public void setTitle(String title) {
        this.title = title;
    }
    public void setDecription(String d){
        this.decription = d;
    }
    public void setSite(String s){
        this.site = s;
    }
    public void setPrice(int i){
        this.price = i;
    }

    public String getTitle(){
        return title;
    }
    public String getDecription(){
        return decription;
    }
    public String getSite(){
        return site;
    }
    public int getPrice(){
        return price;
    }
}

So how would I use Parcelable on List to send the ArrayList as well.
THank you and if you need any more info please ask!

A: You're trying to pass around data that shouldn't normally be passed around. A list is an ideal candidate for an SQLite Database. Try that or another way to persist data in android: http://developer.android.com/guide/topics/data/data-storage.html
If you insist on using Parcelable:
How can I make my custom objects Parcelable?
Also don't use List as your own type, it's standard JAVA.


text:
Q: Use latex code in math expression in Lyx I would like to enter the expression
\textcolor<2>{red}{stuff}

inside a Lyx math environment. But Lyx always renders it as
\textcolor{}<2>{red}{stuff}

Is there a way how to pass <> arguments to Lyx in mathmode?

A: If you know how to insert code in a equation in Lyx, you could define yourself a new command
 \newcommand\mytextcolor[1]{\textcolor<#1>}

and then use
 \mytextcolor{2}{red}{stuff}

in the equation. This will avoid that Lyx sees the <>.


text:
Q: Best orientation line bearing of a vector polygon in QGIS to fit the best Let say, I have a country vector layer like Lebanon in this example, for us as humans we can easly see that the country extends the best not from north to south like Chile, or from east to west like Turkey but oblique from Northeast to Southwest.
If I calculate the centroid of Lebanon C as in image below, is there an approach or possibility to find the angle theta between the line passing through C and the vertical line North-South to fit the best like the orientation of the country?
I drawn the blue lines with paint to show my idea, see image below

A: In later versions of QGIS, you can use the function main_angle in the field calculator.
main_angle($geometry)

From the help panel of the field calculator:

Function main_angle
Returns the angle of the long axis (clockwise, in degrees from North) of the oriented minimal bounding rectangle, which completely covers the geometry.

Note: the minimal bounding rectangle in the image was created for visualisation purposes using the function oriented_bbox


text:
Q: Suggesting ideal locations for column breaks in the multicols environment I've tried using minipages (and had overflow off the bottom of the page).  I'm thinking of something along the lines of \pagebreak[0] but for suggesting column breaks.  Almost a \columnbreak[0], if you will.
I have some text and then a linebreak and then a tikzpicture and then a new pagagraph and then we repeat the text, linebreak, tikzpicture a number more time.  The text and tikzpicture get separated between columns and pagebreaks so I figure if I could tell TeX that I'd rather have the columnbreak between the previous tikzpicture and the next text, then I could solve the problem.


text:
Q: How do change a particular option in linux kernel config file? I tried to follow the default config file for my Creator CI20 in particular setting the CONFIG_HID as follow:
# CONFIG_HID is not set

See ref here.
However everytime, I do a:
$ make menuconfig
<Exit>+<Save>

It turns back to:
CONFIG_HID=y

How do I make sure to have CONFIG_HID=n in my case ?

A: You certainly have checked another option which automatically enables CONFIG_HID.
While in menuconfig, you can use '/' to search for CONFIG_HID and find which other option enables it.


text:
Q: Sample android app demonstrating telephony api? Is there any sample application which demonstrates the capabilities of Telephony API of android? I am interested in getting the call notifications / caller number etc(I understand its doable with PhoneStateListener). Also, Is it possible for 3rd party application to change the incoming call window / outgoing call window (basically to give the user an extra button to search the incoming number from a REST service) ?
Any useful links  or sample application would be very much helpful. Any suggestions ?

A: PhoneStateListener tells your app about phone activity.  Here's some sample code from one of my apps that pauses music when the phone is active:
/**
 * Helper class to pause music while a phone call is in progress.
 *
 * The Android emulator can simulate an outgoing call by clicking
 * the phone button and dialing normally.  Simulate an incoming call
 * by starting the emulator, "telnet localhost 5554" then enter
 * "gsm call 5551234" into the telnet session.
 */
private class MusicServicePhoneStateListener extends PhoneStateListener {
    private boolean mResumeAfterCall = false;

    @Override
    public void onCallStateChanged(int state, String incoming_number) {
        switch (state) {
        case TelephonyManager.CALL_STATE_OFFHOOK:
        case TelephonyManager.CALL_STATE_RINGING:
            Log.i(tag, "phone active, suspending music service");
            mResumeAfterCall = mMediaPlayer.isPlaying();
            mMediaPlayer.pause();
            break;
        case TelephonyManager.CALL_STATE_IDLE:
            Log.i(tag, "phone inactive, resuming music service");
            if (mResumeAfterCall) {
                mMediaPlayer.start();
            }
            break;
        default:
            break;
        }
    }
}

Create and start the listener in onCreate via:
    mPhoneListener = new MusicServicePhoneStateListener();
    ((TelephonyManager)getSystemService(Context.TELEPHONY_SERVICE)).listen(mPhoneListener, PhoneStateListener.LISTEN_CALL_STATE);

Stop the listener in onDestroy with:
    ((TelephonyManager)getSystemService(Context.TELEPHONY_SERVICE)).listen(mPhoneListener, 0);

As for modifying the incoming call dialog the best suggestion I've found is to use a short delay followed by a custom toast message (delay so that your toast appears "above" the incoming call dialog).


text:
Q: Generating a stacked cumulative smooth frequency distribution plot I have data in which two types of occurrences are registered: type_a and type_b and their year of occurrence.
This is one way to generate an example of my data:
set.seed(1)
years <- 1991:2010
type_a_years <- 20
type_b_years <- 10
type_a <- round(runif(type_a_years, 0, 5))
type_b <- c(rep(0, type_a_years-type_b_years),round(runif(type_b_years, 5, 7)))

df <- data.frame(year = unlist(sapply(1:length(years), function(x) c(rep(years[x], type_a[x]),rep(years[x], type_b[x])))),
                 type = unlist(sapply(1:length(years), function(x) c(rep("type_a", type_a[x]),rep("type_b", type_b[x])))))

head(df)
  year   type
1 1991 type_a
2 1992 type_a
3 1992 type_a
4 1993 type_a
5 1993 type_a
6 1993 type_a

I'd like to generate a cumulative frequency distribution plot of type_b events stacked on top of type_a events by year and I'd like the distributions to appear as curves rather than bars.
I'm guessing it should be some manipulation of:
library(ggplot2)
ggplot(df, aes(year)) + stat_ecdf()

Where I'll get two curves and stacked by type where the area under each type will be filled with a different color. That is, the area between the type_a curve and the x-axis will be in one color and the area between the type_b curve and the type_a curve will be in another color.

A: You can do it using some aggregating in dplyr and tidyr, then using geom_area.
library(tidyr)
library(dplyr)
df1 <- df %>% group_by(type, year) %>%
              summarise(total = n()) %>%
              mutate(total = cumsum(total)) %>%
              ungroup %>%
              complete(type, year, fill = list(total = 0))

Now plot:
library(ggplot2)
ggplot(df1, aes(x = year, y = total, fill = type)) + geom_area()


text:
Q: How to skip duplicate data in foreach loop I need help in removing or skipping duplicate data from foreach array, i try to use array_unique() but it doesn't help.
here's my code.
<?php
if(is_cart()){
    foreach ( WC()->cart->get_cart() as $cart_item_key => $cart_item ) {
        $term_name = get_the_terms( $cart_item['product_id'], 'product_cat' );

        foreach($term_name as $idterm){
            if($idterm->parent == 0){
                $parentcat = $idterm->description;
            }
            $term_prid = $idterm->term_id;
        }

        $rootId = end( get_ancestors( $term_prid, 'product_cat' ) );

        $root = get_term( $rootId, 'product_cat' );
        if(!empty($root->description)){
            echo '

'.$root->description.'

';
        }
    }
    if(!empty($parentcat)){
        echo '

'.$parentcat.'

';
    }
}
?>

if i have more than 2 products of same category in cart it repeat the same data, which should not.
this is what i get from print_r($term_prid)
91
91
13

How can i get
91
13

A: Save the IDs you've seen in an array, and check against that.
if(is_cart()){
    $seen_ids = [];
    foreach ( WC()->cart->get_cart() as $cart_item_key => $cart_item ) {
        $term_name = get_the_terms( $cart_item['product_id'], 'product_cat' );

        foreach($term_name as $idterm){
            if (in_array($idterm->term_id, $seen_ids)) {
                continue;
            }
            $seen_ids[] = $idterm->term_id;

            if($idterm->parent == 0){
                $parentcat = $idterm->description;
            }

            $term_prid = $idterm->term_id;

        }

        $rootId = end( get_ancestors( $term_prid, 'product_cat' ) );
        $root = get_term( $rootId, 'product_cat' );
        if(!empty($root->description)){
            echo '

'.$root->description.'

';
        }
    }
    if(!empty($parentcat)){
        echo '

'.$parentcat.'

';
    }
}


text:
Q: Lookup Combo that supports remote data - load data only after user wants to I'm building a VCL c++ builder application.  I would like to see if anyone knows of a component that can load data in the lookup upon drop down only after a user has typed a few letters to limit the rows queried?  Preferably after pressing Tab, or Enter.
What I would like best is to get a behaviour similar to what Linux command line has, but that might be wishful thinking.  The way it would work is to drop down the combo list after user presses tab only if there is multiple options available, and to fill in additional text till the point where characters are not the same anymore, then if user presses tab again, drop down list.
The next best would be if the drop down would only allow drop down if user has typed a few letters, then pressing a specific button opens the dataset with the parameter of the typed text so far, then drops down the combo.
Does a component like this exist?

A: You can check out TMS Software. I'm not sure if it has something exactly for you, but their components are quite flexible. And you can send a feature request to them - to consider for next update. If you are lucky they might add it to next release.


text:
Q: Auto-Refresh on content changed shows only one record out of multiples Below code of auto refresh is not giving error but it shows only one record out of multiples when refresh.
But when i include and do not refresh the div it shows all records.
Like this it shows all records

     <?php include('orders.php'); ?>

Like this it shows one record:

orders.php
<?php
include ('inc/db.php');

$sqlx4  = "select distinct(order_id) as order_id from orders_placed where status = 0 ";
$sqlx5  = $dba2->query($sqlx4);
while ($sql6    = $sqlx5->fetch_assoc()){

    $sqlx1  = "select count(order_id) as total_items, order_id from orders_placed where status = 0 and order_id in ('".$sql6['order_id']."') ";
    $sqlx2  = $dba2->query($sqlx1);
    $sqlx3  = $sqlx2->fetch_assoc();

    $timeoid        = $sqlx3['order_id'];
    $totalItems =   $sqlx3['total_items'];
?>

            Order # <?php echo $timeoid; ?>,
            Total Items ( <?php echo $totalItems; ?> )

<?php } ?>

.
var cacheData;
var data = $('#newOrderRefresh').html();
var auto_refresh = setInterval(
function () {
    $.ajax({
        url: 'orders.php',
        type: 'POST',
        data: data,
        dataType: 'html',
        success: function(data) {
            if (data !== cacheData){
                cacheData = data;
                $('#newOrderRefresh').html(data);
            }
        }
    })
}, 1000);


text:
Q: java PdfTextExtractor.getTextFromPage(Unknown Source) Hello i have trouble with parsing a pdf when the iterator reaches page 11 an exception is throw.
Any ideas? Thanks
Here's my code:
import java.io.*;
import java.nio.charset.Charset;
import java.util.regex.*;
import com.lowagie.text.pdf.PdfReader;
import com.lowagie.text.pdf.hyphenation.TernaryTree.Iterator;
import com.lowagie.text.pdf.parser.PdfTextExtractor;

public class PdfParser {
    /**
     * @param args
     */
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        int index = 0;
        try {
            PdfReader readerN = new PdfReader("C:\\Documents and Settings\\stefan.stere\\hibernateWorkspace\\PdfParser\\src\\monitor3.pdf");
            OutputStreamWriter out = new OutputStreamWriter( new FileOutputStream(new File("C:\\Documents and Settings\\stefan.stere\\hibernateWorkspace\\PdfParser\\src\\pdf2txt.rtf")),"Cp1252");

            PdfTextExtractor parse = new PdfTextExtractor(readerN);
            int nrPages = readerN.getNumberOfPages();

            for (int i=1; i<nrPages ; i++) {
                index++;
                String page = parse.getTextFromPage(i);
                if(page != null){
                    page = page.replace(new StringBuffer("null"), new StringBuffer("??"));
                    page = page.replaceAll("Comercial.", "Comerciala");
                    page = page.replaceAll("ACT ADI..IONAL", "ACT ADITIONAL");
                    page = page.replaceAll("HOT.R..E", "HOTARARE");
                    page = page.replaceAll("HOT.R..EA", "HOTARAREA");
                    page = page.replaceAll("HOT.R..I", "HOTARARI");
                    page = page.replaceAll("..cheiat.", "incheiata");
                    page = page.replaceAll("ANUN..", "ANUNT");
                    out.write(page);
                    System.out.println(page);
                }
            }
            out.close();
            readerN.close();
        } catch (Exception e) {
            // TODO: handle exception
            e.printStackTrace();
            System.out.println(index);
        }
    }
}

and the exception stack:
java.lang.ArrayIndexOutOfBoundsException: Invalid index: 62
at com.lowagie.text.pdf.CMapAwareDocumentFont.decodeSingleCID(Unknown Source)
at com.lowagie.text.pdf.CMapAwareDocumentFont.decode(Unknown Source)
at com.lowagie.text.pdf.parser.PdfContentStreamProcessor.decode(Unknown Source)
at com.lowagie.text.pdf.parser.PdfContentStreamProcessor.displayPdfString(Unknown Source)
at com.lowagie.text.pdf.parser.PdfContentStreamProcessor$ShowTextArray.invoke(Unknown Source)
at com.lowagie.text.pdf.parser.PdfContentStreamProcessor.invokeOperator(Unknown Source)
at com.lowagie.text.pdf.parser.PdfContentStreamProcessor.processContent(Unknown Source)
at com.lowagie.text.pdf.parser.PdfTextExtractor.getTextFromPage(Unknown Source)
at PdfParser.main(PdfParser.java:32)

A: No answer but it seems a lot of people have the same problem, there's another related question on SO. And if you search with ArrayIndexOutOfBoundsException and getTextFromPage on google you see the same problem but no solution...
BTW, your loop will stop before processing the last page as the first page has index 1...

A: As info, now iText 5.0.6 works perfect with more PDF versions, I've tested PDF generated with many different programs and 2.1.7 had problems on many.
Get the last version from iText download


text:
Q: addAll method in list java I have been working around addAll method in java. But it wonders me as
What exactly is the difference between public void addAll(List<T extends Person> persons) and  public void addAll(List<Person> persons)

A: If you are asking about the declartaion, then the difference is that the addAll(List<T extends Person> persons) allows call with list which holds only subclasses of Person. While the addAll(List<Person> persons) will not accept such parameters. As List<SubclassOfPerson> cannot be assigned to List<Parson>
so:
class Child extends Person {};
List<Child> children = .....

calling addAll(children) makes sense, as any  child is a Person, but if the addAll was declared as addAll(LIst<Person> persons), compiler would protest.

A: Both of those methods calls would end up doing the same thing: add every element in the list argument to the list on which the method is invoked. The fact that compiler goes through a slightly different route to process your code has no implication on what ends up being executed nor on the final contents of the list.
Do you have a more specific question?

A: If you want to understand it, you'll have to go through this:
http://docs.oracle.com/javase/tutorial/java/generics/
but in order to answer you, the difference is, that when you write
public void addAll(List<T extends Person> persons)

then you can call this method with addAll(List<Worker> workers) if you have class Worker extends Person. You cannot do that with second declaration though.


text:
Q: Powershell DSC - Download MSI file to VM I've tried the following example to download from Azure blob or Azure file share but never got it to work. Is there a way to download files to VM passing credentials or keys?
        Import-DSCResource -ModuleName PSDesiredStateConfiguration, xPSDesiredStateConfiguration

Node webServer
{           xRemoteFile Installs
                 {
                 DestinationPath = "C:\Scripts"
                 Credential = $StorageCredential
                 Ensure = "Present"
                 SourcePath = "https://storagename.blob.core.windows.net/installs"
                 Type = "Directory"
                 Recurse = $true
                 }
    }

I also tried the using File module.
    Import-DSCResource -ModuleName PSDesiredStateConfiguration, xPSDesiredStateConfiguration

                Node webServer
                {
                                File Installs
                                {
                                DestinationPath = "C:\Scripts"
                                Credential = $StorageCredential
                                Ensure = "Present"
                                SourcePath = "\\storagename.file.core.windows.net\installs"
                                Type = "Directory"
                                Recurse = $true
                                }
                }

A: If you download file from Azure File Share, you could refer to this example. Add following script to your script.
Configuration SimpleExampleWithCredentials {

  param(

      [Parameter(Mandatory=$true)]

      [ValidateNotNullOrEmpty()]

      [PSCredential]$Credentials

  )

If you use classic VM, you could use the following cmdlets.
Set-AzureVMDscExtension -VM $vm -ConfigurationArchive MyConfiguration.ps1.zip -ConfigurationName MyConfiguration -ConfigurationArgument @{ storageCredential= (Get-Credential) }

If you use ARM VM, you should use cmdlet Set-AzureRmVMDscExtension.


text:
Q: is_callable doesn't work on server after uploading my project to server I constantly get this error:

InvalidArgumentException in AccessDecisionManager.php line 52: The
  strategy "affirmative" is not supported.

I checked AccessDecisionManager and found this code:
public function __construct(array $voters, $strategy = self::STRATEGY_AFFIRMATIVE, $allowIfAllAbstainDecisions = false, $allowIfEqualGrantedDeniedDecisions = true)
{
    ....

    $strategyMethod = 'decide'.ucfirst($strategy);
    if (!is_callable(array($this, $strategyMethod))) {
        throw new \InvalidArgumentException(sprintf('The strategy "%s" is not supported.', $strategy));
    }

    ....
}

I checked with var_dump that $strategyMethod = 'decideAffirmative'
But is_callable returns false even if method is present!
private function decideAffirmative(TokenInterface $token, array $attributes, $object = null)
{
    ....
}

In local server it turns perfectly. On remote I get false. PHPInfo of server
Thanks


text:
Q: Yammer embedded application iframe Is it possible to create an App that has an embedded page (iframe/etc) inside Yammer ?
In Yammer we can create standalone application that interact with Yammer, Can we this application inside Yammer?

A: You can inject (static) OpenGraph content into Yammer, but you can't inject dynamic content through the platform, and definitely not iframes. Check out the Yammer Developer Center Open Graph documentation for use cases and examples.


text:
Q: Delegate returns nill in Swift (Data flow between Model and ViewController) I'm creating a basic application in swift where I get data from an api and show it. My Model class handles the fetching data part and I use a delegate to communicate data with the ViewController.
However when fetched data is passed into the controller it is nill for some reason.
Here are the things I know/have tried.

*

*Extracting the JSON is working. The data is correctly fetched.

*I tried using viewWillAppear as well as viewDidLoad

*I have set the delegate to self in the View Controller

Abstracted code is below.
//Model Class

protocol DataDetailDelegate {

    func datadetailFetched(_ datadetail: DataDetailItem)
}

class Model {

    var datadetaildelegate: DataDetailDelegate?

    func fetchData(ID: String) {

        let url = URL(string: Constants.Data_URL + ID)

        guard url != nil else {
            print("Invalid URL!")
            return
        }

        let session = URLSession.shared.dataTask(with: url!) { data, response, error in

            if error != nil && data == nil {
                print("There was a data retriving error!")
                return
            }

            let decoder = JSONDecoder()
            do {
                let response = try decoder.decode(MealDetail.self, from: data!)

                if response != nil {

                    DispatchQueue.main.async {
                        self.datadetaildelegate?.datadetailFetched(response)
                    }

                }

            } catch  {
                print(error.localizedDescription)
            }

        }
        session.resume()

    }

}

//View Controller
import UIKit

class DetailViewController: UIViewController, DataDetailDelegate {

    @IBOutlet weak var instruction: UITextView!

    var model = Model()
    var datadetail : DataDetailItem?

        override func viewDidLoad() {
            super.viewDidLoad()

            model.datadetaildelegate = self
            model.fetchData(ID: data.id)

            if self.datadetail == nil {
                print("No data detail available")
                return
            }

            self.instruction.text = datadetail.instruction
        }

    func datadetailFetched(_ datadetail: DataDetailItem) {
        self.datadetail = datadetail
    }
}

A: As mentioned in the comments, there are many problems with the above code, but the main one being not recognising the asynchronous nature of the fetchData.
The below is a rough solution that addresses the critical issues with your code, rather than being best practice and addressing all of them.  For example you could also check the contents of error and response codes, and pass them back through the completion handler (maybe as a Result type).
For starters, streamline your fetchData so that it gets the data and then handles that data via a completion handler in an asynchronous manner.  Also, don't call it a Model as it's really not.
class SessionManager {

  func fetchData(withID id: String, completion: @escaping (data) -> Void) {
    guard let url = URL(string: Constants.Data_URL + ID) else {
       print("Invalid URL!")
       return
    }

    let session = URLSession.shared.dataTask(with: url) {  data, response, error in

    guard error == nil, let data = data else {   //could be done far better by checking error and response codes
        print("There was a data retriving error!")
        return
    }
    completion(data)
  }
  session.resume()
}

Then adapt your view conroller so that it creates the session manager and fetches the data, but processes it in the completion handler.  I've only added the relevant content.
class DetailViewController: UIViewController, DataDetailDelegate {

    lazy var sessionManager = SessionManager()
    var datadetail : DataDetailItem?

    override func viewDidLoad() {
       super.viewDidLoad()
       sessionManager.fetchData(withID: data.id){ [weak self] data in
         let decoder = JSONDecoder()
         do {
            let response = try decoder.decode(MealDetail.self, from: data)
            DispatchQueue.main.async {
              self?.datadetail = response
              self?.instruction.text = datadetail.instruction
            }
         } catch  {
           print(error.localizedDescription)
         }
      }
   }

   // rest of view controller
 }

That should be enough to get you going.  There are many best practice examples/tutorials scattered around that would be worth a look so you can refine things further.
Note: this has been written in here without a compiler to hand, so there may be some syntax that needs tweaking.


text:
Q: how to get g++ package install in ubuntu 14.04LTS offline? since I am new to this society but I a using Ubuntu for last one and a half year.I was not facing any problems because it is best. My problem is that how to get g++ packages install in my computer in an offline way for 14.04 LTS version because I do not have any internet connections.Thank you to all the respected one's and thank you for making me as one of your family member.

A: Download g++ package for offline installation here. You can install the package with this command:
sudo dpkg -i /path/to/deb/file

For more packages, visit https://packages.ubuntu.com/trusty/g++.


text:
Q: Using Different Language in Voice XML 2.0 Prompt There is classic tag  which used for TTS (Text To Speech) in VXML 2.0 [ prompt ]
 <prompt>
        Which do you like better, dogs or cats?
 </prompt>

My VXML Browser can also able to make TTS suppose for French like this
<prompt>
        Ce que vous aimez mieux, les chiens ou les chats?
 </prompt>

How can I set the TTS values in VXML so that XML Browser will use  different language for TTS such as French?

A: Tag <prompt> has language attribute xml:lang which can be used to specify language according to VXML specification
Your browser might not support it though. You should better provide more details on the VXML browser you are using.


text:
Q: Is it possible to have two separate css files in the manifest, affecting two separate domains? You can have the following:
  "content_scripts": [
    {
      "css": [ "style1.css" ],
      "matches": ["http://domain1.com"],
      "run_at": "document_end"
    }
  ],

but is it possible to do it for two or more domains?
Such as the following:
(which I know wouldn't work but for the sake of example)
  "content_scripts1": [
    {
      "css": [ "style1.css" ],
      "matches": ["http://domain1.com"],
      "run_at": "document_end"
    }
  ],
  "content_scripts2": [
    {
      "css": [ "style2.css" ],
      "matches": ["http://domain2.com"],
      "run_at": "document_end"
    }
  ],

So is this possible to do? If so, how can it be done?

A: Sure, you can inject as many different ones as you want. The syntax would be like this:
"content_scripts": [
{
  "css": ["style1.css"],
  "matches": ["http://domain1.com"]
},
{
  "css": ["style2.css"],
  "matches": ["http://domain2.com"]
}]


text:
Q: rowSelect event is not being called for p:datatable jsf primefaces I'm using primefaces 5.2 and jsf 2.2.6.
I'm trying to select a row from a datatable and populate a panelgrid. The problem is that the onRowSelect method is not being called when selecting the row.
Here is the code for the datatable:
<h:body styleClass="mainPageBody" >

<h:outputText value="#{msg['form.currentProjects']}" styleClass="mainPageProjectsTableTitle" />

    <h:form id="formTable" >
        <p:dataTable id="transactionsTable" var="data" value="#{transactionsPage.ttList}" widgetVar="projectData"
                     rowKey="#{data.id}"
                     draggableColumns="true"
                     resizableColumns="true" liveResize="true" emptyMessage="#{msg['form.noTransactionsFound']}" rows="20"
                     selectionMode="single" selection="#{transactionsPage.selectedTransaction}"
                     filteredValue="#{transactionsPage.fitleredttList}" paginator="true" paginatorPosition="both" paginatorTemplate="{CurrentPageReport} {RowsPerPageDropdown} {FirstPageLink} {PreviousPageLink} {PageLinks} {NextPageLink} {LastPageLink}"
                     >

                 <h:outputText value="#{data.id}"/>

                 <h:outputText value="#{data.uicNumber}"/>

    </h:form>

Here is the code for the panel that has to be populated with values from the selected row, that is part of the same page:
<h:form id="form2">

    <h:panelGrid id="panel" columns="3" cellpadding="5" styleClass="ui-widget-content-borderless" columnClasses="mp-column-center">
        <ui:include src="transactionsEdit.xhtml"/>
    </h:panelGrid>

</h:form>

The managed bean is @ViewScoped and has getter and setter method for the property selectedTransaction and also the method onRowSelect
public void onRowSelect(SelectEvent event) {
    selectedTransaction = (Transactions) event.getObject();
}

The problem is that the following code

is not calling the method onRowSelect.
Does somebody know what the problem could be?
EDIT:
ANSWER: It seems that I couldn't succeed with p:ajax to call the methods onRowSelect or setSelectedTransaction, even if I passed a parameter to onRowSelect.

So, I tried with f:ajax. onRowSelect was called only when passed with a parameter, but the parameter was always null. So this method wasn't useful for me, but the setSelectedTransaction is called too, so the problem solved.
And then, I had to update the panel and this is done using render for f:ajax, not update that is only used for p:ajax.
So the final ajax event call looks like this:
<f:ajax event="rowSelect" render="formTabs:tabs:form2:panel"/>


text:
Q: Does web.config authorization work on files other than aspx? I have ASP.NET application with forms authentication. It works well but I have one directory with olly .txt files (no aspx files) that I want users not to access (or only logged in users).
I added web.config to this directory:
<system.web>
    <authorization>
        <deny users="?" />
    </authorization>
</system.web>

EDIT:
This works only for .aspx files. It does not work for .txt files and similar. Users cannot browse this directory nor subdirectories however knowing .txt file name they can access it.
I tries IIS6  and IIS 7.5. On IIS6 .txt files are also restricted but on IIS 7.5 not so it may be IIS configuration issue.

A: Your question depends on the web server you are using. ASP.NET authorization works only with file types that are handled by ASP.NET. If you have IIS 5 or 6, this is normally not true for .txt files or even for .jpg, .gif and pure .html files, but only for aspx, asmx etc.
No problem if you have IIS7 and integrated mode, because ASP.NET is integrated and will be called for every type of file. So if you have IIS5 or 6 you have to register the mime types such as the aspnet.isapi is called for .txt files as well.
UPDATE:
The configuration of
 <deny users="*">

locks out all users. It would work only in combination with allow, e.g.
<allow roles="administrators" />
<deny users="*">

like this all users but administrators will be locked out. If a user is authenticated but not adminstrator, he will be redirected to the login page.
The other option is to lock out anonymous users only:
<deny users="?">

A: Add location section to the web.config with appropriate settings location Element (ASP.NET Settings Schema)

A: If you use IIS 7+, then you can use the system.webServer/security/authorization http://www.iis.net/ConfigReference/system.webServer/security/authorization section, and have that automatically work for any kind of content in any pipeline mode.
IF you still want to use system.web seciton, then you will need to use Integreated Mode and do the changes that are mentioned in the modules to run for all content, but by far, the simplest is use system.webServer/security/authorization instead.


text: Q: Installing ubuntu to a new laptop(asus laptop with Ryzen processor and Vega graphics) I want to install ubuntu into my new laptop (I want to remove my windows completely) , which partition mode  i should use when I create bootable usb(MBR or GPT) , what all thing do i need to be cautious when installing ubuntu to a new laptop .


text:
Q: Why do generic type restrictions have to be redeclared on descendant types? In C#, given a generic type such as this:
interface IGenericType<T> where T : new()

And a descendant type, such as:
class GenericTypeImplementation<U> : IGenericType<U>

Why do we need to explicitly restrict the generic type U with all the restrictions of the parent type?
class GenericTypeImplementation<U> : IGenericType<U> where U : new()

Am I right in inferring that the issue is in the compiler computing the union of restrictions?
interface IGenericType<T> where T : new()
interface IGenericType2<T> where T : SomeOtherType
class GenericTypeImplementation<U> : IGenericType<U>, IGenericType2<U>
/* Hypothesis: Compiler can't infer U must be "SomeOtherType + new()" */

A: In my opinion, the compiler could be smart enough to infer the restrictions theoretically. But it shouldn't be so smart, because a too-smart compiler is sometimes dangerous. Developers always need a clear/explicit definition of everything. See this scenario:
(1) there is an interface IFoo<T> where T : new()
(2) a class Foo<T> : IFoo<T> and the new() constraint is added automatically by the compiler(brilliant!)
(3) the class Foo<T> is a very base class in the whole project, class A<T> : Foo<T>, and then class B<T> : A<T>...
(4) Now another developer can hardly realize there is such a constraint by looking into the definition of the class, he will get weird compiling errors(well that's acceptable). But what if they are invoked by reflection? Sometimes the program is correct, because the data meets the restriction by accident.

A: The compiler is able to to infer that U must be convertible to SomeOtherType and must have a default constructor.  It will generate a compiler error for each constraint:
Error   1   The type 'U' must have a public parameterless constructor in order to use it as parameter 'T' in the generic type or method '....IGenericType<T>'
Error   2   The type 'U' must be convertible to '....SomeOtherType' in order to use it as parameter 'T' in the generic type or method '....IGenericType2<T>'

This will also happen with just one of those interfaces implemented as well.  The class must successfully implement both interfaces in order to be compiled:
class GenericTypeImplementation<U> : IGenericType<U>, IGenericType2<U>
    where U : SomeOtherType, new()
{...}

or as a non-generic type:
class GenericTypeImplementation : IGenericType<SomeType>, IGenericType2<SomeOtherType>
{...}

To mark a class as implementing an interface is not a way of specifying constraints on the generic type parameters of a class; it is a way of requiring that those constraints exist  on a new type parameter or that they be satisfied by a supplied type.
Perhaps you could think of it this way: an interface is a constrained set of classes and a generic class is also a constrained set of classes.  A generic interface is a constrained set of generic classes.  When you say that a generic class implements a generic interface, you are asking the compiler, "Is this generic class strictly within the set specified by this generic interface?"  You are not merely intersecting them as a further constrained set of classes.

A: Because a generic type restriction is on the type parameter of the defining class (U in your example), from a CLR point of view, that is a different type from the type parameter of the interface.
The type parameter of the class need not be the actual type parameter of the interface. It need not even be a simple type, as in:
class Implementation<T> : IGenericType<List<T>> { /* ... */ }

In this case, the compiler recognizes that List<T> satisfies the constraint, and so no further specification is necessary. But without such knowledge about the generic type parameter, the compiler requires you to declare it explicitly.
It is instructive to compare this to the similar but not identical behaviour of generic methods. As with classes that implement interfaces, the type restrictions must be specified with the declaration. There is one notable exception: if the implementation is explicit. In fact, the compiler will generate an error when you try to re-impose the restrictions.
For example, given an interface
interface ISomething {
    void DoIt<T>() where T : new();
}

the two correct ways to implement this interface are:
class OneThing : ISomething {
    public void DoIt<T>() where T : new() { }
}

class OtherThing : ISomething {
    void ISomething.DoIt<T>() { }
}

Leaving out the constraint in OneThing or iserting it in OtherThing produces a compile-time error. Why do we need the constraint in the first implementation and not in the second one? I'd say for the same reason I mentioned above for type constraints on interfaces: in the first implementation, the type T has no relation to the type parameter on the interface method, so it must be made explicit for the method to match the interface method. In the second implementation, the fact that we explicitly declare the interface means that the type parameter T is the exact same one that was used in the interface.


text:
Q: Error "This stream does not support seek operations" in C# I'm trying to get an image from an url using a byte stream. But i get this error message:

This stream does not support seek operations.

This is my code:
byte[] b;
HttpWebRequest myReq = (HttpWebRequest)WebRequest.Create(url);
WebResponse myResp = myReq.GetResponse();

Stream stream = myResp.GetResponseStream();
int i;
using (BinaryReader br = new BinaryReader(stream))
{
    i = (int)(stream.Length);
    b = br.ReadBytes(i); // (500000);
}
myResp.Close();
return b;

What am i doing wrong guys?

A: You probably want something like this. Either checking the length fails, or the BinaryReader is doing seeks behind the scenes.
HttpWebRequest myReq = (HttpWebRequest)WebRequest.Create(url);
WebResponse myResp = myReq.GetResponse();

byte[] b = null;
using( Stream stream = myResp.GetResponseStream() )
using( MemoryStream ms = new MemoryStream() )
{
  int count = 0;
  do
  {
    byte[] buf = new byte[1024];
    count = stream.Read(buf, 0, 1024);
    ms.Write(buf, 0, count);
  } while(stream.CanRead && count > 0);
  b = ms.ToArray();
}

edit:
I checked using reflector, and it is the call to stream.Length that fails. GetResponseStream returns a ConnectStream, and the Length property on that class throws the exception that you saw. As other posters mentioned, you cannot reliably get the length of a HTTP response, so that makes sense.

A: You can't reliably ask an HTTP connection for its length. It's possible to get the server to send you the length in advance, but (a) that header is often missing and (b) it's not guaranteed to be correct.
Instead you should:

*

*Create a fixed-length byte[] that you pass to the Stream.Read method

*Create a List<byte>

*After each read, call List.AddRange to append the contents of your fixed-length buffer onto your byte list

Note that the last call to Read will return fewer than the full number of bytes you asked for. Make sure you only append that number of bytes onto your List<byte> and not the whole byte[], or you'll get garbage at the end of your list.

A: If the server doesn't send a length specification in the HTTP header, the stream size is unknown, so you get the error when trying to use the Length property.
Read the stream in smaller chunks, until you reach the end of the stream.

A: With images, you don't need to read the number of bytes at all.  Just do this:
Image img = null;
string path = "http://www.example.com/image.jpg";
WebRequest request = WebRequest.Create(path);
req.Credentials = CredentialCache.DefaultCredentials; // in case your URL has Windows auth
WebResponse resp = req.GetResponse();

using( Stream stream = resp.GetResponseStream() )
{
    img = Image.FromStream(stream);
    // then use the image
}

A: Use a StreamReader instead:
HttpWebRequest myReq = (HttpWebRequest)WebRequest.Create(url);
WebResponse myResp = myReq.GetResponse();

StreamReader reader = new StreamReader(myResp.GetResponseStream());
return reader.ReadToEnd();

(Note - the above returns a String instead of a byte array)

A: Perhaps you should use the System.Net.WebClient API.  If already using client.OpenRead(url) use client.DownloadData(url)
var client = new System.Net.WebClient();
byte[] buffer = client.DownloadData(url);
using (var stream = new MemoryStream(buffer))
{
    ... your code using the stream ...
}

Obviously this downloads everything before the Stream is created, so it may defeat the purpose of using a Stream.  webClient.DownloadData("https://your.url") gets a byte array which you can then turn into a MemoryStream.

A: The length of a stream can not be read from the stream since the receiver does not know how many bytes the sender will send. Try to put a protocol on top of http and send i.e. the length as first item in the stream.


text:
Q: update database android doesn't work i'm discovering database in Android. I understand how to read it but i don't succed writing it. Here is the database:
        private static final String DATABASE_CREATE = "create table lesPlats
             (id integer primary key autoincrement, nom text not null, quantite integer);";
        database.execSQL(DATABASE_CREATE);

i edit it:
        values.put("nom", "plat1");
        values.put("quantite", 0);
        database.insert("lesPlats", null, values);

i want to increase the quantity of "plat1" (debug version in comment):
        int n=1;
     // Cursor c = database.rawQuery("SELECT * FROM lesPlats WHERE id="+n, null);
     // c.moveToFirst();
     // System.out.println("QUANTITY BEFORE: "+cursorToComment(c).quantite+ " (id: "+cursorToComment(c).id+")");

        database.rawQuery("UPDATE lesPlats SET quantite = 1 WHERE id = " + n, null);

     // c = database.rawQuery("SELECT * FROM lesPlats WHERE id="+n, null);
     // c.moveToFirst();
     // System.out.println("QUANTITY NEXT: "+cursorToComment(c).quantite+ " (id: "+cursorToComment(c).id+")");

with debugging, i got the result
QUANTITY BEFORE: 0 (id: 1)
QUANTITY NEXT: 0 (id: 1)
So there is a mistake somewhere. Could you tell me if the code is good? specially this one:
database.rawQuery("UPDATE lesPlats SET quantite = 1 WHERE id = " + n, null);
This means that quantity is set to 1 at the id=1, isn't it?
i try with UPDATE, i have the same result...

A: read and close the cursor before calling the second raw, because the query won't get executed without it :
c = database.rawQuery("UPDATE lesPlats SET quantite = 1 WHERE id = " + n, null);
c.moveToFirst();
c.close();

A: sorry guys, i've forgot the to set quantity in the cursorToComment procedure...
private Comment cursorToComment(Cursor cursor) {
    Comment comment = new Comment();
    comment.setId(cursor.getLong(0));
    comment.setNom(cursor.getString(1));
    comment.setQqte(cursor.getInt(2));   //here!!
    return comment;

thx a lot
So, three ways to change the database:
ContentValues values = new ContentValues();
values.put("quantite", 1);
database.update("lesPlats", values, "id=?", new String[]{"1"});

or
database.execSQL("UPDATE lesPlats SET quantite = 1 WHERE id = " + n);

or
c = database.rawQuery("UPDATE lesPlats SET quantite = 1 WHERE id = " + n, null);
c.moveToFirst();
c.close();

pfiou!


text:
Q: How to force a return value of a function in jest? I am trying  to test some code that relies on an api returning some data. Currently, I  am able to  mock the call of listNamespacedIngress in this function:
async function getIngress(namespace) {
  try {
    const result = await k8sIngressApi.listNamespacedIngress(namespace, true);
    const resultSpec = result.body.items.filter(e => e.metadata.name === deploymentPrefix)[0];
    if (!resultSpec) {
      throw new TypeError('Ingress spec is undefined');
    }
    return resultSpec;
  } catch (e) {
    return Promise.reject(e);
  }
}

using a jest.mock and mocking the return value of that function in this library, as seen here:
jest.mock('@kubernetes/client-node', () => ({
  KubeConfig: jest.fn().mockImplementation(() => ({
    loadFromCluster: jest.fn(),
    loadFromDefault: jest.fn(),
    makeApiClient: () => ({
      listNamespacedIngress: () =>
        Promise.resolve({
          body: {
            items: [
              {
                metadata: {
                  name: 'a',
                  namespace: 'b',
                },
                spec: {
                  rules: [
                    {
                      host: 'url.com',
                      http: {
                        paths: [
                          {
                            backend: {
                              serviceName: 'a',
                              servicePort: 80,
                            },
                          },
                        ],
                      },
                    },
                  ],
                },
              },

This way, I am able to test the initial return value if resultSpec doesnt end up being  undefined, as seen here (this test passes):
  it('Should return storybook-staging ingress details', async () => {
    // When
    const result = await getIngress();

    // Then
    expect(result.metadata.name).toEqual('a');
  });

However, I am unsure how I can force listNamespacedIngress to come back as undefined?
EDIT: Added full use of module
const kc = new k8s.KubeConfig();
kc.loadFromDefault();
const k8sDeploymentApi = kc.makeApiClient(k8s.AppsV1Api);
const k8sServiceApi = kc.makeApiClient(k8s.CoreV1Api);
const k8sIngressApi = kc.makeApiClient(k8s.NetworkingV1beta1Api);

const BRANCH_NAME = process.argv.slice(2)[0].toLowerCase();
const NAMESPACE = 'dev';
const deploymentPrefix = 'storybook-staging';

const DEPLOYMENT_CONFIG = getDeploymentConfig(deploymentPrefix, BRANCH_NAME);
const SERVICE_CONFIG = getServiceConfig(deploymentPrefix, BRANCH_NAME);
const INGRESS_CONFIG = getIngressConfig(deploymentPrefix);

const HTTP_CONFLICT = 409;

process.on('exit', code => {
  console.log(`About to exit with code: ${code}`);
});

async function getIngress(namespace) {
  try {
    const result = await k8sIngressApi.listNamespacedIngress(namespace, true);
    console.log(result);
    const resultSpec = result.body.items.filter(e => e.metadata.name === deploymentPrefix)[0];
    if (!resultSpec) {
      throw new TypeError('Ingress spec is undefined');
    }
    return resultSpec;
  } catch (e) {
    return Promise.reject(e);
  }
}

A: A proper way for listNamespacedIngress to change return values is to make it Jest spy. Since it's nested and cannot be easily referred in tests, it should be defined outside module mock:
// should be var because jest.mock is hoisted
var mockListNamespacedIngress;

jest.mock('@kubernetes/client-node', () => {
  mockListNamespacedIngress = jest.fn();

  return {
  KubeConfig: jest.fn().mockImplementation(() => ({
    loadFromCluster: jest.fn(),
    loadFromDefault: jest.fn(),
    makeApiClient: () => ({
      listNamespacedIngress: mockListNamespacedIngress
      ...

This also allows to assert that the function was called:
mockListNamespacedIngress.mockResolvedValue({ body: { items: [...] } });
await expect(getIngress()).resolves.toEqual('a');
expect(mockListNamespacedIngress).toBeCalledWith(...);

...

mockListNamespacedIngress.mockResolvedValue({ body: { items: [] } });
await expect(getIngress()).rejects.toThrow(TypeError);
expect(mockListNamespacedIngress).toBeCalledWith(...);


text:
Q: Configuring a Jenkins pipeline to ignore building unchanged projects I have a Jenkins pipeline that is triggered by a bitbucket webhook every time a pull request is created, and builds docker images.
My bitbucket repository contains multiple projects, each with it's own subfolder and Dockerfile.
I wouldn't want the pipeline to build docker images for all projects every time it is triggered.
How do I tell the pipeline to only build docker images for those projects that have changed?
Thanks,
O.


text:
Q: Test an if condition with mockito Code of the if statement:
if (reponse.getStatus() >= HttpServletResponse.SC_BAD_REQUEST) {
                LOGGER.error("Erreur lors de l'enregistrement de la trace technique - {}", reponse.getStatusInfo().getReasonPhrase());
            }

A: Basically testing always consists of two parts:

*

*preparing some input, so that your production code under test takes a specific path

*verifying that the expected "things" happened

First one is easy: you have to somehow make sure that the response object that your production code is dealing with has the required status. How you do that, very much depends on context.
For the second aspect, that is probably hard. You see, the only action taking place is a (probably static) call to that error() message. If that is the case, then your only way of testing this would be to use JMockit or PowerMock(ito), because those two frameworks allow you to verify static method calls.
So, the real answer is:

*

*figure for yourself how you can gain control over that response object

*buy into using one of these mocking frameworks (not recommended)

*rework your code so that it becomes testable without adding that (imho really really bad) dependency towards PowerMock(ito).


text:
Q: Alt and Title tags for SVG I am adding my images as svg files to my website. How to you add alt and title tags like you do for regular jpg and png images?
This is the code I use to display svg images.
<object type="image/svg+xml" data="img/logo.svg" width="182px" height="199px"></object>

Thanks

A: This question has some good info for you.
Even if you don't have a raster fallback, you could use the fallback just for the alt functionality like so:
<object type="image/svg+xml" data="img/logo.svg" width="182px" height="199px">
    <img src="img/logo.svg" width="182px" height="199px" alt="yourAltText" />
</object>


text:
Q: How to design extension mechanism for java app I have an application where I have a set of core features.

*

*The application itself HAS to work in core only mode.

*I would also want to make the application extensible such that, when certain jar/plugin files exist in the classpath/installation location, additional features would be available, things would just be there. This is OPTIONAL.
The way I would do it is using the factory pattern with a modification.
In the core package, I have an extension point (implemented by either a public static variable or a singleton, or other extension point model from my framework - Eclipse RCP). The extension jars/plugins get this extension point and registers its factory object to this extension point. (This is best done with RCP plugin/feature activation mechanism, or it can just be anything that causes a load of the extension jar/plugin factory class)
When the application runs, the core factory would produce objects from the extension factory if one has been registered or use its core factory otherwise.
This is how the application goes from core mode to extension mode if an extension jar exists.
I wonder if this is a decent way to do what I wanted to do or this is just a hack, anti-pattern, etc...
Please propose a better solution if you can. Thanks.

A: Java has a standard mechanism precisely for this, the java service providers, thinks in the way you use a JDBC plugin, you put the JDBC driver in your classpath and your application now can connect to this concrete database provider (oracle, mysql). In fact this is used in a lot of java standards that define an interface an allow different implementations.
Its not very different from you implementation, but its a standard and there are some classes in the jdk to make this easy to implement, for example take a look to this: http://docs.oracle.com/javase/7/docs/api/java/util/ServiceLoader.html


text:
Q: ArrayList of ArrayList outputting I am trying to put an arraylist of integers inside an arraylist of arraylist of integers .
i tried.
public class test3{
    public static void main(String[] args) throws IOException{
        String text= null;
        ArrayList<ArrayList<Integer>> outerlist = new ArrayList<ArrayList<Integer>>();
        ArrayList<Integer> innerlist = new ArrayList<>();

        int dept= 17;
        int arrv= 6;
        int[] arr = new int[1000];
        String[] stations = null;
        FileReader file = new FileReader("test2.txt");
        BufferedReader br = new BufferedReader(file);
        while((text = br.readLine()) != null){
            innerlist.clear();
            stations = text.split(" ");
            //int[] array = Arrays.stream(stations).mapToInt(Integer::parseInt).toArray();

            for(int i = 0 ; i<stations.length ; i++){
                arr[i] = Integer.parseInt(stations[i]);
            }
            for(int j = 0 ; j<stations.length ; j++){
                innerlist.add(arr[j]);
            }
            outerlist.add(innerlist);

        }
        System.out.println(outerlist);
    }
}

it should output
[[1, 17, 3, 150, 22], [2, 6, 34, 118], [5, 22, 3, 19, 6, 118, 250, 7], [10, 15, 89, 14, 33, 77, 2, 101, 50, 44]]
but instead it output:
[[10, 15, 89, 14, 33, 77, 2, 101, 50, 44], [10, 15, 89, 14, 33, 77, 2, 101, 50, 44], [10, 15, 89, 14, 33, 77, 2, 101, 50, 44], [10, 15, 89, 14, 33, 77, 2, 101, 50, 44]]
the test file i am reading from (test2.txt) contains:
1 17 3 150 22
2 6 34 118
5 22 3 19 6 118 250 7
10 15 89 14 33 77 2 101 50 44

A: Just change innerlist.clear() to innerlist = new ArrayList<>();.
When you add inner list to outer list, it's add by memory address, so, when you change inner list, it changes in all the place. But when you do innerlist = new ArrayList<>(); you creates new list, and memory adderss was changed, but it's data isn't changed


text:
Q: Input String not in Correct format error in c# DataGridView 'Am getting this error in the following code:
string QtyVal = MatCompDtlDataGridView.CurrentCell.Value.ToString();
decimal Result = (Convert.ToDecimal(QtyVal)) / 999;
if (Result == 0)
{
    MessageBox.Show("Quantity value can not be null");
}

A: You didn't tell us what is the value of QtyVal exactly but you can use Decimal.TryParse method first to check your string is convertable to decimal or not.

Converts the string representation of a number to its Decimal
  equivalent using the specified style and culture-specific format. A
  return value indicates whether the conversion succeeded or failed.

string QtyVal = MatCompDtlDataGridView.CurrentCell.Value.ToString();
decimal d;
if(Decimal.TryParse(QtyVal, NumberStyles.AllowDecimalPoint, CultureInfo.InvariantCulture, out d))
{
   d= (Convert.ToDecimal(QtyVal)) / 999;
}

Its 0000 or 00.00

Both
Convert.ToDecimal(0000)
Convert.ToDecimal(00.00)

works on me. Beucase my CultureInfo.CurrentCulture is tr-TR and NumberFormat.NumberGroupSeparator is . and most probably your culture doesn't have a dot as NumberGroupSeparator but since you didn't tell us what your culture is, we never know.

A: You need to convert (Convert.ToDecimal(QtyVal)) / 999 to a decimal:
 decimal result = (decimal)((Convert.ToDecimal(QtyVal)) / 999);

A: I checked up the value in QtyVal variable which was "" for both 0000 and 00.00 so instead of converting it to decimal, I checked it for null in my if condition and it worked.


text:
Q: Couldn't execute Excel Macro using Python why couldn't I use the script below to run a Macro by Python? Any suggestions would be appreciated.
import xlwings as xw
wb= xw.Book('C:\\myfolder\\path\\myFileName.xlsm')
a = wb.macro("z_ColumnClear.Column_Clear")

A: The idea is from this link.
https://www.excelcise.org/running-excel-vba-from-python/
and this link provides several scenario from users when the script don't work.
Cannot run the macro... the macro may not be available in this workbook
import os
import win32com.client as win32

def run_excel_macro (file_path_no_extention, VBA_macro_name, VBA_procedure_name):
"""
Execute an Excel macro
:param file_path: path to the Excel file holding the macro
:param VBA_module_name: VBA name
:param VBA_procedure_name: name in the sub routine
:param separator_char: the character used by the operating system to separate pathname components
:return: None
"""
xl = win32.Dispatch('Excel.Application')
xl.Application.visible = False

# os.sep is \
try:
    wb = xl.Workbooks.Open(os.path.abspath(file_path_no_extention))
    xl.Application.run("'" + file_path_no_extention.split(sep=os.sep)[-1] + "'" + "!" + VBA_macro_name + "." + VBA_procedure_name)
    wb.Save()
    wb.Close()

except Exception as ex:
    template = "An exception of type {0} occurred. Arguments:\n{1!r}"
    message = template.format(type(ex).__name__, ex.args)
    print(message)

xl.Application.Quit()
del xl
print("Completed: " + str(file_path_no_extention.split(sep=os.sep)[-1]))


text:
Q: How to get checked list and checked button bar value on button ng-click Ionic How to get selected list value and selected button bar value using ionic and Angular Js when i click on fModalHide(1);
$scope.fModalHide = function(index){

// I want to value of selected list and  selected button bar

}

 Location

<ion-list class="mylist"><ion-radio ng-model="choice" value="pass" ng-value="'10'">Delhi</ion-radio>
<ion-radio ng-model="choice" value="pass" ng-value="'20'">Noida</ion-radio>
<ion-radio ng-model="choice" value="pass" ng-value="'30'">Gurgaon</ion-radio>
<ion-radio ng-model="choice" value="pass" ng-value="'40'">Ghaziabad</ion-radio>
<ion-radio ng-model="choice" value="pass" ng-value="'50'">Faridabad</ion-radio>
<ion-radio ng-model="choice" value="pass" ng-value="'60'">Greater Noida</ion-radio>
</ion-list>

First
Second
Third

<button class="button button-full button-small button-positive" ng-click="fModalHide(1)">Create</button>

A: You can create some $scope params for selected list and button:
$scope.selectedList = 20;
$scope.selectedButton = 1;

Then update these value when click button or radio. In function fModalHide you can get these value :
$scope.fModalHide = function(index){
 var selectedList =  $scope.selectedList;
 var selectedButton = $scope.selectedButton;
}


text:
Q: Magento: TypeError: N is not a function I'm trying to add highcharts to magento, but I get following error
TypeError: N is not a function (highcharts.js line 192)

My local.xml
<adminhtml_mymodule_show>
    <reference name="head">
        <action method="addJs"><file>mymodule/js/highcharts.js</file></action>
        <action method="addJs"><file>mymodule/js/my_charts.js</file></action>
    </reference>
</adminhtml_mymodule_show>

my_charts.js
document.observe("dom:loaded", function() {
    var chart = new Highcharts.Chart({

        chart: {
            renderTo: 'container',
            type: 'bar'
        },
        title: {
            text: 'Fruit Consumption'
        },
        xAxis: {
            categories: ['Apples', 'Bananas', 'Oranges']
        },
        yAxis: {
            title: {
                text: 'Fruit eaten'
            }
        },
        series: [{
            name: 'Jane',
            data: [1, 0, 4]},
            {
                name: 'John',
                data: [5, 7, 3]}]
    });
});

My view file

            <?php echo $this->__('Test header') ?>

<?php echo $this->test; ?>

I checked in Firebug and these files are added inside head tag. I tried also add prototype-adapter.js or using standalone framework but it didn't work- I get every time error from title.
Im using magento 1.9 and highcharts 4.0.4.
Thanks for any help

A: Javascript does not recognize N in highchart.js. There may be external js that need to be loaded along with highchart.js.
Make sure jQuery is loaded before highchart.js.


text:
Q: Get Data from subscribe and assign to local variable Angular 6 Service
getProjectEpics(id: string): Observable<any> {
return this.http.get<any>(this.baseUrl + 'getEpics/' + id);
}

Component Angualr 6
projectEpics=[];
getProjectEpics(id: string) {
this.epicService.getProjectEpics(this.id).subscribe(
  next => {
    console.log('RESPONSE', next);
    this.projectEpics = next[0].epics;
    console.log(this.projectEpics); // array has data
  },
  error => {
    this.alertify.error(error);
  }
);
console.log(this.projectEpics); // The array is empty at this log.
}

I am using Angularr 6. I have a method returning observable of type any getProjectEpics in serive which is calling an API. Then in my component i am subscribing to observable method avaliable in service. I successfully get the data from the API and serive but issue is that when i assign the data present in next object to my local array projectEpics and log projectEpics array inside next to console, it displays the array but, when i log it outside next or outside subscribe the projectEpics array is empty and shows no data.

A: This is the way it works when using async calls, you only have access to variables in that scope/thread.  you could use a service / RxJS subjects / ...  to communicate to the outside

A: Observables are asynchronous in nature. Javascript is a single thread environment and any asynchronous tasks it detects are handed off to enclosing environment(Browser,NodeJS etc.,) to execute it in a separate thread. When javascript tries to run your code, it does the following:

*

*Main thread Call to getProjectEpics()

*Checks the statement this.epicService.getProjectEpics() and hands off the execution

*Main thread executes your last console.log() - this happens even before the second step is finished

Array is empty in the last console.log() statement as it won't wait for the API call to finish.
For a detailed explanation, please see https://www.youtube.com/watch?v=8aGhZQkoFbQ


text:
Q: How would one sync text from one form to another? English is not my native language so please bear with me.
What I meant by my question is that how would one make a form (form 2, for example) display what is being typed from form 1, like in real time. I assume the
TextChanged event would be used but what's the next step?

A: Throw an event on form2 and call it from form1
On Form1:
private Form2 frm2;

public Form1()
    {
        InitializeComponent();
    }

    private void button1_Click(object sender, EventArgs e)
    {
        var text = Textbox1.Text;
        frm2.TextChanged.Invoke(text , new EventArgs());
    }

    private void Form1_Load(object sender, EventArgs e)
    {
        frm2 = new Form2();
       frm2.Show();
    }

and on form2:
        public EventHandler TextChanged;

 public Form2()
    {
        InitializeComponent();
        TextChanged += HandleTextChanged;
    }

    private void HandleTextChanged(object sender, EventArgs e)
    {
        label1.Text = (string) sender;

    }

A: I prefer not to let the two forms know each other.
You can instead do something like this:
static class Program
{
  private static Form _form1;
  private static Form _form2;
  public static void Main()
  {
     _form1 = new MyForm();
     _form2 = new MyForm();
     _form1.MyTextbox.OnTextChanged += Form1_MyTextBox_TextChanged;
  }

  private void Form1_MyTextBox_TextChanged(object sender, EventArgs e)
  {
       _form2.MyTextBox.Text = _form1.MyTextbox.Text;
  }
  }
}

public class MyForm : Form
{
  public TextBox MyTextBox {get;set;}
}

A: To keep it simple and OOP-friendly, I would make a property in Form2 and update it in the Form1.TextChanged event:
Form1.cs
public partial class Form1 : Form
{
    private Form2 _form2;

    public Form1()
    {
        InitializeComponent();

        this.textBox1.TextChanged += (sender, e) =>
        {
            _form2.TextBoxValue = textBox1.Text;
        };

        _form2 = new Form2();
        _form2.Show();
    }
}

Form2.cs
public partial class Form2 : Form
{
    public string TextBoxValue
    {
        get => textBox1.Text;
        set => textBox1.Text = value;
    }

    public Form2()
    {
        InitializeComponent();
    }
}

Note that you would need to change the Form1 and Form2 names to the actual form class names in your application (as well as the textBox1 name).
Edit:
As requested in the comments, if you want changes to either textbox to be updated in both forms, you need to add the TextBoxValue property to both  forms, and make the event handlers in both forms change that property. I've also cleaned up the code a little.
Form1.cs
public partial class Form1 : Form
{
    private Form2 _form2;

    public string TextBoxValue
    {
        get => textBox1.Text;
        set => textBox1.Text = value;
    }

    public Form1()
    {
        InitializeComponent();

        this.textBox1.TextChanged += (sender, e) =>
        {
            _form2.TextBoxValue = textBox1.Text;
        };

        _form2 = new Form2();
        _form2.Show();
    }
}

Form2.cs
public partial class Form2 : Form
{
    private Form1 _form1;

    public string TextBoxValue
    {
        get => textBox1.Text;
        set => textBox1.Text = value;
    }

    public Form2()
    {
        InitializeComponent();

        this.textBox1.TextChanged += (sender, e) =>
        {
            _form1.TextBoxValue = textBox1.Text;
        };

        this.Shown += (sender, e) =>
        {
            _form1 = (Form1)Application.OpenForms["Form1"];
        };
    }
}


text:
Q: MySQL - Order query and display one random row at the top I have a table that looks like:
ID  |  TICKET PRICE  |  VIP
----------------------------
 1  |     $45.00     |  1
 2  |     $40.00     |  1
 3  |     $20.00     |  0
 4  |     $65.00     |  0
 5  |     $45.00     |  1

I need to query this table to order all rows by Price, but always show one random row which has a VIP=1 at the top. So for example, the query should return:
ID  |  TICKET PRICE  |  VIP
----------------------------
2  |     $40.00     |  1
3  |     $20.00     |  0
1  |     $45.00     |  1
5  |     $45.00     |  1
4  |     $65.00     |  0

And when you refresh the page, row ID 5 may then become the first row, because it has a VIP=1.
I currently have my query looking like:
(SELECT * FROM tickets WHERE VIP=1 ORDER BY rand() LIMIT 1)
UNION
(SELECT * FROM tickets WHERE VIP=0 ORDER BY ticket_price ASC)

This issue with this is that it will only display one VIP row. How would I query this data properly?

A: Use order by.  Here is one method:
select t.*
from (select t.*, (@rn := @rn + 1) as seqnum
      from tickets t cross join
           (select @rn := 0) params
      order by vip desc, rand()
     ) t
order by (seqnum = 1) desc, price asc;

This uses the subquery to identify the one row to keep at the top.  Then it uses this information for ordering in the outer query.
If your rows have a unique identifier, you could also do:
select t.*
from tickets t cross join
     (select id from tickets where vip = 1 order by rand() limit 1) as t1
order by (t.id = t1.id) desc, price asc;


text:
Q: Magento2 getting 'Constr is not a constructor' error for custom theme I am not sure what this error is and if it is affecting anthing, however this is coming into my console:
layout.js:64 Uncaught TypeError: Constr is not a constructor (layout.js line 64)

A: This is a bug in the agreement-validator JS.
(vendor/magento/js/module-checkout-agreements/view/frontend/web/js/view/agreement-validation.js)
Here you see: //return Component.extend({});
This should be uncommented because it breaks the second parameter of the fire function of jquery. Not sure if it breaks something else though, but the result of this, is this error and in some cases when the terms and agreements are set to manually, the order button will not work.
Until this is fixed by Magento, you can create an override for this JS in you own theme folder. To do this, add the following file:
app/design/frontend/<ThemeNameSpace>/<Theme>/Magento_CheckoutAgreements/web/js/view/agreement-validation.js and paste the contents of vendor/magento/js/module-checkout-agreements/view/frontend/web/js/view/agreement-validation.js into it.
Uncomment the return and redeploy the static content.

A: For anyone who might encounter this problem as well: I had the same problem with my custom JavaScript components. It turned out a small typo in my JS files was causing the problem. Instead of define() I used require() on top. So to wrap it all up, here's a boilerplate for a custom JavaScript component:
define([
  'uiComponent'
], function(
  uiComponent
) {
  "use strict";

  /**
   * Return the UI Component
   */
  return uiComponent.extend({
    /**
     * Initialization method
     */
    initialize: function () {
      this._super();
    }
  });
});

A: I have faced the same issue. The cause of the issue i have declared same js file location which is already used in Core file.
For example, I have tried to restructure the order summary totals blocks by using my custom js file like,
"components": {
     "block-totals": {
              "component": "Magento_Checkout/js/summary/totals",
                  }
             }

But in the same location already a totals.js exist in magento-checkout/frontend/web/js/summary/totals.js.
Then I have renamed the file name like,
"component": "Magento_Checkout/js/summary/showtotals",

Now I don't have any errors !! and my order summary totals block overwritten.

A: For me, I was using a Magento Js Mixin and required the template adjusted slightly differently as described in the Magento docs here:
https://devdocs.magento.com/guides/v2.3/javascript-dev-guide/javascript/js_mixins.html

A: After upgrading a Magento installation from 2.1.x to 2.3.x, very same JS error was triggered by a custom JS rewrite (of a Magento core RequireJS alias) requiring an update.
Next changes resolved the JS error in my case:
File: Vendor/Module/view/frontend/requirejs-config.js
var config = {
-    paths: {
-        alias: 'Vendor_Module/js/complex/path/amd-module',
+    map: {
+        '*' : {
+            alias: 'Vendor_Module/js/complex/path/amd-module'
+        }
     },
     config: {
         mixins: {

Having the require JS alias rewrite moved to the correct config made the Uncaught TypeError: Constr is not a constructor error disappear.


text:
Q: How to save object of class with dict inside to set I want to create a class, objects of it should store a dict and put it into an object of another class which store objects of first class as set.
I'm parsing xml model of DB, domains for now, in format like this
domain name="BinData" type="BLOB" align="L"/

and want to have set of all domains and each attribute of domain as pair key:value.
I know that you can't do it just putting dict to set. But maybe I can handle this in classes?
What I have tried:
from xml.dom.minidom import parse
class schema:

    def __init__(self,xdb_file):
        self.xdb_file = parse(xdb_file)
        self.domains = self.get_domains()

    def __eq__(self, other):
        if (self.domains == other.domains):
            return True
        else:
            return False

    def get_domains(self):
        domains_set = set()
        domains = self.xdb_file.getElementsByTagName("domain")
        for domain_description in domains:
            domains_set.add(domain(domain_description.attributes.items()))
        return domains_set

class domain:
    def __init__(self,items):
        self.description = dict()
        for item in items:
            self.description[item[0]]=item[1]
        self.description = (self.description)
    def description(self):
        return self.description

    def __eq__(self, other):
        is_Equal = True
        if (set.difference(self.description,other.description)):
            return True
        return False

In the end, it shows mistake about unhashable type domain.


text:
Q: Whats the difference between 127.0.0.1 and ::1 For couple day I was fighting to set up apache installed from Homebrew on OSX 10.10 . For some reason everything was working but not the local domains that I was trying to setup via hosts file. No matter what I was doing only http://localhost was available trough browser. And then I've changed one thing.
Originally in /etc/hosts I was putting this line to set local domain:
127.0.0.1  imac.dev

And that did not work, but then I changed it to:
::1  imac.dev

which is how localhost was set up in hosts files and it works!
Can anyone explain me why?

A: The first one is an IPv4 address and the other signifies and IPv6 local address.
Loopback address for ipv4
 127.0.0.1  imac.dev

Loopback local address for ipv6
::1  imac.dev

In most current OSes IPv6 if enabled, takes precedence over ipv4 so that might be the reason you were having that issue. Similarly I, had to use IPv6 IP address in my DNS record for SPF because GMail was looking for that too. So whether we like it or not, it's being favored and will replace IPv4 eventually.
https://en.wikipedia.org/wiki/Localhost


text:
Q: TreeView ScrollBar bug I have a treeview in the winform application....
I added a node to it and reduced the width of the treeview such that the horizontal scroll
comes...
then i deleted the added node.
When i increase the treeview width the scroll comes...
But the scroll should not come..
What is the solution for this condition?

A: Use a non-standard 3rd party treeview. The default one has bugs far worse than this.

A: Sounds like a threading issue. Does your code contain any Application.DoEvents()? Do you update the TreeView from the GUI thread? Please show some code.


text:
Q: Throttles, Quotas and Pricing of Azure IoT Hub After reading about the throttles and quotas of Azure IoT Hub, I am struggling to understand how an IoT Hub can support millions of devices (Microsoft's promise). Maybe you guys can help. These are my thoughts so far:
Quote from Microsoft doc
Device connections:

120/sec/unit (for S2), 12/sec/unit (for S1).  Minimum of 100/sec. For
  example, two S1 units is 2*12 = 24/sec, but you will have at least
  100/sec across your units. With nine S1 units you have 108/sec (9*12)
  across your units.

12/sec/unit - does it mean that if I only have one scaling unit I can have max. 12 simultaneous connections at the same time?
Or does it mean that I can open max. 12 new connection per second?
What does "Minimum of 100/sec" mean?
IoT Hub supports AMQP 1.0.
My understanding was that with this protocol I can have a permanently open device <--> cloud connection to be able to send/receive messages "in real time". It would not be possible to support more than 12 devices with a single scaling unit if only 12 simultaneous connections were allowed.

A: You are correct in the understanding that the AMQP connection is assumed to remain active in order to achieve "real-time" delivery of cloud-to-device messages.
The throttle you are referring to governs the rate at which new devices can connect to an IoT hub, and not the maximum number of simultaneously connected devices. The throttle is dependent on the number of units that are provisioned for the hub.
For instance, if you buy a single S1 unit, you get a throttle of 100 connections per sec. This means that in order to connect 100.000 devices it would take at least 1000 secs ~ 16mins. You can, however, have as many simultaneously connected devices as you have in your device identity registry.
Usually apps with many devices buy more units, so the throttle increases proportionally (120 connections/sec/unit for S2 units, 12 conn/sec/unit for S1). In case of S1, to accommodate for spikes we never impose a throttle of less than 100 connections/sec, this means that if you buy up to 8 S1 units, you always get 100 connections/sec, when you have 9 you will get 108 connections/sec.


text:
Q: ansible delegate_to variable undefined I have a problem where I'm trying to delegate facts to a group of hosts. I have a master node generating a value, and I want to ensure my group of "workers" has access to that value (rather than targeting the master via hostname).
ansible 2.7.9
vagrant 2.2.4
VagrantFile
ansible_groups = {
    "local" => [],
    "swarm" => [],
    "swarm-master-first" => [],
    "swarm-master" => [],
    "swarm-worker" => []
  }

  (1..num_masters).each do |i|
    ansible_groups["local"].push("swarm_master#{i}")
    ansible_groups["swarm"].push("swarm_master#{i}")
    if i == 1
      ansible_groups["swarm-master-first"].push("swarm_master#{i}")
    end
    ansible_groups["swarm-master"].push("swarm_master#{i}")
  end
  (1..num_workers).each do |i|
    ansible_groups["local"].push("swarm_worker#{i}")
    ansible_groups["swarm"].push("swarm_worker#{i}")
    ansible_groups["swarm-worker"].push("swarm_worker#{i}")
  end

  (1..num_masters).each do |i|
    config.vm.define "swarm_master#{i}" do |swarm_master|
      swarm_master.vm.network "private_network", ip: "192.168.50.1#{i}"
      swarm_master.vm.hostname = "swarmmaster#{i}"
      swarm_master.vm.provider :virtualbox do |vb|
          vb.name = "swarm-master#{i}"
      end
      swarm_master.vm.provision "ansible" do |ansible|
        ansible.playbook = "site.yml"
        ansible.become = true
        ansible.become_user = "root"
        ansible.groups = ansible_groups
      end
    end
  end

  (1..num_workers).each do |i|
    config.vm.define "swarm_worker#{i}" do |node|
      node.vm.network "private_network", ip: "192.168.50.2#{i}"
      node.vm.hostname = "swarmworker#{i}"
      node.vm.provider :virtualbox do |vb|
          vb.name = "swarm-worker#{i}"
      end
      node.vm.provision "ansible" do |ansible|
        ansible.playbook = "site.yml"
        ansible.become = true
        ansible.become_user = "root"
        ansible.groups = ansible_groups
      end
    end
  end
end

resulting in an inventory:
# Generated by Vagrant

swarm_master1 ansible_host=127.0.0.1 ansible_port=2222 ansible_user='vagrant' ansible_ssh_private_key_file='/Users/dmcminn/.vagrant.d/insecure_private_key'
swarm_worker1 ansible_host=127.0.0.1 ansible_port=2200 ansible_user='vagrant' ansible_ssh_private_key_file='/Users/dmcminn/.vagrant.d/insecure_private_key'

[local]
swarm_master1
swarm_worker1

[swarm]
swarm_master1
swarm_worker1

[swarm-master-first]
swarm_master1

[swarm-master]
swarm_master1

[swarm-worker]
swarm_worker1

playbook.yml
- hosts: swarm-master-first
  tasks:
    - set_fact:
        swarm_token: "TEST"
      delegate_to: "{{ item }}"
      delegate_facts: True
      with_items: "{{ groups['swarm-worker'] }}"
    #- debug: var=swarm_token

- hosts: swarm-worker
  gather_facts: yes
  tasks:
    - debug: var=swarm_token

output
PLAY [swarm-master-first] ******************************************************

TASK [set_fact] ****************************************************************
ok: [swarm_master1 -> 127.0.0.1] => (item=swarm_worker1)

...

PLAY [swarm-worker] ************************************************************

TASK [Gathering Facts] *********************************************************
ok: [swarm_worker1]

TASK [debug] *******************************************************************
ok: [swarm_worker1] => {
    "swarm_token": "VARIABLE IS NOT DEFINED!"
}

What am I doing wrong here?
Thanks

A: The scope of a variable is the playbook. Scope of the variable "swarm_token" is the 1st playbook. 2nd playbook knows nothing about "swarm_token".