text:
Q: How to use VariableRef as indices in Julia JuMP In Julia when I do:
model = Model();
set_optimizer(model, Cbc.Optimizer);

N=11;

model = Model();
set_optimizer(model, Cbc.Optimizer);
@variable(model, X[1:N,1:N,1:N], Bin);
@variable(model, 1<=K<=10, Int);

for k in K
    @constraint(model, (sum(X[1,j,k] for j= 1:N)) ==1 )
end

I get this error:

ArgumentError: invalid index: K of type VariableRef

Because I used a variable reference(k) as index for a vector (X).
How could I fix that?

A: If you want to K to interact with other variables you need to make it a binary vector with the sum of 1 and then use multiplication for modelling the interaction.
@variable(model, K[1:10], Bin);
@constraint(model, sum(K) == 1)

Now I am not exactly shure what you want to accomplish. If you want to turn off and on equations depending on the value of K this would look like this:
@constraint(model,con[k in 1:10], sum(X[1,j,k] for j= 1:N)*K[k] == K[k] )

This however makes the model non-linear and you would need to use a non-linear solver for it.
Depending on your use case having sums simply up to 1 could be enough (and this yields a model much easier for solvers but might your business needs or not):
@constraint(model,con[k in 1:10], sum(X[1,j,k] for j= 1:N) == K[k] )


text:
Q: Apple Mail not working properly Since installing Catalina on both my laptop and desktop I can only receive emails on the laptop - what do I have to do to overcome this problem?

A: Apple Mail has a wonderful connection doctor.
I would open it and see what specific error it finds and then work to solve it from the wizard steps and help that the connection doctor provides for your specific setup and mail provider.
Once you've done that or if you can't solve it - then you can ask a follow on question or reach out to that mail vendor's support with a very specific error condition and not just "mail doesn't work"

*

*Click the Window menu

*Click the Connection Doctor item

*Follow the results for any light that's not green

A: Probably it's because of using POP3 as incoming mail server, switch to IMAP to insure that the message will arrive to all of your devices not just a single device.
Check this question.

POP3 and IMAP are two different protocols (methods) used to access
  email.
Of the two, IMAP is the better options and the recommended option when
  you need to check your emails from multiple devices, such as a work
  laptop, a home computer, or a tablet, smartphone, or other mobile
  device. Tap into your synced (updated) account from any device with
  IMAP.
POP3 downloads email from a server to a single computer, then deletes
  it from the server. Because your messages get downloaded to a single
  computer or device and then deleted from the server, it can appear
  that mail is missing or disappearing from your Inbox if you try to
  check your mail from a different computer.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Selenium MoveToElement Action is not working On performing MoveToElement Action,Mouse hasnt moved to the element location.Please find the below code.
    Actions action = new Actions(driver);
    action.MoveToElement(element);
    action.Build().Perform();

A: You can try the below code:
 IWebElement element = driver.FindElement(By.Id("Login_Id"));

        Actions action = new Actions(driver);
        action.MoveToElement(element);
        action.Build().Perform();


text:
Q: TeamCity Professional License I'm considering TeamCity for CI and not sure whether I can use Professional License (which is free) for commercial application?
From their license page https://www.jetbrains.com/teamcity/buy/ , seem like the Professional License only restricted in number of build configuration and build agents, doesn't mention anything about commercial usage.
In their FAQ https://sales.jetbrains.com/hc/en-gb, they are talking about commercial license and personal license, not mentioning professional license and enterprise license, which makes me even more confused. Is the FAQ page outdated?
My application is .NET application, hosted in Github (private). We intend to setup TeamCity in AWS as build server

A: According to the licensing (section 4b: https://www.jetbrains.com/teamcity/buy/license.html), there is no restriction for corporations.
Note: In my division we currently use the free version, and we didn't find any difficulties. We are still planning to upgrade soon because of the limited build configurations.

A: TeamCity can be used for commercial purposes, but is restricted to 20 build configurations and 3 build agents. If you want to use more build configurations or agents, then you need to upgrade to a paid licence.
However, if you just need additional build agents, these can be bought separately.

A: From TeamCity 2017.2 onwards, the professional version (free) includes 100 build configurations, which is a significant increase on the previous versions that were limited to 20. It still has a limit of 3 build agents.
Further info here https://confluence.jetbrains.com/display/TCD10/Licensing+Policy


text:
Q: Retrieve data from firebase in react native app I am new to React native. I want to show the text which is fetched from firebase database on-app screen as text.
I have tried to print on console and alert and it is showing successfully but not on app screen.firebase data console print alert box
import React,{Component} from 'react';
import { View, Text,} from 'react-native';
import * as firebase from 'firebase';

export default class ListItem extends Component {

  state= {
      items: []
   }

    componentWillMount(){
        var firebaseConfig = {
          apiKey: "***",
          authDomain: "***",
          databaseURL: "***",
          projectId: "***",
          storageBucket: "***",
          messagingSenderId: "***",
          appId: "***",
          measurementId: "***"
        };

        firebase.initializeApp(firebaseConfig);

        var ref = firebase.database().ref('/14/info');

        ref.on("value", function(snapshot) {

        const userItem = snapshot.val();
        let items = Object.values(userItem);

        });
      }

render() {
        return (
            <View style= {{justifyContent: 'center'}}>

             <Text>{this.state.items}</Text>
            </View>
        )
    }
}

A: Data is loaded from Firebase (and pretty much any modern web API) asynchronously, since it may take some time to get the result. This means that when your app is rendered, the data isn't available yet. For this reason you need to tell React to re-render when the data is available, which you do by calling setState().
let self = this;
ref.on("value", function(snapshot) {
    const userItem = snapshot.val();
    let items = Object.values(userItem);
    self.setState({ items: items });
});

Alternatively you can use the fat arrow notation, to make this a bit simpler:
ref.on("value", (snapshot) => {
    const userItem = snapshot.val();
    let items = Object.values(userItem);
    this.setState({ items: items });
});

I highly recommend reading up on how to manage state in a React application before continuing, as this behavior is quite crucial to efficiently building React applications.


text:
Q: jquery selector won't work on controls loaded with asp:UpdatePanel I have a legacy code that uses asp.net updatepanel to load some pagination items. basically it will have some text boxes and some text. i need to check whether any checkbox is selected on click of a button. The jquery code that i have works for the initial load but when the ajax load happens, the items loaded are no longer in the initial DOM so will not be considered for any jquery activities. we can use live or deligate for events but if i have to uses the control as a selector that won't help.
The code to check whether the checkbox is selected is strait forward but my concern is how do i rebind it after ajax call?
if ($('input:checked').length > 0) {
       alert('checked');
   }
   else {
          alert("not selected");
   }

Any ideas??

A: If you change the initial bind (or click or whatever, click is just a wrapper for bind) to either live or (better) delegate, they will survive updates to the underlying DOM elements.
Sadly the api.jquery.com site is having issues today, so those links won't be hyper-useful right now. Basically, though, if you have:
$("some_selector").click(function() { ... });

You can change it to
$("some_selector").live("click", function() { ... });

or (better)
$("some_parent_element_selector").delegate("selector_for_descendants", "click", function() { ... });

What happens there is that jQuery watches for the event on the parent element (or "body" in the case of live) and then checks to see whether the originating element matches the selector you gave. If so, it calls your handler as though it had been hooked on the actual element. Since the handler is on an ancestor element, not the actual descendant element, you can swap those out at will. This is sometimes called "event delegation" (hence the function delegate).
Example:
HTML:

  This is the container.

    This is the descendant of the container. Click me.

JavaScript:
$("#container").delegate(".foo", "click", function() {
  $("
Element with class 'foo' clicked!
").appendTo(document.body);
});

Live copy

A: jQuery $(document).ready and UpdatePanels?

A: There is a solution on codeplex: http://updatepanelplugin.codeplex.com/discussions/70810


text:
Q: How can i show django-filter results in another view, assuming i have a search box in my home page and a results page to display the results? I have been using django-filters in many of my projects where the search form is on the same page as the list of results and that works just fine, but now im faced by a scenario where i have a search box in my home page and a results page somewhere else, how can i pass the filtered results to the view of my results page?

A: You could go a couple of different ways.
One idea is to just render a different template if there is search data present in the request.
Seeing as you didn't post any of your own code, we don't know how you have things named or set-up so here is a quick sketch of the kind of thing I mean.
class SomeView(View):
    template_name = 'some_view.html'
    results_template_name = 'some_view_results.html'

    def get(self, request, *args, **kwargs):
        if not request.GET.get('q'):
            return render(request, self.template_name)
        results = SearchFilter(request.GET)
        context = {'results': results}
        return render(request, self.results_template_name, context)

This would be one of the simplest solutions. You could even get away with using one template and just conditionally dispatch some rendering over whether or not results is in the context.
Another would be to do a full redirect and pass along whatever data you need as kwargs to whatever view you are calling. But that is kind of messy and unnecessary.
The best solution is to wire up a new ResultsView endpoint, move the filtering to that view, and put a reference that URL into the form node on the template. Which would require something like this.
<form method="GET" action="{% url search %}">
  <input type="text" id="search" name="q" placeholder="Search">
</form>

Assuming that you have named ResultsView as search in your URL config.


text:
Q: "/1/2/3/".split("/") It's too hot & I'm probably being retarded.
>>> "/1/2/3/".split("/")
['', '1', '2', '3','']

Whats with the empty elements at the start and end?
Edit: Thanks all, im putting this down to heat induced brain failure. The docs aren't quite the clearest though, from http://docs.python.org/library/stdtypes.html
"Return a list of the words in the string, using sep as the delimiter string"

Is there a word before the first, or after the last "/"?

A: As JLWarlow says, you have an extra '/' in the string. Here's another example:
>>> "//2//3".split('/')
['', '', '2', '', '3']

A: Slashes are separators, so there are empty elements before the first and after the last.

A: Compare with:
"1/2/3".split("/")

Empty elements are still elements.
You could use strip('/') to trim the delimiter from the beginning/end of your string.

A: you're splitting on /. You have 4 /, so, the list returned will have 5 elements.

A: That is exactly what I would expect, but we are all different :)
What would you expect from: : "1,,2,3".split(",") ?

A: You can use strip() to get rid of the leading and trailing fields... Then call split() as before.

A: [x for x in "//1///2/3///".split("/") if x != ""]


text:
Q: Removing datapoints outside interval for both axes of a plot I am trying to plot some data using matplotlib.
import matplotlib.pyplot as plt

x_data = np.arange(0,100)
y_data = np.random.randint(11, size=(100,))
plt.plot(x_data, y_data)
plt.show

This, of course, works fine. However, I would like to remove the data that is outside a given interval (e.g. 4 < y_data < 6). For the y_data, this is done by
y_data_2 = [x for x in y_data if 4 <= x <= 6]

However, since the first dimensions are no longer equal, you are no longer able to plot y_data_2 vs. x_data. If you try to
plt.plot(x_data, y_data_2)

you will, of course, get an error stating that
ValueError: x and y must have same first dimension, but have shapes (100,) and (35,)

My question is thus twofold: is there a simple way for me to remove the equivalent datapoints in x_data? Also, is there a way I could find the indices of the points that are to be removed?
Thank you.

A: You can use masking together with indexing. Here you create a mask to capture values y values which lie between 4 and 6. You then apply this conditional mask to your x_data and y_data to get the corresponding values. This way you don't need any for loop or list comprehensions.
x_data = np.arange(0,100)
y_data = np.random.randint(11, size=(100,))
mask = (y_data>=4) & (y_data<=6)

plt.plot(x_data[mask], y_data[mask], 'bo')

A: First, you can get the index of y_data_2 in y_data, and then get the subarray x_data_2 of x_data. Then, plot the x_data_2, y_data_2.
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd

x_data = np.arange(0,100)
y_data = np.random.randint(11, size=(100,))
y = pd.Series(y_data)

y_data_2 = [x for x in y_data if 4 <= x <= 6]
index = y[y.isin(y_data_2)].index
print(index)
x_data_2 = x_data[index]
plt.plot(x_data, y_data)
plt.scatter(x_data_2, y_data_2)
plt.show()


text:
Q: accepts_nested_attrinutes_for rails3.1rc4 I use accepts_nested_attributes_for in a model but my child form isn't saved in the database?
I am building a nested form almost in the same way as in episode 196 / 197 from Ryan Bates railscasts. I have a parent question form and as a child the answer form:
models/question.rb
class Question < ActiveRecord::Base
  belongs_to :user
  has_many :answers, :dependent => :destroy
  accepts_nested_attributes_for :answers, :reject_if => lambda { |a| a[:text].blank? },
                                :allow_destroy => true

  validates :content, :presence => true
end

models/answer.rb
class Answer < ActiveRecord::Base
    belongs_to :question
  belongs_to :user
end

controllers/questions_controller.rb
class QuestionsController < ApplicationController

  before_filter :authenticate_user!

  def index
    setup_questions
  end

  def create
    @question = Question.new(params[:question])

    #this is to get every id_key from the user into the params of the answer
    params[:question][:answers_attributes].keys.each {|key| params[:question][:answers_attributes][key][:user_id] = current_user.id }

    @question.user_id = current_user.id

    if @question.save
      redirect_to questions_path, :notice => "Successfully created question."
    else
      setup_questions
      render :index
    end
  end

  def edit
        @question = Question.find(params[:id])
  end

  def update
     @question = Question.find(params[:id])
      respond_to do |format|
        if @question.update_attributes(params[:question])
          format.html { redirect_to(@question, :notice => 'Question was successfully updated.') }
          format.xml  { head :ok }
        else
          format.html { render :action => "edit" }
          format.xml  { render :xml => @question.errors, :status => :unprocessable_entity }
        end
      end
  end

  def show
    @question = Question.find(params[:id])
  end

  def destroy
    @question = Question.find(params[:id])
    #authorize! :destroy, @question
    @question.destroy
    redirect_to questions_path, :notice => "Successfully deleted question: #{@question.content}."
  end

  private

  def setup_questions
    @questions = Question.all
    @question ||= Question.new
    @question.answers.build #to build the answers form
  end
end

views/question/_form.html.erb
<%= form_for(@question) do |f| %>

  <% if @question.errors.any? %>

<%= pluralize(@question.errors.count, "error") %> prohibited this question from being saved:

      <% @question.errors.full_messages.each do |msg| %>

<%= msg %>

      <% end %>

  <% end %>

    <%= f.label :content, "Question" %>

    <%= f.text_field :content, :placeholder => "type your question here.." %>

        <%= f.fields_for :answers do |builder| %>
            <%= builder.label :content, "Possible answer" %>

            <%= builder.text_field :content, :placeholder => "type an optional answer.." %>
        <% end %>

    <%= f.submit %>

<% end %>

So now the big question... Why doesn't it save anything from the answer field to the database? I thought one create action at the parent (question) should be enough and that the "accepts_nested_attributes_for" should take care of it's child(s).
Regards,
Thijs

A: 1 Remove this line from controller
params[:question][:answers_attributes].keys.each {|key| params[:question][:answers_attributes][key][:user_id] = current_user.id }

2 add this into your view

    <%= f.fields_for :answers do |builder| %>
      <% builder.object.user = current_user %>
      <%= builder.label :content, "Possible answer" %>

      <%= builder.text_field :content, :placeholder => "type an optional answer.." %>
      <%= builder.hidden_field, :user_id %>
    <% end %>


text:
Q: UICollectionView layout issue on iOS7 I am developing an app that supports iOS7 and iOS8. On iOS8 running on an iPad 2 the app runs fine. No issues. However on iOS7 there is an issue with one of my UICollectionView's which I just can't seem to fix. I am using AutoLayout and out of desperation, have tried springs and struts which made no difference.
So this is how the cell looks at 320 width:

Here are the AutoLayout constraints applied to the UICollectionView

And here is what happens when its on an iPad with iOS 7.1

Whatever I try I always get the same result on iOS7. On iOS8 with an iPad the cell displayed perfectly fine.
Not sure what is going on here.

A: Right, so I found the answer incase anyone else suffers the same issue.
The accepted answer from this SO question: Auto layout constraints issue on iOS7 in UITableViewCell
Actually helped me.
Here is what i did in my UICollectionViewCell's subclass:
    -(id)initWithCoder:(NSCoder *)aDecoder
{
    self = [super initWithCoder:aDecoder];

    if (self){

        self.contentView.autoresizingMask = UIViewAutoresizingFlexibleHeight|UIViewAutoresizingFlexibleWidth;

            return self;
    }
    return nil;
}

This solved the issue for me.


text:
Q: how do I set up my web app dev environment for easy production transition? I'm about to start developing a web app. It will be hosted on dedicated servers in the cloud when its time to go live. Currently my development environment is my shared hosting account. I'm assuming it would be more difficult (and pointless) to mimic a shared hosting type of environment because of its heavy customization, restrictions and intended purpose (serve hundreds of sites instead of one).
Considering that I will have complete/root control of the production server(s), should I set up my development environment on a physical or virtual server instead? If so, do I simply convert/image/import my VirtualBox/VMware virtual dev machine (or P2V) to the virtual machine in the cloud or would I have to manually mimic the environment (i.e., install the same exact OS, software, libraries, components, patches, etc.) of the dev machine (and copy/SVN the site & DB over)? If not, what is the best practice for setting up dev servers for easy live transition?

A: Under the assumption that we are talking whole machines (whether physical or virtual) for the production environment (rather than, say Google App Engine), my best practice is thus:
Take the extra effort to create proper packaging for your software. For example with Java development targeted for RedHat, use/write Maven tools that create RPMs. For your database, for all changes and include them in the RPM and either have them apply automatically or create a small tool that applies them for you. Essentially, you are done when a server can be installed/upgraded with a single command. Yes, this means including config files tailored to that system.
This is a bit of extra work, but it is so worth it in the long run.
Once you have properly packaged your software, the question of dev/staging/demo servers isn't so important anymore, because you can always build another. And with proper installers, you know exactly what changes you need to do to a machine to get it working properly.
Don't bother with migrating virtual machines around: you would need to change lots of configuration parameters on migration anyway.
If you tell us a bit more of OS/dev tools concerned, I may have some more specific tips for you.
EDIT: PHP/MySQL. Assuming this is LAMP.
Create a deb/rpm with your PHP code that depends on the various Apache, mysql, mod_ssl, php packages that you need. Look at other PHP applications packages on that platform for inspiration. Typically, you don't want to have a package dependency on a database, because the db may be on a different box.
Your package should prolly contain two SQL scripts (that comes from your source repo): one that initializes a new database, including grant statements, loading stored procedures, creating indices, etc and one that loads some demo data that can be used on test systems to get up and running quickly. Also, successive versions of your packages may contain patch scripts that upgrade the database.
Most modern Linux distributions frown on overwriting files from other packages, so try to avoid it if possible.
EDIT2: How to build a Debian package from just a directory tree.
You need a directory tree that looks like the installation you want to make (lets say in a dir called build), and you need some control files:
controlfiles/control:
Package: coolapp
Version: 1.0.0-2
Architecture: i386
Maintainer: Skunkworks Dept <bittrance@example.com>
Depends: apache2 (>= 2.2.16)
Section: contrib/libs
Priority: optional
Description: My Cool App
 It's going to revolutionize, yo!

controlfiles/conffiles:
etc/coolapp/settings.conf

Given these two, use this script called mkdeb:
#!/bin/bash

CONTROLDIR=$1
shift
SOURCEDIR=$1
shift
INCLUDES=$*
BUILD=/var/tmp/mkdeb

CONTROLFILE=$CONTROLDIR/control
PKGNAME=$(grep -E '^Package:' $CONTROLFILE | awk '{ print $2 }')
PKGVERSION=$(grep -E '^Version:' $CONTROLFILE | awk '{ print $2 }')
PKGARCH=$(grep -E '^Architecture:' $CONTROLFILE | awk '{ print $2 }')

FILENAME=$PWD/${PKGNAME}_${PKGVERSION}_${PKGARCH}.deb

rm -rf $BUILD && install -d $BUILD
tar -C $SOURCEDIR -zcf $BUILD/data.tar.gz $INCLUDES
# Proper debian packages have md5 sums for all their files
(cd $SOURCEDIR && find $INCLUDES -type f | xargs md5sum > $BUILD/md5sums)
metadata=
for f in control prerm postrm preinst postinst templates conffiles ; do
    if [ -f $CONTROLDIR/$f ] ; then
        cp $CONTROLDIR/$f $BUILD
        chmod a+x $BUILD/$f
        metadata="$metadata $f"
    fi
done

# Metadata and stuff
tar -C $BUILD -zcf $BUILD/control.tar.gz md5sums $metadata
echo 2.0 > $BUILD/debian-binary
(cd $BUILD && ar rc $FILENAME debian-binary control.tar.gz data.tar.gz)

Like so:
mkdeb ./controlfiles ./build .

A: First and foremost, keep a running log of any modifications that you do to your server, this is called a runbook. Some things to manually keep track of:

*

*Version levels of important packages. Language, libraries, and database packages.

*Locations of all important directories and paths.

*List any external dependancies.

Second, use scripts to define all of your environmental variables and system setup. Failing this, at least keep notes.
Third, keep as much (if not everything) under revision control, including your runbook, and environmental scripts. You should be able to deploy a new instance of your server from just your SVN repository.
Fourth, keep backups, keep, really, really good backups. Test them.
The rest is very specific to your deployment. Setting up on a virtual or physical server is entirely dependent on your IO (input/output) load across your network, disk, and memory. This can only be quantified over time, so graph as much as you can.
Above all, make things modular and repeatable.
(Thanks @bittrance for the comment!)
Here's a few examples of "use a script to setup your environmental variables."

A: *

*Keep the underlying distro of dev and live the same.   For instance, if live is going to be ubuntu 10.10 ec2 instances, than dev should be an ubuntu 10.10 environment, even if that means running a virtual machine on your (mac) laptop.  Even better is to have it be the same as live, such that even network connectivity issues are equalized.

*Configure those two servers/environments using a config management (puppet/chef) tool so that its self documenting and reproducible.  These work just as well, if anything easier, on a single server.   You could start out bone dumb simple with one giant recipe that just has some if-dev/else-live hacks.   Keep these recipes in your version control system along with your code.

*keep your code somewhere separate in version control, could be local like a trac/svnserve setup or could be hosted like github. Just separate, somewhere that is not at all involved in end-user service. Write a very simple script to deploy your application from that version control system.  It can be just a shell script with 3 or 4 lines of bash mashed together, start simple, keep it in version control itself, and iterate as needed.
If you do all that you'll have a dev environment that matches the live environment in a way that you can prove it with a diff.  You also get an simple deployment workflow that makes it easy to iterate super fast, and you'll have all the groundwork in place to build matching servers and scale out when needed.

A: Using your shared account for dev work is probably the worst way to go, as it's unlikely to be anywhere near the same configuration as the final live server(s)e. I suggest setting up a local machine to be as close a clone of your final target configuration as possible. In regard to physical vs virtual, if virtual provides adequate performance for your needs there is no reason to go physical.
If you create a local clone of your target machine, when the time comes it's literally only a matter of copying the files over, ensuring of course that permissions are set correctly on the target. Then do a dump of your database(s) and load them on the target. It just doesn't get much easier than that.


text:
Q: ASP.NET page change causes an object array in Session to be unable to cast to it's own type? I am storing an array of a custom serializable class in session on my site.  When a page on the site changes, suddenly it renders them invalid, and tells me that it can't cast the type to it's own type.  I assume the class version numbers are changing or something?!
I'd appreciate avoiding the "don't use session" answers, unless it's a really simple solution.  I'm not trying to redesign this whole process.
Unable to cast object of type 'ShipmentPackages[]' to type 'ShipmentPackages[]'.

Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

Exception Details: System.InvalidCastException: Unable to cast object of type 'ShipmentPackages[]' to type 'ShipmentPackages[]'.

Source Error:

Line 21:         Else
Line 22:             If Not Session("ShipmentList") Is Nothing Then
Line 23:                 ShipmentList = DirectCast(Session("ShipmentList"), ShipmentPackages()).ToList
Line 24:             End If
Line 25:         End If

A: I have seen this message a number of times myself, it is very annoying! As you pointed out, it probably because the assembly version changed. In Asp.Net, when the page changes, the code gets recompiled. Depending on where you put the class will determine if the class gets recompiled with the page or not. I would suggest moving any "model" type classes to a separate project. This will avoid this problem as well as the urge to mix view/controller and model code :).
You can also try serializing the object into session as XML. If you do, you should be able to deserialize it even if the assembly changes, though not if the properties on the object change.
I know you said you didn't want to hear this, but you might also consider not putting objects in the session. This makes it difficult to scale your application if the time ever comes that it is necessary. The sooner you fix this the easier it will be to fix.

A: A few days ago I got annoyed by this issue too. Alas Brian's first solution will only work as long as you do not need to compile the "model-project" again. If you do that (because of a bugfix, etc.) and update the running application (with users holding their session during the update-process, what is done in my case) you get the exception again :-(!
In my special case the best solution was really easy! I changed "DirectCast" to "TryCast". If the assemblyversion changed and casting fails, trycast will return nothing. In this case, or if I haven't written the dictionary/collection to the session yet, I fetch my data (again) over the database and store afterwards. The next time casting will work ;-)! And another great point, this works also if the interface of the object will change!


text:
Q: signatures/types in functional programming (OCaml) I started learning functional programming (OCaml), but I don't understand one important topic about fp: signatures (I'm not sure if it's a proper name). When I type something and compile with ocaml, I get for example:
# let inc x = x + 1 ;;
val inc : int -> int = <fun>

This is trivial, but I don't know, why this:
let something f g a b = f a (g a b)

gives an output:
val something : ('a -> 'b -> 'c) -> ('a -> 'd -> 'b) -> 'a -> 'd -> 'c = <fun>

I suppose, that this topic is absolutely basics of fp for many of you, but I ask for help here, because I haven't found anything on the Internet about signatures in OCaml (there are some articles about signatures in Haskell, but not explanations).
If this topic somehow will survive, I post here several functions, which signatures made me confused:
# let nie f a b = f b a ;; (* flip *)
val nie : ('a -> 'b -> 'c) -> 'b -> 'a -> 'c = <fun>

# let i f g a b = f (g a b) b ;;
val i : ('a -> 'b -> 'c) -> ('d -> 'b -> 'a) -> 'd -> 'b -> 'c = <fun>

# let s x y z = x z (y z) ;;
val s : ('a -> 'b -> 'c) -> ('a -> 'b) -> 'a -> 'c = <fun>

# let callCC f k = f (fun c d -> k c) k ;;
val callCC : (('a -> 'b -> 'c) -> ('a -> 'c) -> 'd) -> ('a -> 'c) -> 'd = <fun>

Thank you for help and explanation.

A: If you're really interested in the subject (and have access to a university library), read Wadler's excellent (if somewhat dated) "Introduction to functional programming". It explains type signatures and type inference in a very nice and readable way.
Two further hints: Note that the -> arrow is right-associative, so you can bracket things from the right which sometimes helps to understand things, ie a -> b -> c is the same as a -> (b -> c). This is connected to the second hint: Higher order functions. You can do things like
let add x y = x + y
let inc = add 1

so in FP, thinking of 'add' as a function that has to take two numerical parameters and returns a numerical value is not generally the right thing to do: It can also be a function that takes one numerical argument and returns a function with type num -> num.
Understanding this will help you understand type signatures, but you can do it without. Here, quick and easy:
# let s x y z = x z (y z) ;;
val s : ('a -> 'b -> 'c) -> ('a -> 'b) -> 'a -> 'c = <fun>

Look at the right hand side. y is given one argument, so it is of type a -> b where a is the type of z. x is given two arguments, the first one of which is z, so the type of the first argument has to be a as well. The type of (y z) , the second argument, is b, and hence the type of x is (a -> b -> c). This allows you to deduce the type of s immediately.

A: There are a couple of concepts you need to understand to make sense of this type signature and I don't know which ones you already do, so I tried my best to explain every important concept:
Currying
As you know, if you have the type foo -> bar, this describes a function taking an argument of type foo and returning a result of type bar. Since -> is right associative, the type foo -> bar -> baz is the same as foo -> (bar -> baz) and thus describes a function taking an argument of type foo and returning a value of type bar -> baz, which means the return value is a function taking a value of type bar and returning a value of type baz.
Such a function can be called like my_function my_foo my_bar, which because function application is left-associative, is the same as (my_function my_foo) my_bar, i.e. it applies my_function to the argument my_foo and then applies the function that is returned as a result to the argument my_bar.
Because it can be called like this, a function of type foo -> bar -> baz is often called "a function taking two arguments" and I will do so in the rest of this answer.
Type variables
If you define a function like let f x = x, it will have the type 'a -> 'a. But 'a isn't actually a type defined anywhere in the OCaml standard library, so what is it?
Any type that starts with a ' is a so-called type variable. A type variable can stand for any possible type. So in the example above f can be called with an int or a string or a list or anything at all - it doesn't matter.
Furthermore if the same type variable appears in a type signature more than once, it will stand for the same type. So in the example above that means, that the return type of f is the same as the argument type. So if f is called with an int, it returns an int. If it is called with a string, it returns a string and so on.
So a function of type 'a -> 'b -> 'a could take two arguments of any types (which might not be the same type for the first and second argument) and returns a value of the same type as the first argument, while a function of type 'a -> 'a -> 'a would take two arguments of the same type.
One note about type inference: Unless you explicitly give a function a type signature, OCaml will always infer the most general type possible for you. So unless a function uses any operations that only work with a given type (like + for example), the inferred type will contain type variables.
Now to explain the type...
val something : ('a -> 'b -> 'c) -> ('a -> 'd -> 'b) -> 'a -> 'd -> 'c = <fun>

This type signature tells you that something is a function taking four arguments.
The type of the first argument is 'a -> 'b -> 'c. I.e. a function taking two arguments of arbitrary and possibly different types and returning a value of an arbitrary type.
The type of the second argument is 'a -> 'd -> 'b. This is again a function with two arguments. The important thing to note here is that the first argument of the function must have the same type as the first argument of the first function and the return value of the function must have the same type as the second argument of the first function.
The type of the third argument is 'a, which is also the type of the first arguments of both functions.
Lastly, the type of the fourth argument is 'd, which is the type of the second argument of the second function.
The return value will be of type 'c, i.e. the return type of the first function.


text:
Q: How to insert ProyectosHasCentros table in the entities definition? I have this three tables in my model:

And I need to create the relationship between them in order to get valid entities but I need some help here. This is what I have right now:
Proyectos.php
<?php

namespace PI\ProyectoBundle\Entity;

use Doctrine\ORM\Mapping as ORM;

/**
 * @ORM\Entity
 * @ORM\Table(name="proyectos")
 */
class Proyectos {

    /**
     * @ORM\Id
     * @ORM\Column(type="integer")
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    protected $id;

    /**
     * @ORM\Column(type="string", length=45, unique=true, nullable=false)
     */
    protected $nombre;

    /**
     * @ORM\Column(type="boolean", nullable=true)
     */
    protected $estado;

    /**
     * @ORM\Column(type="string", length=45, nullable=false)
     */
    protected $pais;

    /**
     * @ORM\ManyToOne(targetEntity="PI\ClienteBundle\Entity\Clientes", cascade={"all"})
     * @ORM\JoinColumn(name="cliente", referencedColumnName="id")
     */
    protected $clientes;

    public function getId() {
        return $this->id;
    }

    public function setNombre($nombre) {
        $this->nombre = $nombre;
    }

    public function getNombre() {
        return $this->nombre;
    }

    public function setEstado($estado) {
        $this->estado = $estado;
    }

    public function getEstado() {
        return $this->estado;
    }

    public function setPais($pais) {
        $this->pais = $pais;
    }

    public function getPais() {
        return $this->pais;
    }

    public function setClientes(\PI\ClienteBundle\Entity\Clientes $clientes) {
        $this->clientes = $clientes;
    }

    public function getClientes() {
        return $this->clientes;
    }

}

And Centros.php
<?php

namespace PI\CentroBundle\Entity;

use Doctrine\ORM\Mapping as ORM;

/**
 * @ORM\Entity
 * @ORM\Table(name="centros")
 */
class Centros {

    /**
     * @ORM\Id
     * @ORM\Column(type="integer")
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    protected $id;

    /**
     * @ORM\Column(type="text", unique=true, nullable=false)
     */
    protected $descripcion;

    /**
     * @ORM\ManyToMany(targetEntity="PI\UnidadBundle\Entity\Unidades", inversedBy="centros", cascade={"persist"})
     * @ORM\JoinTable(name="unidades_has_centros",
     *      joinColumns={@ORM\JoinColumn(name="centros_id", referencedColumnName="id")},
     *      inverseJoinColumns={@ORM\JoinColumn(name="unidades_id", referencedColumnName="id")}
     *      )
     */
    protected $unidades;

    public function __construct() {
        $this->unidades = new \Doctrine\Common\Collections\ArrayCollection();
    }

    public function getId() {
        return $this->id;
    }

    public function setDescripcion($descripcion) {
        $this->descripcion = $descripcion;
    }

    public function getDescripcion() {
        return $this->descripcion;
    }

    public function setUnidades(\PI\UnidadBundle\Entity\Unidades $unidades) {
        $this->unidades[] = $unidades;
    }

    public function getUnidades() {
        return $this->unidades;
    }

}

How I add the n:m relationship in both sides to get valid entities and to make CRUD operations more easy than create a new Entity ProyectosHasCentros.php and put fields inside it?

A: If you don't add proyectos_cliente to the second table you can use the ManyToMany relationships in your entities. If you want extra fields, then you have to create an extra entity which contains the relationships with Proyectos and Centros. Beside the relationships you add extra properties, like proyectos_cliente.
Try to use one PK and use UNIQUE for the cliente field


text:
Q: Как изменить цвет рамки нажатой button
Как поменять синий цвет рамки уже нажатого input type = 'button' на какой-нибудь другой?

A: Похоже, что это у вас :focus на этой кнопке. Попробуйте ей дать outline. Ну или меняйте его по тому же :focus.

A: Попробуйте установить класс active при нажатии на кнопку и ему дать рамку какую надо...! Зависит от того что вам конкретно нужно, что бы она всегда такой была до следующего нажатия или просто на фокус...?

A: Нужно для неё задать псевдоклассы :focus, :active и применить outline: none;.

button {
  width: 100px;
  height: 100px;
}

button:focus,
button:active {
  outline: none;
}
<button>Button</button>


text:
Q: how to add begin of line with multilines with delimiter? I have a file like this:
Input:
---
a
b
c
d
---
a
b
c
d
---
a
b
c
d

And I would like to add same structure at each block delimited by --- like:
Output:
---
1: a
2: b
3: c
4: d
---
1: a
2: b
3: c
4: d
---
1: a
2: b
3: c
4: d

I try using sed like:
sed -i '1s/a: /\1/'

and so on but it keeps adding to the first line.
Best regards.

A: One awk idea:
awk '{ pfx=++count ": "        # set default prefix as incremented counter + ": "
       if ($0 ~ /^---/)        # if lines starts with "---" then ...
           pfx=count=""        # reset variables
       print pfx $0            # print prefix plus current line
     }' x

or as a one-liner (sans comments):
awk '{ pfx=++count ": "; if ($0 ~ /^---/) pfx=count=""; print pfx $0 }' x

This generates:
---
1: a
2: b
3: c
4: d
---
1: a
2: b
3: c
4: d
---
1: a
2: b
3: c
4: d


text:
Q: Add computed field to linq projection with automapper Having a mapping with automapper that maps Orders entity to OrdersDto
i would add a computed field not in domain table (Orders)
I do not kwnow if is possible and if i asked correctly but i hope code will be helpful
CreateMap<Orders, OrdersDto>()
            .ForMember(x => x.Id, conf => conf.MapFrom(i => i.OrderId))
            ...other fields

var orders = _ordersRepository.GetOrders();//<==Orders Table
var ordersView = (from o in orders
                  join s in solvency on o.Code equals s.Code
                              into os
                              from x in os.DefaultIfEmpty()
                              let computed = ...
                              select new
                              {
                                  fields...
                                  MyComputed = x.computed //<== want to include
                              })
                            .ToList();

I would my query in action controller to be more readable using
ProjectTo<OrdersDto>()

removing projection to anonimous object with linq


text:
Q: Ionic's 'capacitor update' doesn't pull PLAY_SERVICES_VERSION variable form config.xml That's about it. I was having trouble because version 11.8.0 of Google Services was crashing my cordova-plugin-googleplus when doing authentication. When I update it to 16.0.1 in gradle configs, it works, but I have to rewrite it manually every build, because cap sync rewrites it back to 11.8.0.
I altered the PLAY_SERVICES_VERSION variable from 11.8.0 to 16.0.0 in config.xml and package.json at Ionic's root directory, but it stills rewrites it back to 11.8.0 in every build. Where should I change this version so I don't get this annoyance?

A: Capacitor doesn't read the config.xml
If you want to force a version just add that library in the dependencies section of the app's build.gradle
implementation 'com.google.android.gms:play-services-auth:16.0.0'
implementation 'com.google.android.gms:play-services-identity:16.0.0'

that should force that version


text:
Q: How do I give Pycharm camera access on a mac to use with OpenCV? Python code works in terminal but does not work in Pycharm This code works fine when I run it in terminal with a virtual environment. I believe this is being caused by Pycharm not having camera access. This is my best guess because when I ran in terminal, terminal asked for camera access but camera access is never asked for when I run in Pycharm.
I tried tccutil reset Camera com.jetbrains.pycharm but that did not fix my issue.
Error:
False None
Traceback (most recent call last):
  File "/Users/troy/PycharmProjects/OpenCV/Test.py", line 14, in <module>
    cv2.imshow("Video", img)
cv2.error: OpenCV(4.3.0) /Users/travis/build/skvark/opencv-python/opencv/modules/highgui/src/window.cpp:376: error: (-215:Assertion failed) size.width>0 && size.height>0 in function 'imshow'

import cv2

cap = cv2.VideoCapture(1)

cap.set(3, 640)
cap.set(4, 480)

if not (cap.isOpened()):
    print("Camera Error")

while True:
    success, img = cap.read()
    print(success, img)
    cv2.imshow("Video", img)
    if cv2.waitKey(10) & 0xFF == ord('q'):
        break

A: If you are using the default camera, you can change it to
cap = cv2.VideoCapture(0)


text:
Q: Why is it necessary to terminate a process when the child process has already ignored the SIGINT signal? My English is not good.
I'm reading the code from ansible 1.1
The following is taken from "ansible-1.1/lib/ansible/runner/__init__.py"
def _executor_hook(job_queue, result_queue):

    # attempt workaround of https://github.com/newsapps/beeswithmachineguns/issues/17
    # this function also not present in CentOS 6
    if HAS_ATFORK:
        atfork()

    signal.signal(signal.SIGINT, signal.SIG_IGN)
    while not job_queue.empty():
        try:
            host = job_queue.get(block=False)
            result_queue.put(multiprocessing_runner._executor(host))
        except Queue.Empty:
            pass
        except:
            traceback.print_exc()

class Runner(object):
    # ...
    def _parallel_exec(self, hosts):
        ''' handles mulitprocessing when more than 1 fork is required '''

        manager = multiprocessing.Manager()
        job_queue = manager.Queue()
        for host in hosts:
            job_queue.put(host)
        result_queue = manager.Queue()

        workers = []
        for i in range(self.forks):
            prc = multiprocessing.Process(target=_executor_hook,
                args=(job_queue, result_queue))
            prc.start()
            workers.append(prc)

        try:
            for worker in workers:
                worker.join()
        except KeyboardInterrupt:
            for worker in workers:
                worker.terminate()
                worker.join()

When an error is caught, the terminate method is also called.
What is the difference between this and a direct pass?
try:
    for worker in workers:
        worker.join()
    except KeyboardInterrupt:
        pass

A: This lets the workers do their thing until they're done
try:
  for worker in workers:
    worker.join()

This gets called when you press ctrl+c
except KeyboardInterrupt:
  for worker in workers:
    worker.terminate()
    worker.join()

You are basically telling the program: "Don't let the workers finish their stuff, shut them down and get me out of here NOW"

A: On SIGINT, it will tell each worker to terminate, but then it still waits for them all to exit (completing whatever they do on termination) before it exits itself.


text:
Q: Salesforce silverpop integration Is there any document describing how to integrate salesforce with silverpop? I've already checked bunch of websites, but found nothing specific. Thanks for help

A: In case you'd like more detail on the integration: Silverpop's digital marketing platform integrates seamlessly with Salesforce.com, eliminating the silos between sales and marketing departments and providing both teams with visibility into each other's activities.  With the integration, you are able to sync your lead and contact data from Salesforce.com with your Silverpop database, view detailed mailing and Web browsing activities directly within SFDC, enable your sales team to send marketing-approved messages directly from SFDC and easily manage how you would like to sync data between the two platforms. For more information on the Silverpop and Salesforce.com integration, including a demo and customer case studies, please visit http://www.silverpop.com/Partners/Partners-All/Salesforcecom/ or reach out to me directly at fyule@silverpop.com.


text:
Q: Counterexample for associativity of smash product In Section 1.7 of Parametrized Homotopy Theory by May and Sigurdsson it is stated that the smash product of pointed topological spaces is not associative (which is just another hint that $\mathrm{Top}$ is the "wrong category"). Specifically, they claim that $\mathbb{N} \wedge (\mathbb{Q} \wedge \mathbb{Q})$ is not isomorphic to $(\mathbb{N} \wedge \mathbb{Q}) \wedge \mathbb{Q}$ in $\mathrm{Top}_*$. But actually  they just prove that the canonical bijection $\mathbb{N} \wedge (\mathbb{Q} \wedge \mathbb{Q}) \to (\mathbb{N} \wedge \mathbb{Q}) \wedge \mathbb{Q}$ is not an isomorphism. Equivalently, there is no isomorphism in the slice category $(\mathbb{N} \times \mathbb{Q} \times \mathbb{Q}) / \mathrm{Top}_*$. Therefore, my question is as follows:

How to prove that there is no isomorphism between $\mathbb{N} \wedge (\mathbb{Q} \wedge \mathbb{Q})$ and $(\mathbb{N} \wedge \mathbb{Q}) \wedge \mathbb{Q}$ in $\mathrm{Top}_*$?

I had asked the same question on math.SE.

A: This is not a real answer since there is a gap, a claim I'm not currently able to prove, but it is too long for a comment and I hope somebody can fix the gap. Consider the topological property of being sequential. The idea is that $(\mathbb Q\wedge \mathbb Q)\wedge\mathbb N$ is sequential but $\mathbb Q\wedge (\mathbb Q\wedge\mathbb N)$ should not.
First countable spaces, such as $\mathbb Q\times \mathbb Q$, are sequential. Sequential spaces are closed under quotients and disjoint unions, hence $\mathbb Q\wedge \mathbb Q$, $(\mathbb Q\wedge \mathbb Q)\times\mathbb N$ and $(\mathbb Q\wedge \mathbb Q)\wedge\mathbb N$ are sequential.
We can identify the underlying sets of $(\mathbb Q\wedge \mathbb Q)\wedge\mathbb N$ and $\mathbb Q\wedge (\mathbb Q\wedge\mathbb N)$ in the obvious way, so we're really speaking about different topologies on the same set. May and Sigurdsson
show that the former has strictly more open sets than the latter. I think both of them have the same convergent sequences, but I haven't been able to prove it (the only problem is when the limit is the base point). If this is true, any open set in $(\mathbb Q\wedge \mathbb Q)\wedge\mathbb N$ would be sequentially open in $\mathbb Q\wedge (\mathbb Q\wedge\mathbb N)$, so the latter cannot be sequential, otherwise the two topologies would be the same.

A: Building on Fernando's answer, here is a proof that they are not homeomorphic.  By Fernando's answer, it suffices to show that if a sequence $(x_k,y_k,n_k)$ converges to the basepoint in $\mathbb{Q}\wedge(\mathbb{Q}\wedge\mathbb{N})$, it also converges to the basepoint in $(\mathbb{Q}\wedge\mathbb{Q})\wedge\mathbb{N}$.  Let $(x_k,y_k,n_k)$ be such a sequence.  We may assume that the points $(x_k,y_k,n_k)$ are all distinct from the basepoint.  I claim $\{n_k\}\subseteq\mathbb{N}$ must be a finite set; the result then follows easily.
Suppose for a contradiction that $\{n_k\}$ is infinite.  Passing to a subsequence, we may assume that for each $n\in\mathbb{N}$, there are only finitely many $k$ such that $n_k=n$.  For definiteness of notation, let us say that $0$ is our chosen basepoint in both $\mathbb{Q}$ and $\mathbb{N}$.  For each $n>0$, let $\epsilon_n>0$ be such that $\epsilon_n<|x_k|$ and $\epsilon_n<|y_k|$ for all $k$ such that $n_k=n$.  Now let $$U=\{(x,y,n):|x|<\epsilon_n\text{ or }|y|<\epsilon_n\}\subset \mathbb{Q}\wedge(\mathbb{Q}\wedge\mathbb{N}).$$
Then $U$ contains the basepoint and is disjoint from our sequence.  Furthermore, the pullback of $U$ to $\mathbb{Q}\times(\mathbb{Q}\wedge\mathbb{N})$ is open: it is the union of the open sets $$V=\mathbb{Q}\times\{(y,n):|y|<\epsilon_n\}$$ and $$W_n=\{x:|x|<\epsilon_n\}\times \{(y,n):y\neq0\},$$
the latter being a separate open set for each fixed $n>0$.  Thus $U$ is open, contradicting the assumption that our sequence converges to the basepoint.


text:
Q: Set own event id while creating event using microsoft graph API I'm using Microsoft Graph API for integration of microsoft/outlook calendar and events.
API Reference is here
I want to specify my own custom id for event while creating an event with this rest API, but I didn't find any way to do so. It automatically created an id. Is there any way of specifying our own Id.
Following is my request:
POST: https://graph.microsoft.com/v1.0/me/events

 {
   "subject": "My event",
   "start": {
      "dateTime": "2017-10-05T07:57:45.679Z",
      "timeZone": "UTC"
  },
  "end": {
      "dateTime": "2017-10-12T07:57:45.679Z",
      "timeZone": "UTC"
  }
}

A: No the ids are created by Exchange and are not user definable. The best option I can think of is to add an extended property to the event:
https://developer.microsoft.com/en-us/graph/docs/api-reference/v1.0/resources/extended-properties-overview

A: One can use the optional property transactionId, reference can be found at event and create event
Be aware this property is set when creating the event by a third party app and cannot be updated later.


text:
Q: Forced alignment using Aeneas with multible aeneas text files We have started a project to create a Turkish speech recognition dataset to use with DeepSpeech.
We finished preprocessing task of Ebook.
But we couldn't finish the forced alignment process with Aeneas.
According to its tutorials for forced alignment, you need a text file and its recorded audio file. While preprocessing of Ebook we have created 430 text files which are edited and cleaned for aeneas format (divided into paragraphs and sentences using nltk library).
But, while processing our created task object and creating its output file (Json file), we couldn't merge output files. For every Aeneas file, it starts from the beginning of the audio file.
It seems we need to split our audio file to 430 parts, but it is not a easy process.
I tried to merge Json files with:
import json
import glob

result = []
for f in glob.glob("*.json"):
  with open(f, "rb") as infile:
    result.append(json.load(infile))
with open("merged_file.json", "w") as outfile:
  json.dump(result, outfile)

But it didn't work, because while forced alignment process, aeneas starting from the beginning of the audio file for each aeneas text files.
Is it possible to create a task object which includes all 430 aeneas text files and append them into one output file (Json file) with respect to their timings ( their seconds ) also using one audio file?
Our task object:
# create Task object
config_string = "task_language=tur|is_text_type=plain|os_task_file_format=json"
task = Task(config_string=config_string)
task.audio_file_path_absolute = "/content/gdrive/My Drive/TASR/kitaplar/nutuk/Nutuk_sesli.mp3"
task.text_file_path_absolute = "/content/gdrive/My Drive/TASR/kitaplar/nutuk/nutuk_aeneas_data_1.txt")
task.sync_map_file_path_absolute = "/content/gdrive/My Drive/TASR/kitaplar/nutuk/syncmap.json")

Btw, we are working on Google Colab with python 3.

A: I figured out to solve my question, and found a solution.
Instead of combining JSON files, I could combine aeneas text files with this code:
with open("/content/gdrive/My Drive/TASR/kitaplar/{0}/{1}/{2}_aeneas_data_all.txt".format(book_name,chapter,
book_name), "wb") as outfile:
    for i in range(1,count-1):
      file_name = "/content/gdrive/My Drive/TASR/kitaplar/{0}/{1}/{2}_aeneas_data_{3}.txt".format(book_name, chapter, book_name, str(i))
  #print(file_name)
      with open(file_name, "rb") as infile:
        outfile.write(infile.read())

So after combining aeneas files, I can create a json file which contains all paragraphs.


text:
Q: Change both border and fill colors in one place in QGIS 3.0 This seems somewhat basic, but is there a way to set the colors for both fill and stroke of a polygon layer at the same time?  I find myself frequently having to change the colors in multiple places, especially when I am using line fill types. Changing the highest level color changes the fills in subordinate layers, but doesn't affect the stroke.
This dialogue allows you to change fill colors in all subordinate styles

but doesn't affect the strokes

Am I missing a setting somewhere?

A: If you set the stroke colour using the expression editor ("E" box on right of dropdown):

Then you can use @symbol_color for the stroke colour:

which ignores the colour in the drop-down, and doesn't render it in the preview top right of the dialog, but does (when applied) give you strokes that match the fill. Even if you change the fill colour. Here's what I get, with large dotted strokes so you can see them:


text:
Q: ¿Es posible declarar una variable que contenga un if statement? ¿Es posible declarar una variable que contenga un if statement?
El siguiente pseudocódigo (escrito solo con la idea de ilustrar el ejemplo), representa la idea que se persigue, esto es, que la variable m tome un valor diferente dependiendo del valor de j.
j = [1, 2, 3]
m =  if j[0]:
            [{'b': 0.0, 'x': 0.0, 'm': 0.02} for _ in range(100)]
     if j[1]:
            [{'b': 0.5, 'x': 0.5, 'm': 0.02} for _ in range(100)]
     if j[2]:
            [{'b': 1.0, 'x': 1.0, 'm': 0.02} for _ in range(100)]

A: Entiendo que lo que buscas es una asignación rápida de una variable según una determinada condición. Hay algunas formas de hacerlo (modifiqué un poco los valores de tu ejemplo por que estabas retornando siempre la misma lista):
Mediante una función
def valor(j):

  if j == 1:
    return [{'b': 0.8, 'x': 0.5, 'm': 0.02} for _ in range(100)]
  elif j == 2:
    return [{'b': 1.8, 'x': 1.5, 'm': 1.02} for _ in range(100)]
  elif j == 3:
    return [{'b': 2.8, 'x': 2.5, 'm': 2.02} for _ in range(100)]
  else:
    return None

j = 2
m = valor(j)
print(m)

Es una buena alternativa ya que permite verificar mejor la condición j, por ejemplo devolver un valor default si no se eligió ningún valor esperado.
Mediante el uso de diccionarios
opciones = {1:[{'b': 0.8, 'x': 0.5, 'm': 0.02} for _ in range(100)],
            2:[{'b': 1.8, 'x': 1.5, 'm': 1.02} for _ in range(100)],
            3:[{'b': 2.8, 'x': 2.5, 'm': 2.02} for _ in range(100)]}

j = 2
m = opciones[j]
print(m)

Es una asignación directa desde un diccionario que tiene como clave las opciones válidas, se emitirá un KeyError si usas cualquier valor de j no contemplado, salvo que accedas al diccionario usando el método get():
m = opciones.get(j, None)

A: Literalmente como lo estas preguntando no es posible. Aun asi, existe un par de formas de hacer algo muy parecido en Python. La primera es con los llamados Operadores de Coalescencia, y se usan de la siguiente forma:
m = j[0] or [{'b': 0.8, 'x': 0.5, 'm': 0.02} for _ in range(100)]

Esto se evalua de la siguiente manera. Si el primer termino/variable es verdadero, entonces a la variable se le asigna ese primer termino/variable. Si el primer termino/variable es falso, entonces a la variable se le asigna el segundo termino/variable. Ten en cuenta que solo se evalua el primer termino/variable.
La segunda es con el operador ternario, que es bastante parecido. Tendrias que usarlo de la siguiente manera:
m = [{'b': 0.8, 'x': 0.5, 'm': 0.02} for _ in range(100)] if j[0] else None

De esta forma, el valor por defecto es la lista que estas indicando cuando la condición se cumple y cuando no se cumple la condición, entonces la variable toma el valor None.
Como te decia, no es exactamente hacer un if dentro de la asignación, si no más bien evaular para asignar. Esto es una forma poco usual de hacerlo, pero es lo más parecido a tu pregunta. Supongo que podrias anidar de alguna forma las operaciones en alguna de estas dos formas. Ya que probablemente estes investigando los medios para llegar a un objetivo final, te recomiendo mejor hacerlo por funciones como lo indica la respuesta de Patricio.
Puedes ver más información de estos operadores en la documentación oficial de tu versión de Python. y tambien en esta pregunta del sitio en ingles.


text:
Q: PGPOOL slave node on 'waiting' status I am trying to configure a simple pgpool with master and slave (all on the same machine - different ports).
whenever I enter the pgpool via psql -p 9999 and run show pool_nodes; I see the master and slave clusters but the slave status is waiting (both of them running).
The master and slave are configured as primary and hot_standby for replication. but whenever I insert/select through the pgpool all goes through the master...
I want to get to a point that inserts will be made in the primary and the selects will go in slave.
su - postgres
mkdir production_server
mkdir slave1
mkdir slave_archive
create new cluster on production_server

changes for those values on postgresql.conf (production_server):
-------------------------------------------------------
wal_level = replica
archive_mode on
listen_address = *
archive_command= cp %p /var/lib/pgsql/slave_archive/%f
port=5435
-------------------------------------------------------

restart the cluster on production_server
pg_basebackup -p 5435 -D /var/lib/pgsql/slave1

changes for those values on postgresql.conf (slave1):
-------------------------------------------------------
port=5466
hot_standby=on
primary_conninfo= host =127.0.0.1 port=5435
restore_command = cp /var/lib/pgsql/slave_archive/%f %p
-------------------------------------------------------

create also a standby.signal file (we're using postgres version 12.x)
switch to root and chmod 700 on slave1 directory
switch back to postgres: su - postgres
start the cluster on -D /var/lib/pgsql/slave1

psql -p 5435
create table table1 as SELECT * FROM generate_series(1, 10000);
select pg_switch_wal();
---> on psql -p 5466 we will also see this insert/table

let's configure the pg_pool:
------------------------------------------------------------
cd /etc/pgpool-II
cp pgpool.conf.sample pgpool.conf
vi pgpool.conf:
----------------------------------------
listen_address=*
backend_hostname0=127.0.0.1
backend_port0=5435
backend_directory0=/var/lib/pgsql/production_server

backend_hostname0=127.0.0.1
backend_port0=5466
backend_directory0=/var/lib/pgsql/slave1
health_check_user=postgres

----------------------------------------

./pgpool &
psql -p 9999
in order to see the active nodes in the pool run:
show pool_nodes;
---> we need to recieve 2 nodes: 5435 / 5466

This is my script to configure the pgpool + master & slave. How do I solve the waiting status?

A: I faced the same problem when i installed pgpool-II-12* package (4.1 version). Couldn't find any solution for that so I removed it and installed pgpool-II-pg12* package (4.2 version) from here and configured it. It worked fine for this version.


text:
Q: Cannot insert duplicate key in object 'dbo.User'.\r\nThe statement has been terminated I have a user table. there are references to this table from other tables for fields such as CreatedBy.
Problem is, when I am inserting a row of another table (say 'x'), it tries to insert a new user into the user table.
What it should be doing is insert a row into table 'x' with CreatedBy as the existing user.
Using Entity Framework 4. Anyone faced a problem like that before?

A: You can insert an entity together with related entities or you can insert an entity without the related entities, just referencing existing ones. It depends on the code you write.
Example 1:
User user = GetUserFromSomewhere();
using (var context = new MyContext())
{
    Order order = new Order();
    order.CreatedBy = user;

    context.Orders.AddObject(order);
    // will put both order and related entity user into Added state
    // because user is not attached to the context

    context.SaveChanges();
    // creates new order and new user and sets the relationship between them
}

Example 2:
using (var context = new MyContext())
{
    User user = context.Users.SingleOrDefault(u => u.Id == 1);
    // query attaches this user to this context
    // user is in state Unchanged now

    Order order = new Order();
    order.CreatedBy = user;

    context.Orders.AddObject(order);
    // will put the order into Added state but doesn't touch the
    // state of already attached related entities -> user remains
    // in state Unchanged

    context.SaveChanges();
    // creates new order with reference to user, but doesn't create new user
}

Example 3:
User user = GetUserFromSomewhere();
using (var context = new MyContext())
{
    context.Users.Attach(user);
    // we attach explicitely to the context telling EF thereby
    // that we know that this user exists in the DB
    // user is in state Unchanged now

    Order order = new Order();
    order.CreatedBy = user;

    context.Orders.AddObject(order);
    // will put the order into Added state but doesn't touch the
    // state of already attached related entities -> user remains
    // in state Unchanged

    context.SaveChanges();
    // creates new order with reference to user, but doesn't create new user
}

Edit
Example 4:
int userId = GetUserIdFromSomewhere();
using (var context = new MyContext())
{
    var user = new User { Id = userId };
    // we create a stub user entity with the correct primary key
    // It's not necessary to set other properties
    // to only set the relationship to the order

    context.Users.Attach(user);
    // we attach explicitely to the context telling EF thereby
    // that we know that this user exists in the DB
    // user is in state Unchanged now

    Order order = new Order();
    order.CreatedBy = user;

    context.Orders.AddObject(order);
    // will put the order into Added state but doesn't touch the
    // state of already attached related entities -> user remains
    // in state Unchanged

    context.SaveChanges();
    // creates new order with reference to user, but doesn't create new user
}


text:
Q: Why doesn't my object property function increment when called into a "new" operator via variable I am trying to figure out why calling a function from an object value directly inside a "new" operator works as desired (creates a unique incremental id integer for the "same" object):
var allItems = [];
var item;
var idid = 0;

function generateId() {
  return idid += 1;
}

function create(){
  var item = new NewItem( {id: generateId(), punch: 10, kick: 5} );
  allItems.push(item);
  console.log (allItems);
}

function NewItem(item) {
  this.item = item;
}

But calling the same function from an object value within a variable that is then brought into the "new" operator does not work in the same way (continuously returns the number "1").
var allItems = [];
var item;
var idid = 0;

function generateId() {
  return idid += 1;
}

function create(){
  var item = new NewItem(coolObject);
  allItems.push(item);
  console.log (allItems);
}

function NewItem(item) {
  this.item = item;
}

var coolObject = {id: generateId(), punch: 10, kick: 5};

This can be demonstrated by creating the same object several times in each example via:
<div>
    <button onclick="create()">CREATE</button>
</div>

A: In the first case, you call generateId() multiple times which increments the id, in the second case you call it just once. That has nothing todo with the new constructor call, it can be easily reproduced with:
 // works:

 let obj = { id: generateId() }; // first call
 console.log(obj) // { id: 1 }
 let obj2 = { id: generateId() }; // second call
 console.log(obj2); // { id: 2 }

 // "doesnt work":

 let obj = { id: generateId() }; // first call
 console.log(obj) // { id: 1 }
 console.log(obj) // { id: 1 }

A: OK finally got it...
Need to put the 'external' var object in its own object (which is cool, this is where you can list out all your items in a neat and fashionable way) like so:
var everyItems = {
  coolObject: {punch: 10, kick: 5},
  neatoObject: {swipe: 7, scratch: 2},
};

Then you still need to call that generateId function directly within the new constructor (I never figured out a way around this) but now put the id generator along side the new item you're creating like so:
function create(){
  var item = new NewItem( {id: generateId()}, coolObject );
  allItems.push(item);
}

Then here is where the true resolution to my problem comes in, in the actual constructor function you merge the uniquely generated ID with the new item you are creating...
function NewItem(item, coolObject) {
    this.item = item;
    Object.assign(item, coolObject);
}

Fire off create() a bunch-o-times and you'll get a bunch of identical "coolObjects" EXCEPT they will have unique ID's.
// item: {id: 1, punch: 10, kick: 5}
// item: {id: 2, punch: 10, kick: 5}
// item: {id: 3, punch: 10, kick: 5}
// item: {id: 4, punch: 10, kick: 5}

To recap, I was doing exactly what I wanted by including the new object properties, including the generateId() function, directly in the new operator variable (like my first example) - but this meant I would have had to code a create item function for each individual new, different, or same (but with unique ID) type of item. a dozen? hundred? thousand?
So needed to get the functionality (unique ID with matching objects) to work with an external object.
TL;DR
generate the unique ID separately, pass in the external object (with all of its properties) and merge them together with Object.assign.


text:
Q: Strange interaction between fontspec, lua and pgfplots While trying to combine some Lua code with plots written in pgfplots something went completely wrong. I have no idea what causes the problem, as the error message is a bit opaque to me. Here is the example which compiles nicely in luatex without the fontspec package:
\documentclass[12pt]{article}
\usepackage{pgfplots}

\usepackage{fontspec}
\usepackage{luacode}
\usepackage{filecontents}

\begin{filecontents*}{test.txt}
some text
\end{filecontents*}

\begin{luacode*}
  function readtxt()
    file = io.open("test.txt", "r")
    text = file:read("*all")
    return tex.print(text)
  end
\end{luacode*}

\begin{document}
\directlua{readtxt()}

\begin{tikzpicture}
  \begin{axis}
    \addplot[] coordinates {(0.0, 0.0) (1,1)};
  \end{axis}
\end{tikzpicture}

\end{document}

With fontspec enabled the first error messages of a total of 58 are:
! LuaTeX error ...)/MiKTeX 2.9/tex/luatex/luaotfload/otfl-font-def.lua:239: att
empt to call field 'suffix' (a nil value).
<to be read again>
                   relax
l.26   \end{axis}

The lua interpreter ran into a problem, so the
remainder of this lua chunk will be ignored.

! Font \EU2/lmr/m/n/8=file:lmroman8-regular:script=latn;+trep;+tlig; at 8pt not
 loadable: metric data not found or bad.
<to be read again>
                   relax
l.26   \end{axis}

I wasn't able to read the size data for this font,
so I will ignore the font specification.

Somehow there is some negative interaction between the three components, Lua, pgfplots and fontspec. Individually they all work nicely. Some interaction was reported in this question: Bad interaction between fontspec and some lua code that performs string-related search and replace operations but this seems unrelated.
Any ideas what is going on here?

A: The problem has nothing to do with pgfplots: You get the same error if you simply try to change the font after your \directlua e.g. by issuing a \tiny.
The source of the problem is the name of your file handle. Probably luaotfload is using this name too. Every thing works if I change the name to e.g. fileA:
\documentclass[12pt]{article}

\usepackage{fontspec}
\usepackage{luacode}
\usepackage{filecontents}

\begin{filecontents*}{test.txt}
some text
\end{filecontents*}

\begin{luacode*}
  function readtxt()
    fileA = io.open("test.txt", "r") --changed
    text = fileA:read("*all")
    return tex.print(text)
  end
\end{luacode*}

\begin{document}
\directlua{readtxt()}

\tiny abc
\end{document}


text:
Q: add a constraint on a datetime column i want to to add a constraint onto a ID column and a date time column, so that an id can only be entered once in a day
alter table Table1
...
add constraint pk_id Primary Key (datetime,ID)

If an id has been inserted for the following datetime 2015-03-17 12:48:00, it would not get inserted again on the same datetime, but if the time changes to 2015-03-17 12:45:00 the id gets entered again.
Is there a way to add the constraint to just the date part of the datetime column?

A: I don't think you can but you have different alternatives:

*

*Change your column to just have the date part populated

*Create a computed column where you remove the time part and create the unique index used this column instead.

EDIT: as per @a-ツ comment there are other options:

*

*Split the column in two, one to store the date and other to store the time part, so you can create de index over the date one

A: You have to give composite primary key or check constraint..
Check this example. For composite key, on design mode, just select both column and right click and select "primary-key".
CREATE TABLE [dbo].[Table_1](
    [id] [int] NOT NULL,
    [datecolumn] [datetime] NOT NULL,
    [name] [varchar](50) NULL,
 CONSTRAINT [PK_Table_1] PRIMARY KEY CLUSTERED
(
    [id] ASC,
    [datecolumn] ASC
)

) ON [PRIMARY]

GO

insert into Table_1 values (1, '2014-03-17 00:00:00.000', 'othercolumnvalue')

insert into Table_1 values  (1, '2014-03-17 12:00:00.000', 'othercolumnvalue')
insert into Table_1 values  (1, '2014-03-17 02:10:59.000', 'othercolumnvalue')

--this will give error as you already entered the same value.
insert into Table_1 values (1, '2014-03-17 00:00:00.000', 'othercolumnvalue')

how do I make a composite key with SQL Server Management Studio?


text:
Q: What is the word for oddly matched meal items For example if I have a burger and soup, or spaghetti and milk. Almost like a potluck or a pitch-in, but less on purpose.

A: If it's not too much of a mixed metaphor in this instance,

smorgasbord
1:  a luncheon or supper buffet offering a variety of foods and dishes
  (as hors d'oeuvres, hot and cold meats, smoked and pickled fish,
  cheeses, salads, and relishes)
2:  an often large heterogeneous mixture, melange

[M-W] seems a reasonable fit.
As hinted, melange / mélange is another possibility.


text:
Q: I would like to add a border-bottom when i hover the elements inside as well I have a navigation bar that is outputs a border-bottom when i hover over the li but when i hover over the child elements of that li, the :hover stops, how do i make it so that the :hover remains even when i hover over the child elements.
I would like to add some parts of the code. This is the HTML file.

* {
  margin: 0;
  padding: 0;
  border: 0;
}

` header {
  background: #fff;
  width: 100%;
}

.navbar {
  padding: 0;
}

.navbar nav {
  width: 100%;
  height: 115px;
}

.navbar nav ul {
  float: right;
  margin: 0;
}

.navbar nav ul li {
  text-decoration: none;
  float: left;
  list-style: none;
  position: relative;
}

.navbar nav ul li a {
  color: black;
  display: block;
  padding: 45.5px 14px;
  text-decoration: none;
}

.parent-a:hover {
  border-bottom: #aa312c 4px solid;
  padding: 25.5px 14px;
  margin: 18px 0;
}

.level2-ul:hover .parent-a {
  border-bottom: #aa312c 4px solid;
  padding: 25.5px 14px;
  margin: 18px 0;
}

.navbar nav ul li ul {
  display: none;
  position: absolute;
  background-color: white;
  padding: 0;
  border-radius: 0px 0px 4px 4px;
}

.navbar nav ul li:hover ul {
  display: block;
  background-color: rgb(234, 236, 237);
  z-index: 100;
}

.navbar nav ul li ul li {
  width: 180px;
  border-radius: 4px;
}

.navbar nav ul li ul li a {
  color: black;
  padding: 8px 14px;
  border-bottom: 1px solid #dedfe1;
}

.navbar nav ul li ul li a:hover {
  background: #dedfe1;
}

#headline {
  color: #fff;
  padding: 4px;
  font-size: 1.5rem;
  margin: 0;
  text-align: center;
  font-weight: bold;
}

#headline-wrapper {
  background: #aa312c;
}

              Online Activities

Google

Youtube

Reddit

              Social Media

Facebook

Instagram

Twitter

              Online Shopping

Shopee

Lazada

Carousell

        Software Quotation Tool

By doing this, I can hover over the 3 nav lis and :hover would be activated. However, as soon as I hover over the inner li, the :hover stopped, I tried using .level2-ul but unable to do so. Thank you for the help.

A: Put parent-a on the li rather than on the a.

* {
  margin: 0;
  padding: 0;
  border: 0;
}

` header {
  background: #fff;
  width: 100%;
}

.navbar {
  padding: 0;
}

.navbar nav {
  width: 100%;
  height: 115px;
}

.navbar nav ul {
  float: right;
  margin: 0;
}

.navbar nav ul li {
  text-decoration: none;
  float: left;
  list-style: none;
  position: relative;
}

.navbar nav ul li a {
  color: black;
  display: block;
  padding: 45.5px 14px;
  text-decoration: none;
}

.parent-a:hover > a {
  border-bottom: #aa312c 4px solid;
  padding: 25.5px 14px;
  margin: 18px 0;
}

.level2-ul:hover .parent-a {
  border-bottom: #aa312c 4px solid;
  padding: 25.5px 14px;
  margin: 18px 0;
}

.navbar nav ul li ul {
  display: none;
  position: absolute;
  background-color: white;
  padding: 0;
  border-radius: 0px 0px 4px 4px;
}

.navbar nav ul li:hover ul {
  display: block;
  background-color: rgb(234, 236, 237);
  z-index: 100;
}

.navbar nav ul li ul li {
  width: 180px;
  border-radius: 4px;
}

.navbar nav ul li ul li a {
  color: black;
  padding: 8px 14px;
  border-bottom: 1px solid #dedfe1;
}

.navbar nav ul li ul li a:hover {
  background: #dedfe1;
}

#headline {
  color: #fff;
  padding: 4px;
  font-size: 1.5rem;
  margin: 0;
  text-align: center;
  font-weight: bold;
}

#headline-wrapper {
  background: #aa312c;
}

              Online Activities

Google

Youtube

Reddit

              Social Media

Facebook

Instagram

Twitter

              Online Shopping

Shopee

Lazada

Carousell


text:
Q: Spilled tea on laptop; still working, should I service it anyway? Displayport dead I need some advice. I spilled tea on the left side of my X230T.
I did the normal out with the battery and dry procedure. The laptop works now. Not much got in the keyboard, much spilled against the ports on the left side. The displayport is not working, but the USB and VGA is working. But I think some water got inside the fan vent and that might in the long run rust up the system board.
Should I get a service on it just to be sure? Check for damage and maybe replace the systemboard? Will a new board fix the displayport or did it shortcut something in the CPU, since the the gpu is integrated in it? I don't now, I could just use it as long as it works and get a new one when or if it dies, but I would like to try to be preventive if possible.
If a service now will prevent it from kicking the boot in 4 months time it's worth it for me.


text:
Q: Failed to connect to localhost 127.0.0.1:44373 I'm using xamarin forms + asp.net core web api. If I try to call from Postmat then everything is fine, but if I call from a device (I use a real device, not an emulator) then I have this error "Failed to connect to localhost / 127.0.0.1: 44373"
My string "https: // localhost: 44373 / api / v1 / reports / get_reports" Phone local IP - 192.168.0.101
My ipconfig
Wireless LAN adapter Wi-Fi:
Connection-specific DNS Suffix  . :
   Link-local IPv6 Address . . . . . : fe80::4dbf:c945:4125:74c8%5
   IPv4 Address. . . . . . . . . . . : 192.168.0.102
   Subnet Mask . . . . . . . . . . . : 255.255.255.0
   Default Gateway . . . . . . . . . : 192.168.0.1


text:
Q: Check if a set of puzzle pieces is forms a valid puzzle I have a set of puzzle pieces (triangles and squares) of e.g. the form
{[1, 2, 3, 4], [2, 4, 5], [1 , 3, 6]}
Now, I want to check if these pieces can be put together on a grid.
A valid layout would e.g be:
A set of puzzles that would not have a valid mapping would be
{[1, 2, 3, 4], [2, 4, 5], [1 , 5, 6]}
My first ansatz is to put all numbers in the set of puzzle pieces (in the above examples it would be 1, 2, 3, 4, 5, 6) as nodes in a graph and connect them according to the puzzle pieces (if a connection occurs several times, consider it only ones).
Then I check if the resulting graph is planar (this is cheap, it scales with the number of edges to the power of 2).
However, the planarity is only necessary for a valid mapping but not sufficient, since it does not take into account that the puzzle pieces have to form a square or a triangle (nothing stretched or similar).
So I thought about a list of forbidden edges, which is appended by looping over the set of puzzles, however, I am stuck. Does someone have a clever idea to answer the question: Does a given set of puzzles form a valid layout on a grid (at best in polynomial time).
The length of the set is arbitrary
Edit: For a puzzle piece such as [1, 2, 3, 4], the four numbers must form a square, and it does not matter in which order these numbers appear on the grid. The same applies to triangles. Therefore, swapping e.g. 2 and 4 in the figure above would still be a valid assignment

A: I hesitate to post this, because it doesn't completely meet your requirements, but perhaps this can be a start.
This does as I suggested in my comments, by building up a big polygon through accretion of the individual pieces.  For triangles, this is easy, but if the points of the squares are not in rotational order, then this fails.  You'll see that I changed the rectangle to [1,2,4,3] to get this to pass.  In that case, you would need to remember where the squares were added, and if a piece doesn't attach, try it again after flipping those points.
def check(data):
    # Pick the first triangle to start our polygon
    poly = [p for p in data if len(p)==3][0]
    data.remove(poly)

    while data:
        undone = []
        for unit in data:
            print(poly)
            # How many sides are in common with our master polygon?

            common = [p for p in unit if p in poly]
            if len(common) > 2:
                # Impossible.
                return False
            if len(common) < 2:
                # Can't attach this one yet.
                undone.append( unit )
                continue

            # We extend the polygon by inserting the one or two new points
            # between the two known ones.

            # For a triangle, it's easy.  For a square, we can't know
            # the orientation of the other two sides.

            other = [p for p in unit if p not in poly]
            print(unit, common,other)
            for i in range(len(poly)-1):
                if poly[i] in common:
                    if poly[i+1] in common:
                        poly = poly[:i+1]+other+poly[i+1:]
                    elif i == 0 and poly[-1] in common:
                        poly.extend( other )
                    else:
                        return False
                    break
        if undone == data:
            return False
        data = undone
    print(poly)
    return True

data = [[1,2,4,3],[2,4,5],[1,3,6]]
print(check(data))
data = [[1,2,4,3],[2,4,5],[1,5,6]]
print(check(data))

A: If all you want to know is whether a feasible mapping exists (true or false result) and doesn't care about its details (an assignment of numbers to the grid), then I think a good starting point would be to check every piece of puzzle against every other piece in the following way.
If the intersection of sets of vertices for two pieces has size of:

*

*0: then the pieces are not adjacent, continue checking,

*1: then a valid mapping cannot be created because two pieces share only a single vertex and not edge (it's only my assumption that it's invalid),

*2: then the pieces are adjacent and the edge is specified by the two vertices, continue checking,

*3: or more, then a valid mapping cannot be created because a piece is contained withinside of the other.

The above method has complexity of O(n^2), where n is the number of pieces. It might be sufficient for your needs but it really depends on what are the formal criteria for a layout to be considered valid.

A: I have an approach would run in linear time.  It's not a complete solution, but may be a suitable foundation.  I'm not a python developer, so pardon the sketchy pseudocode.
Create a shape object, with the following structure:
Shape {
   id: int,
   points: [int…],
   edges: [[point,point]...]
   diagonals: [[point,point]...]
   function cornerSize(point) {
     if (points.length==4) return 2;
     if (exists(diagonals[0]) && point!=diagonals[0][0] && point!=diagonals[0] [1]) return 2;
     return 1;
  }
}

Within that structure, assume all point pairs are consistently ordered smallest to largest, and can be represented as a string if needed, such as "1,5" instead of [1,5]-- the goal is just a consistent  unique identifier for an unordered pair.  The shape.id is determined by the ordinal position in your input array of puzzle pieces.  When you construct a Shape object, you'll assign the puzzle piece to points, and populate the Shape's id, and will initially leave edges and diagonals empty.
You will maintain a placedPoints map, where each point is a key to lookup an array of all known shapes connected to that point.
placedPoints[point] = [Shape…]

You'll also maintain a joinedEdges map, with a point pair as key, and a list of associated Shapes as the value.
joinedEdges[point,point] = [Shape…]

Iterate through your list of pieces, constructing a shape for each and updating your two maps.  You consider your puzzle valid if it runs through all pieces without throwing an exception (which can be caught by the caller)..
function processPieces(pieces) {
    for (int p=0; p<pieces.length; p++) {
        shapes[p]=new Shapes(p, pieces[p]);
        for (int i=0; i<pieces[p].length; i++) {
            if (exists(placedPoints[pieces[p][i]])) {
                placedPoints[pieces[p][i]].append(shapes[p]);
                int cornerSum=sumOfCornerSizes(placedPoints[pieces[p][i]]);
                if (cornerSum > 8) throw "Too many shapes share the same point."
            } else {
                placedPoints[pieces[p][i]]=[shapes[p]];
            }
            commonEdges = findCommonEdges(shapes[p], placedPoints[pieces[p][i]]);
        # findCommonEdges should throw if any 2 shapes share more than 2 points in common
        for (commonEdge : commonEdges) {
            if (exists(joinedEdges[commonEdge])) {
                throw "Too many shapes share the same edge."
            } else {
                For each point in commonEdge
                    For each shape in placedPoints[point]
                         Commit commonEdge into shape.edges and shape.diagonals
                          # Shape will keep track of known edges until you can
                          # determine a diagonal, at which point you should be
                          # able to determine all its remaining edges and diagonals.

                         If inconsistency found, throw exception.
                          # A triangle diagonal may only pair with another triangle diagonal.
                          # A square diagonal may not pair with any other shape.
            }
        }
    }
}

Summary of criteria for consistency:

*

*A shape's orthogonal edge may be shared with at most one other shape's orthogonal edge.

*A triangle's diagonal edge may be only shared with another triangle's diagonal edge.

*A square's diagonal edge my not be shared with another shape.

*A point may intersect with no more than 8 units of other shapes, where a 45 degree angle counts as one unit and a 90 degree angle counts as two.


text:
Q: drivers for Intel Graphics 620 on Ubuntu 16.04 I'm using Ubuntu 16.04 on a Dell Latitude 5480 which has Intel HD Graphics 620.  I first noticed a problem when the HDMI output was not working.  The graphics drivers don't seem to be working properly, here is the return from my sudo lshw -C display

  *-display
       description: VGA compatible controller
       product: Intel Corporation
       vendor: Intel Corporation
       physical id: 2
       bus info: pci@0000:00:02.0
       version: 04
       width: 64 bits
       clock: 33MHz
       capabilities: pciexpress msi pm vga_controller bus_master cap_list rom
       configuration: driver=i915 latency=0
       resources: irq:129 memory:ee000000-eeffffff memory:d0000000-dfffffff ioport:f000(size=64) memory:c0000-dffff

It sees that it's Intel, but it doesn't seem to know which chipset it is.
Any recommendation on how to resolve this?  It's a corporate machine and they won't let me update past 16.04.


text:
Q: How to Multi-threading this example of code? I would like to simulate a distributed system and how machines do their works, the topology adopted is a centralized one, I have many little systems in which each sub systems adopts this topology, I mean I suppose that my distributed system constitutes of many centralized systems.
I have created a simple discrete event simulator, which simulates the work in side One centralized system, the code is like:
public class SimuleOnesystem {
// a set of parameters
class Arrival{// here we simulate the arrival of works to a server
 // the code..
}
class Service{// here we simulate the services  }
class Departure{// means that the work is well done
 }
}

My question is, how could I multithreaded this code, I mean I  would like to execute for example 5 Centralized systems at the same time in which each system has its own simulation clock, eventList and so on, and these systems can communicate between each other in term of sending and receiving request and executing jobs etc...
Thanks in advance.

A: Besides the introduction of threads, as already pointed out in the other answers, your comment to ring bearer's answer is true: you have to take care of the event list and the simulation clock.
As far as I can see it, your example is a fairly typical discrete-event simulation. Trying to parallelize those, even just across threads, i.e. in a single address space (executed by the same JVM on a single machine, which may have multiple cores etc.), is not quite trivial. I would suggest you start with reading some introductory material on the matter (I would recommend this book).
Your basic problem is that you cannot prevent some threads of executing faster than others (e.g. because they have to handle less load), and hence their local clocks may advance into the simulated 'future'. If one of the other threads, i.e. a thread that is lagging behind, now issues a new event/message that would have to be processed by one thread that is advanced too far in time, everything will break (or fail quietly and be invalid). Think of opening your mailbox today and receiving a message from last year, to which you also should have responded immediately...
Algorithms that prevent such situations from happening are called synchronization algorithms. There are basically two flavors of those: optimistic methods allows such straggler events (messages from the past) to happen, but detect them and clean up any inconsistencies if necessary. In your case, though, it seems advisable to look at conservative algorithms first, which avoid such methods altogether. They are (usually) easier to implement, but only work well if there are certain delays between the sender of an event and the time the event has to be executed (e.g. see this classical paper for details, or this more recent one detailing a Java-based simulation system that uses conservative synchronization).
If you have a synchronization algorithm in place, it will also manage your local simulation time clocks.
As implementing these algorithms is rather time-consuming, you may also consider to use some Java-based simulation framework or library that already provides the methods (it's a well-known problem).

A: At a very basic level, all you have to do is to make SimuleOnesystem a Thread or a Runnable - then from a driver program such as a main method, create as many threads as you like and start them.

A: I don't mean this as a flippant answer, but: Java Concurrency In Practice, buy it now...
But to be more serious, you are now quickly getting into a very hairy testing scenario. I don't believe that you are going to have to get into using java.util.concurrent.ExecutorService, but if you are going to communicate between threads, you need to be conscious of having thread-safe communication channels (simple Lists, MessageQueues, database tables, etc...) between each simulation thread.


text:
Q: If statements inside of constructors I have a class called with an empty constructor and I want to have an if statement that sets a Boolean to true if the constructor has been used in an instantiation of that class. For example:
public class Test {
public float a1;
public int b1;
public double c1;
public Boolean ifConsUsed = false;

public Test(float a, int b, double c, Main app) {
   a1 = a; b1 = b; c1 = c; applet = app;
      if(expression goes here) {
      ifConsUsed = true;
      }
   }

}
In this instance what expression would I put into the if statement to detect if the constructor was used?

A: You do not need any condition to set ifConsUsed if your intention is just to figure out that if constructor is called or not
 public Test(float a, int b, double c, Main app) {
      ifConsUsed = true;
       ....
         }

A: If the constructor runs , it itself means that an object has been instantiated.
The constructor of a class is called it itself means that the object has been created. So, keep it simply..
public class Test
{
    public float a1;
    public int b1;
    public double c1;
    public Boolean ifConsUsed = false;

    public Test(float a, int b, double c, Main app)
   {
        a1 = a; b1 = b; c1 = c; applet = app;
        ifConsUsed = true;
   }
}


text:
Q: How to initialize private fields that are default nil when making the zero value useful? I am trying to follow the Go proverb "Make the zero value useful" but run into an issue with private fields on my struct that are by default nil (like map). If the zero value of my struct is to be useful, at some point it needs to initialize the private field. Consider the following situation in which I would like to do away with the constructor for Response, and make the zero value of Response useful. Obviously the field bag (which is a map[string]interface{}) needs to be initialized. I try to initialize the field bag when the getter Bag() is called on Response, which works, and allows for then calling Set() on the bag to set a value. But somehow when the response ends up back in the main function, my value gets lost.
I believe the problem is that the initialization that I came up with replaces the pointer on a copy of Response, instead of changing what the pointer points at. So the old pointer still points to nil, but I am not sure. How to initialize the private field correctly without the constructor?
func main() {
    response := getResponse()
    number := response.Bag().Get("NiceNumber")
    fmt.Println(response.Name, "tells me that your nice number today is:", number)
}

func getResponse() (response Response) {
    response = newResponse() // I am trying to do away with this line.
    response.Name = "MyResponse"
    response.Bag().Set("NiceNumber", 100)
    return
}

type Response struct {
    Name string
    bag  Bag
}

func (r Response) Bag() Bag {
    // I have added this piece of code as an attempt to initialize r.bag
    if r.bag == nil {
        r.bag = Bag(make(map[string]interface{}))
    }
    // ---
    return r.bag
}

type Bag map[string]interface{}

func (b Bag) Set(name string, value interface{}) {
    b[name] = value
}

func (b Bag) Get(name string) interface{} {
    return b[name]
}

// This constructor would be deleted if possible.
func newResponse() Response {
    return Response{
        Name: "",
        bag:  Bag(make(map[string]interface{})),
    }
}

Output now is MyResponse tells me that your nice number today is: 100, and when I remove the call to the constructor of Response, the output is MyResponse tells me that your nice number today is: <nil>.

A: You can change the Bag() method's receiver to a pointer.
func (r *Response) Bag() Bag {
    if r.bag == nil {
        r.bag = Bag(make(map[string]interface{}))
    }
    return r.bag
}

Note that you can still invoke a pointer-receiver method on a non-pointer value as long as the value is addressable. See the docs on Calls:

A method call x.m() is valid if the method set of (the type of) x
contains m and the argument list can be assigned to the parameter list
of m. If x is addressable and &x's method set contains m, x.m() is
shorthand for (&x).m()


text:
Q: How to Drop a Row in R Based on the First Column I have a data.frame setup like this:
df <- data.frame(units = c(1.5, -1, 1.4),
              what =  c('Num1', 'Num2', 'Num3'))

Which gives me something like this:
  units         what
1 1.500000     Num1
2 -1000000      Num2
3  1.400000      Num3

I want to  able to remove the entire row if the number in the first column is -1. So Ideally loop through the whole dataframe and remove the rows that have -1 in the unit column. I've been trying things like this:
if(CONDITION TO REMOVE) {
    print("deleting function...")
    df <- df[-c(df[,'Num2']),]
  }

But it deletes everything in the rest of the df. I only want to delete that one row (and the entire row).
Thanks in advance.

A: newdf <- df[-which(df[,1] ==-1),]

newdf is df without the rows containing -1 in the first column.

A: You can use dplyr to better suit your needs:
df.new <- df %>% filter(units != -1)

Or you can do this using base R
df.new <- df[df$units != -1, ]


text:
Q: All fragments for a phone sized app? For tablet sized screens you tend to end up with one or some small number of activities, and more fragments and you swap out part of the UI with different fragments. This all makes sense and is pretty easy to build and manage.
But what about for a phone sized screen? traditionally you'd use a different activity for each screen, but does that still make sense, seems annoying and tedious to have if tablet() swapFragments else startActivity() logic everywhere.
It seems like a better idea might be to follow the tablet structure more closely and have fewer activities, and have some interactions swap out the one fragment that you can see, but the google blog entry on fragments uses activities still for the smaller display, so not sure that's the right way to go.
So for people build apps that support phone & tablet sized screens, what are you doing, few activities & mostly fragments everywhere, or still mostly activities for the phone sized screens?, or something else ?

A: I prefer Activities and Fragments. One Activity will have one or two fragments depending upon the screen size.
Lets take fragment one is list and fragment two is detail of the item selected in the list.
So I define two layouts one for phone (consists of one fragment) and other for tablet (tablet one contains layout consist of two fragments).
One this is done, Activity will have small logic to determine is two fragments are loaded or one. If one then it has to launch another activity for second fragment. If two fragments are there then just load the other fragment with the corresponding data.