text:
Q: PowerShell complex -replace In PowerShell, how do you replace:
Session("*Logging")="true"

to
Session("*Logging")="false"

The following PowerShell script doesn't work.
get-content E:\WebSystems\Web1\web.config -replace "Session("*Logging")="true"", "Session("*Logging")="false"" | set-content E:\WebSystems\Web1\web.config

It says a bunch of errors:
You must provide a value expression on the right-hand side of the '*' operator.
Unexpected token ... in expression or statement.
Missing argument in parameter list.

A: If Session("*Logging")="true" is a string literal then some of the characters would needed to be escaped for the match to work. -replace uses regex for string matching and the brackets and astericks have special functions. One thing you could do is use the static method [regex]::escape to do the hard work for you. Other issues are that you need to enclose the Get-Content in brackets else it will treat -replace as a parameter to Get-Content. Also the string are not escaped properly which is what would cause most of your syntax errors. In the variables below I enclose the string in single quotes which is one of several approaches for addressing this.
$match = [regex]::escape('Session("*Logging")="true"')
$replace = 'Session("*Logging")="false"'

(get-content E:\WebSystems\Web1\web.config) -replace $match, $replace | ....

The escaped string looks like Session\("\*Logging"\)="true". You dont need to work about special characters for the replacement string itself.

A: Your string quoting is mashed, "Session(" is a string, then *Logging falls outside a string, and PowerShell is trying to deal with it as a multiplication or similar.
If you fixed the quoting, you'd then need to escape Regex special characters to use them as string literals.
And if you fix that, I end up with an error saying get-content doesn't take a -replace parameter.
How about something like:
#short commandlet nanmes
(gc E:\WebSystems\Web1\web.config) |% { $_.replace('Session("*Logging")="true"', 'Session("*Logging")="false"') } | sc E:\WebSystems\Web1\web.config

#long form commandlet names
(Get-Content E:\WebSystems\Web1\web.config) |foreach { $_.Replace('Session("*Logging")="true"', 'Session("*Logging")="false"') } | Set-Content E:\WebSystems\Web1\web.config

This uses foreach to gain access to the string.replace() method, which uses string literals and avoids having to deal with regex escapes, uses single quotes to have a string with double quotes in it, and wraps get-content in parentheses so it reads all content and closes the file and doesn't clash with set-content.


text:
Q: Mongodb Muliple averages based on a different column Using mongodb aggregate, is there a way to have the query return Weight average on all Scale , an average of Scale 1 , an average of Scale 2 all all returned in the same query?
This is an example of an entry in my data set
{
   "Profile" : "P1",
   "AvgWeight" : 639,
   "Time" : "2017-04-14T05:17:42.000Z",
   "Scale" : 1,
   "Weight" : 1504,
   "Target" : 680
}

My query that I am currently running that is averaging the weight accrost all scales ( Might not help, but better to have more info )
 [{
                    "$match": {
                        "Time": {
                            "$gt": moment(start).format("YYYY-MM-DD HH:mm:ss"),
                            "$lt": moment(end).format("YYYY-MM-DD HH:mm:ss")
                        }
                    }
                },
                {
                    "$group": {
                        "_id": {
                            "hour": {
                                "$hour": "$Time"
                            },
                            "day": {
                                "$dayOfYear": "$Time"
                            },
                            "interval": {
                                "$add": [{
                                        "$multiply": [{
                                            "$minute": "$Time"
                                        }]
                                    },
                                    {
                                        "$multiply": [{
                                                "$hour": "$Time"
                                            },
                                            100
                                        ]
                                    },
                                    {
                                        "$multiply": [{
                                                "$dayOfYear": "$Time"
                                            },
                                            10000
                                        ]
                                    },
                                    {
                                        "$multiply": [{
                                                "$year": "$Time"
                                            },
                                            10000000
                                        ]
                                    }
                                ]
                            }
                        },
                        "time": {
                            "$first": "$Time"
                        },
                        "avgW": {
                            "$avg": "$AvgWeight"
                        },
                        "avgWe": {
                            "$avg": "$Weight"
                        },
                        "avgTarget": {
                            "$avg": "$Target"
                        }
                    }
                }, {
                    "$sort": {
                        "Time": -1
                    }
                }
            ]

Adding Expected Response SOmething like
[
  {
    "_id : {"hour":1,"day":105,"interval":20971050122},

"time":"2017-04-15T01:22:58.000Z",
    "avgW":646,
    "avgWe":1577,
    "avgTarget":680 ,
    "Scale1" : 100 ,
    "Scale2" : 120
    } ,
   { "_id":{"hour":1,"day":105,"interval":20771050122},
   "time":"2017-04-15T01:22:55.000Z",
    "avgW":646,
    "avgWe":1335,
    "avgTarget":680 ,
    "Scale1" : 100 ,
    "Scale2" : 120 }
]

But if it is a little different I can handle it, as long all the scales are in the same parent object ( it would be to cpu intensive to post process them to link up the matching groups )

A: You can split the first group into two groups.
First group to calculate weight avg for all scales and second group to do rest of avgs.
Something like:
 [{
        "$match": {
            "Time": {
                "$gt": moment(start).format("YYYY-MM-DD HH:mm:ss"),
                "$lt": moment(end).format("YYYY-MM-DD HH:mm:ss")
            }
        }
    }, {
        "$group": {
            "_id": {
                "scale": "$Scale",
                "hour": {
                    "$hour": "$Time"
                },
                "day": {
                    "$dayOfYear": "$Time"
                },
                "interval": {
                    "$add": [{
                            "$multiply": [{
                                "$minute": "$Time"
                            }]
                        },
                        {
                            "$multiply": [{
                                    "$hour": "$Time"
                                },
                                100
                            ]
                        },
                        {
                            "$multiply": [{
                                    "$dayOfYear": "$Time"
                                },
                                10000
                            ]
                        },
                        {
                            "$multiply": [{
                                    "$year": "$Time"
                                },
                                10000000
                            ]
                        }
                    ]
                }
            },
            "time": {
                "$first": "$Time"
            },
            "scaleAvg: {
            "$avg": "$Weight"
        }
    }
 }, {
    "$group": {
        "_id": {
            "hour": "$_id.hour",
            "day": "$_id.day",
            "interval": "$_id.interval"
        },
        "time": {
            "$first": "$time"
        },
        "avgW": {
            "$avg": "$AvgWeight"
        },
        "avgWe": {
            "$avg": "$Weight"
        },
        "avgTarget": {
            "$avg": "$Target"
        },
        "scaleAvgs": {
            "$push": {
                "scale": "$_id.scale",
                "scaleAvg": "$scaleAvg"
            }
        }
    }
 }, {
    "$sort": {
        "time": -1
    }
 }]

redpajama_set_name: RedPajamaStackExchange


text:
Q: Transfer how to deliver message to Gateway? https://github.com/spring-projects/spring-integration-samples/tree/master/intermediate/tcp-client-server-multiplex
I saw this exmaple. So, I was changed architecture.

*

*send model

*receive model

And I have a question.
I don't understand transfer's role in send model.
I understand Aggregator delivery message to Transfer.
But, I don't understand How to deliver message to gateway.
How to deliver?

That is my spring integration config.
It is Send app setting,
  <!-- telegram bean -->
  <bean id="byteArrayRawSerializer" class="org.springframework.integration.ip.tcp.serializer.ByteArrayRawSerializer">
    <property name="maxMessageSize" value="2000"/>
  </bean>
  <bean id="myCorrelationStrategy" class="com.test.util.MyCorrelationStrategy"/>
  <!-- online connection factory -->
  <int-ip:tcp-connection-factory id="server" type="server" port="20001" single-use="false" lookup-host="false" so-timeout="60000" serializer="byteArrayRawSerializer" deserializer="byteArrayRawSerializer" />
  <int-ip:tcp-connection-factory id="client" type="client" host="localhost" port="10001" single-use="false" so-timeout="60000" serializer="byteArrayRawSerializer" deserializer="byteArrayRawSerializer" />

  <!--  Send -->
  <int:gateway id="sendGateway"
        service-interface="com.test.MySendGateway"
        default-reply-timeout="20000"
        default-request-channel="sendChannel"/>

  <int:publish-subscribe-channel id="sendChannel" />

  <int-ip:tcp-outbound-channel-adapter id="sendAdapter" order="2" channel="sendChannel" connection-factory="client" />

  <int:bridge input-channel="batchSendChannel" output-channel="toSendAggregator" order="1"/>

  <int:channel id="toSendAggregator" datatype="byte[]"/>

  <int:aggregator input-channel="toSendAggregator"
        output-channel="toSendTransformer"
        expire-groups-upon-completion="true"
        correlation-strategy="myCorrelationStrategy"
        correlation-strategy-method="getCorrelationKey"
        release-strategy-expression="size() == 2" />

  <int:transformer input-channel="toSendTransformer"  expression="payload.get(1)"/>

  <int-ip:tcp-inbound-channel-adapter id="sendReplyAdapter" channel="toSendAggregator" connection-factory="client" />

  <!--  Receive -->
  <int-ip:tcp-inbound-channel-adapter id="inboundAdapter" channel="batchInboundChannel" connection-factory="batchReceiveServer" />
  <int-ip:tcp-outbound-channel-adapter id="outboundAdapter" channel="batchOutboundChannel" connection-factory="batchReceiveServer"/>

  <int:channel id="batchInboundChannel" />

  <int:channel id="batchOutboundChannel"/>

  <int:service-activator id="myReceiveServiceActivator" method="receive" input-channel="batchInboundChannel">
    <bean class="com.test.endpoint.MyReceiveServiceActivator" />
  </int:service-activator>

And, It is Delivery app setting(center of picture),
  <!-- Bean load -->
  <bean id="byteArrayRawSerializer" class="org.springframework.integration.ip.tcp.serializer.ByteArrayRawSerializer">
    <property name="maxMessageSize" value="2000"/>
  </bean>

  <!-- Connection factory -->
  <int-ip:tcp-connection-factory id="server" type="server" port="30001" using-nio="true" single-use="false" lookup-host="false" so-timeout="10000" serializer="byteArrayRawSerializer"  deserializer="byteArrayRawSerializer" />
  <int-ip:tcp-connection-factory id="client" type="client" host="${RemoteTarget.ip}" port="${RemoteTarget.port}" using-nio="true" single-use="false" so-timeout="10000" serializer="byteArrayRawSerializer"  deserializer="byteArrayRawSerializer" />

  <!-- Connection factory -->
  <int-ip:tcp-connection-factory id="inboundServer" type="server" port="10001" using-nio="true"  single-use="false" lookup-host="false" so-timeout="${server.outbound.connectionTimeout}" serializer="byteArrayRawSerializer"  deserializer="byteArrayRawSerializer" />
  <int-ip:tcp-connection-factory id="inboardClient" type="client" host="localhost" port="20001" using-nio="true" single-use="false" so-timeout="10000" serializer="byteArrayRawSerializer"  deserializer="byteArrayRawSerializer" />

  <int-ip:tcp-inbound-channel-adapter id="receiveAdapter" channel="receiveChannel" connection-factory="server" auto-startup="true"/>
  <int-ip:tcp-inbound-channel-adapter id="sendReplyAdapter" channel="sendReplyChannel" connection-factory="client" auto-startup="true"/>

  <int:channel id="receiveChannel"/>
  <int:channel id="sendReplyChannel"/>

  <int-ip:tcp-outbound-channel-adapter id="receiveAdapter.inboard" channel="receiveChannel" connection-factory="inboundServer" />
  <int-ip:tcp-outbound-channel-adapter id="sendReplyAdapter.inboard" channel="sendReplyChannel" connection-factory="inboardClient" />

  <int-ip:tcp-outbound-channel-adapter id="sendAdapter" channel="sendChannel" connection-factory="client" />
  <int-ip:tcp-outbound-channel-adapter id="receiveReplyAdapter" channel="receiveReplyChannel" connection-factory="server" />

  <int:channel id="sendChannel" />

  <int:channel id="receiveReplyChannel"/>

  <int:router id="outRouter" input-channel="toRouter" method="route" auto-startup="true">
      <bean class="com.test.endpoint.MyRouter"/>
  </int:router>

  <int:channel id="toRouter"/>

  <int-ip:tcp-inbound-channel-adapter id="sendAdapter.inboard" channel="toRouter" connection-factory="inboundServer" auto-startup="true"/>
  <int-ip:tcp-inbound-channel-adapter id="receiveReplyAdapter.inboard" channel="toRouter" connection-factory="inboardClient" auto-startup="true"/>

But, When I call gw.send(msg), it is not work,
(exactly, message stop at the delivery machine's 'sendAdapter.inboard' until timeout and router get this message....

A: I an not sure what is transfer in your ar3chitecture either.
According the sample you show, we have:
gateway -> outbound-channel-adapter
        |-> aggregator

inbound-channel-adapter->aggregator->transformer

Where gateway sends its request to both TCP Outbound Channel Adapter and Aggregator, just because of <publish-subscribe-channel id="input" />.
As we know gateway is a request/reply component. When it sends requests, it waits for reply, because of the contract:
public interface SimpleGateway {

    String send(String text);

}

In this case the Gateway add TemporaryReplyChannel as a replyChannel header to wait for reply.
The reply is produced when we don't specify the output-channel on the last downstream flow consumer.
In our case it is exactly the <transformer> after <aggregator>:
<transformer input-channel="toTransformer.client"
    expression="payload.get(1)"/> <!-- The response is always second -->

I think that is a trick what you are looking for. It is called replyChannel header in the Consumer logic.


text:
Q: Does PCIe 3.0 x8 provide enough bandwidth for a dual QSFP 40Gbit NIC? I'm researching dual QSFP 40GBit network cards for a work project and have a few questions regarding PCIe 3.0's theoretical max bandwidth.
I'm currently looking at a dual QSFP PCIe 3.0 x8 card on CDW (Mellanox MCX314A-BCBT), but I don't think PCIe x8 would provide enough bandwidth for both 40Gbit links at 100% utilization.
Wikipedia states that PCIe 3.0 has a theoretical max bandwidth of 985MB/s per lane.  Thus, by my calculations, PCIe 3.0 x8 would yield a max bandwidth of 7880MB/s.  If this is true, the card would saturate the PCIe connection if both links are at 100% utilization.
Here are my specific questions:

*

*What is the max bandwidth that a dual QSFP 40Gbit network card can output?

*What is the max bandwidth that a PCIe 8x can handle before saturation?

*Is there an easy way to calculate this?

A:
What is the max bandwidth that a PCIe 8x can handle before saturation?

The max bandwidth of a single PCIe v3 lane is 985 MB/sec.  (8.0 Gbit/second).
x8 means that up to 8 PCIe lanes can be used, which give a theoretical max of 64 Gbit/sec.
This is less then two 40Gbit links.
So you can not run both links at full speed. It might be enough in practise though. Especially if the traffic is bursty. Just as long as both channels do not burst at the same time.

A: Doing a little dimensional analysis
Converting 7880 Mbytes per second to Gbits per second we get 63.04 Gbits/sec
(63.04 gigabits per second)/(40 (gigabits per second)) = 1.576

If you have a layout like this:
Unit (1) PCIe 3.0 slot, x8 or larger -> one QSFP card providing 1 x 40 Gbps connected to 8 lanes
Unit (2) PCIe 3.0 slot, x8 or larger -> one QSFP card providing 1 x 40 Gbps connected to 8 lanes
... then it will work fine, even accounting for the fact that there will be some overhead making it difficult to achieve theoretical throughput, because each PCIe slot will get its own lanes.
If however you have a layout like this:
Unit (1) PCIe 3.0 slot, x8 or larger -> one QSFP card providing (2 x 40 Gbps) connected to 8 lanes
... then it won't work fine, because now instead of having 1.576 times more bandwidth you need, you actually only have 0.788x as much bandwidth as you need.
I guess the manufacturer figures that protocol overhead at the ethernet layer will slow it down enough that this limitation won't matter, or otherwise some bottleneck further down in the I/O subsystem, or app turns (round trips). It seems odd that they would design the card so that the maximum theoretical throughput of the two ports on the board exceeds the theoretical throughput of the 8 lanes, but if you are really expecting to utilize >78% of 80 Gbps of throughput, you might want to just buy two cards (ideally, with one port apiece, if you can find a different model with that), and put them in separate slots, with each slot being at least 8 lanes wide.

A: Look...
Wikipedia states that the theoratical output through a single lane of PCIe 3.0 × 8 port is around 985MB/s.That's around 7880 MB/s or around 7.69GB/s for 8 lanes.
Let's move to Add on card.....
40G QSFP+ means 40Gb/s or basically around 5GB/s output.So i.e.10GB/s if you combine bandwidth of both of the output ports.
So here's the conclusion...
Our input is bottlenecked to 7.69GB/s which is ofcourse less than 10GB/s.So anyone who is labelling their cards with exactly these same specs,they are trying to make you fool.


text:
Q: Groovy get deeply nested parameter from Jenkins XML I have an XML file in Jenkins that looks like this:
<?xml version='1.0' encoding='UTF-8'?>
<build>
  <actions>
    <hudson.model.ParametersAction>
      <safeParameters class="sorted-set"/>
      <parameters class="java.util.Arrays$ArrayList">
        <a class="hudson.model.ParameterValue-array">
          <hudson.model.StringParameterValue>
            <name>branch</name>
            <description></description>
            <value>feature/MyAmazingBranch</value>
          </hudson.model.StringParameterValue>
          ...
</build>

I am aiming to build a gradle task that will return the branch parameter, in this case feature/MyAmazingBranch.
I have been able to parse the XML, and print the parsed result, but it doesn't currently make sense to me, and I'm not sure how to access a specific node.
task getBranch {
    ext.srcFile = file('build_jenkins.xml')
    def buildFile = new XmlParser().parse(srcFile)

    println buildFile

}

This prints:
build[attributes={}; value=[actions[attributes={}; value=[hudson.model.ParametersAction[attributes={}; value=[safeParameters[attributes={class=sorted-set}; value=[]], parameters[attributes={class=java.util.Arrays$ArrayList}; value=[a[attributes={class=hudson.model.ParameterValue-array}; value=[hudson.model.StringParameterValue[attributes={}; value=[name[attributes={}; value=[branch]], description[attributes={}; value=[]], value[attributes={}; value=[feature/WAWEB-6358-create-api-for-developer-applications]]]]....

How would I go about accessing the parameter names and values using Gradle/Groovy?

A: The following will create you a collection of values for children with parent nodes prefixed with hudson.model. & suffixed with ParameterValue with something in the middle of this which seems to be the pattern for subclasses of hudson.model.ParameterValue
def build = new XmlSlurper().parse( srcFile )
def params = build.'**'.findAll{ node -> node.name() =~ /hudson.model.[\w.]+ParameterValue/ }*.value


text:
Q: RPM: Installed (but unpackaged) file(s) found on Centos 6 with CUPS 1.7.1 Trying to install CUPS 1.7.1 on Centos 6.5 via RPM, I use:
# rpmbuild -ta cups-1.7.1-source.tar.bz2 --without dbus --without libusb1

but stops with below error:
Checking for unpackaged file(s):

/usr/lib/rpm/check-files /root/rpmbuild/BUILDROOT/cups-1.7.1-1.x86_64
error: Installed (but unpackaged) file(s) found: /usr/share/cups/usb/org.cups.usb-quirks

RPM build errors:
Installed (but unpackaged) file(s) found:

/usr/share/cups/usb/org.cups.usb-quirks

A: This file was installed into the %{buildroot} directory in the %install phase, but was not referenced in the %files. rpmbuild does not allow files in %{buildroot} that are not packed in the %files. So either add it in the %files if the file is needed, or do not install it the %{buildroot}

A: I had the same problem but it turns out that the postinstall file that i was creating needed an extra newline at the end because when the spec was being created, the %file was butt ended into my %post entry.


text:
Q: Using delimiters on scanner to read multiples lines from a text file Using scanner we can read next string, next line etc. But how can we read multiple lines into a string using scanner. Suppose the input something like
FIRSTNAME="John"
LASTNAME="Taylor"
ADDRESS="line1
line2
line3
line4"

output should look something like
John, "Taylor"

and how to we read entire address into a single string variable so that when we print it should like
"line1
 line2
 line3
 line4"

A: You could read the lines one by one using the Scanner#nextLine() method of Scanner and keep appending them in a StringBuffer with the \n at the end of each line. Once you are done reading all the lines, StringBuffer#toString() will give you your desired result.
In your case, you need to read the line and String#split(regex) it on the = symbol and take the second element of the resultant array.


text:
Q: Connect to MSSQL with USB in android private void fillCustomerInformationFields() throws  SQLException {
    Connection conn = null;
    PreparedStatement preparedStatement = null;
    ResultSet resultSet;
    Intent intent = getIntent();
    String IDValue = intent.getStringExtra("id");

    String query = "SELECT  SiparisID, M.MusteriAdi + ' ' + M.MusteriSoyadi AS MusteriAdi, U.UrunAdi," +
            " CASE WHEN OdemeTuru=0 THEN ? WHEN OdemeTuru=1 THEN ? WHEN OdemeTuru=2 THEN ? END AS OdemeTuru, TeslimTarihi,"+
    "M.musteriAdresi, SiparisDurumu, Aciklama FROM Siparisler S INNER JOIN Musteriler M ON M.MusteriID=S.MusteriID INNER JOIN Urunler U ON U.UrunID=S.urunID"+
    "WHERE S.SiparisID='"+IDValue+"'";

    try {
        conn = getDBConnection();
        preparedStatement = conn.prepareStatement(query);
        preparedStatement.setString(1,"Peşin");
        preparedStatement.setString(2,"Taksitli");
        preparedStatement.setString(3,"Kapıda");
        resultSet = preparedStatement.executeQuery();

        while(resultSet.next())
        {
            edtSiparisID.setText(resultSet.getString("SiparisID"));
            edtUrunAdi.setText(resultSet.getString("UrunAdi"));
            edtMusteriAdi.setText(resultSet.getString("MusteriAdi"));
            edtOdemeTuru.setText(resultSet.getString("OdemeTuru"));
            edtTeslimTarihi.setText(resultSet.getString("TeslimTarihi"));
            edtSiparisAdresi.setText(resultSet.getString("musteriAdresi"));
            edtAciklama.setText(resultSet.getString("Aciklama"));
        }
    }catch (SQLException e){
        e.printStackTrace();
    }finally {
        if(preparedStatement != null){
            preparedStatement.close();
        }
        if(conn != null){
            conn.close();
        }
    }

}

Hello everyone. İ'm making a project and i connect to mssql from android app via usb. I wrote to code for read data from mssql but i'm getting error.  how can i fix the error? Thanks for the help
The exception displayed in LogCat is:
com.example.uur.stock W/System.err﹕ java.sql.SQLException: Incorrect syntax near 'S'.

A: Check your query
String query = "SELECT  SiparisID, M.MusteriAdi + ' ' + M.MusteriSoyadi AS MusteriAdi, U.UrunAdi," +
            " CASE WHEN OdemeTuru=0 THEN ? WHEN OdemeTuru=1 THEN ? WHEN OdemeTuru=2 THEN ? END AS OdemeTuru, TeslimTarihi,"+
    "M.musteriAdresi, SiparisDurumu, Aciklama FROM Siparisler S INNER JOIN Musteriler M ON M.MusteriID=S.MusteriID INNER JOIN Urunler U ON U.UrunID=S.urunID"+
    "WHERE S.SiparisID='"+IDValue+"'";

this is causing the exception:
FROM Siparisler S JOIN Musteriler M

must change to
FROM Siparisler as S JOIN Musteriler as M

More info:
SQLite - ALIAS Syntax


text:
Q: undefined method `error_message_on' after implementing simple private messages I'm developing my first RoR website and I went through the steps to install simple_private_messages. Is this the way it's supposed to look?
http://i.imgur.com/HTootKv.jpg
I get this error message when I click "compose":
 NoMethodError in Messages#new

Showing C:/app/views/messages/new.html.erb where line #5 raised:

undefined method `error_message_on' for #<#<Class:0x516e6d0>:0x516c0f0>

I went through all of the steps correctly (I believe).
Here's my route.db
  resources :users do
             resources :messages do
               collection do
                 post :delete_selected
               end
             end
           end

messages/new.html.erb
<% form_for @message, :url => user_messages_path(@user) do |f| %>

    To:

        <%= f.text_field :to %>
        <%= error_message_on @message, :to %>

    Subject:

    <%= f.text_field :subject %>
    <%= error_message_on @message, :subject %>

      Message

      <%= f.text_area :body %>
            <%= error_message_on @message, :body %>

      <%= submit_tag "Send" %>

<% end %>

Messages model
class Message < ActiveRecord::Base

  is_private_message

  attr_accessor :to

end

Messages controller
class MessagesController < ApplicationController

  before_filter :set_user

  def index
    if params[:mailbox] == "sent"
      @messages = @user.sent_messages
    else
      @messages = @user.received_messages
    end
  end

  def show
    @message = Message.read_message(params[:id], current_user)
  end

  def new
    @message = Message.new

    if params[:reply_to]
      @reply_to = @user.received_messages.find(params[:reply_to])
      unless @reply_to.nil?
        @message.to = @reply_to.sender.login
        @message.subject = "Re: #{@reply_to.subject}"
        @message.body = "\n\n*Original message*\n\n #{@reply_to.body}"
      end
    end
  end

  def create
    @message = Message.new(params[:message])
    @message.sender = @user
    @message.recipient = User.find_by_login(params[:message][:to])

    if @message.save
      flash[:notice] = "Message sent"
      redirect_to user_messages_path(@user)
    else
      render :action => :new
    end
  end

  def delete_selected
    if request.post?
      if params[:delete]
        params[:delete].each { |id|
          @message = Message.find(:first, :conditions => ["messages.id = ? AND (sender_id = ? OR recipient_id = ?)", id, @user, @user])
          @message.mark_deleted(@user) unless @message.nil?
        }
        flash[:notice] = "Messages deleted"
      end
      redirect_to :back
    end
  end

  private
    def set_user
      @user = User.find(params[:user_id])
    end
end


text:
Q: Why won't changes that I've made on a github repo reflect on the browser? To start things off, I've successfully git cloned and ran this repo on my machine (https://github.com/creativetimofficial/light-bootstrap-dashboard-react).
At first it didn't work because I didn't run npm install --save-dev node-sass-chokidar but again, I can run it successfully on my machine after doing so.
When I run npm start, the dashboard and contents appear just fine but upon making any changes to it, like changing some text, it doesn't reflect on the browser at all.  It doesn't even auto-reload which's what it's supposed to do.  Even if I manually press cmd + r and/or cmd + shift + r, nothing changes.
What could possibly be wrong and how can I rectify this?

A: Ok I think I see the problem. You have to re-run your app. The fact that you're being asked if you want to run on a different port means the original application (the one without your changes) is still running. In the terminal where you originally ran npm start use ctrl-c to exit the server and then npm start again and you should see your changes reflected.


text:
Q: wxPython : Change label of "Browse" button in wxFilePickerCtrl object I'm using wxPython 4.2.0 for python 3.10.8 through wxFormBuilder and I can't find a way to change the label of the "Browse" button of my wxFilePicker object. I want to change this label because my application's language is not English and I'd like to have language coherency over the whole interface and to avoid confusing non-english speaking users. To be clear, the object is working perfectly, I'd just like to change the label of the button.
I already searched for similar questions and in the documentation but there's nothing on this specific label.
I want to know if it's possible at all to change this label while still using the very practical wxFilePickerCtrl, and if so, how. If it's impossible, I'll just leave the label as is.

A: I can't test this, as I use Linux, which uses a bitmap rather than a Browse button but I assume that once you have created the filepickerctrl you can simply adjust the values, as follows:
self.fp_ctrl = wx.FilePickerCtrl(self.panel, wx.ID_ANY, message="Choose a file")
self.fp_ctrl.SetLabel("MyLabel")
self.fp_ctrl.SetLabelText("LabelText")
self.fp_ctrl.SetToolTip("MyLabel Tip")

I assume at least one of the above will be useful but as I said, it is an assumption.
Based on your comment, the easiest answer then, is roll your own e.g:
import  wx

class MyPicker(wx.Frame):
    def __init__(self, parent=None, title=None):
        wx.Frame.__init__(self, parent=None, id=wx.ID_ANY, title=title, size=(-1, 535))
        panel = wx.Panel(self)
        sizer = wx.BoxSizer(wx.HORIZONTAL)
        self.filehandle = wx.TextCtrl(panel, -1, (''), style=wx.TE_READONLY)
        self.select_button = wx.Button(panel, wx.ID_OPEN, "&Navegar")
        self.select_button.Bind(wx.EVT_BUTTON, self.OnButton)
        sizer.Add(self.filehandle, 1, wx.ALL, 10)
        sizer.Add(self.select_button, 0, wx.ALL, 10)
        panel.SetSizer(sizer)
        self.Show()

    def OnButton(self, event):
        dlg = wx.FileDialog(self, style=wx.FD_OPEN|wx.FD_PREVIEW, wildcard="*.png")
        if dlg.ShowModal() == wx.ID_OK:
            self.filehandle.SetValue(dlg.GetPath())
        dlg.Destroy()

app = wx.App()
MyPicker(title="File Picker")
app.MainLoop()

This restricts file selection to png files only with the wildcard argument, just for testing.


text:
Q: Create a GIF for Maya with python threading I want to add a gif element in my custom Maya UI using python. Since Maya doens't accept animated images as input I created a while loop and edit the input image. To do to that I used Timer and everything works fine, untill I rerun the script. The old thread is somehow still active (altough I kill it every time I run the script)
This is the code I have. I have a start and stop button that work exactly as they are supposed to, but if I rerun the script, the old thread is still active.
from threading import Timer
import time
import maya.cmds as cmds

global t
global N
global B

def initGif():
    global t
    global N
    global B

    terminateGif()
    N = 0

    t = Timer(1.0, startGif)
    t.start()

def startGif():
    global N
    global t
    while N < 1000:
        if N < 1000:
            print "Hello", t # This is where the actual images would iterate instead of "Hello"
            time.sleep(5)
        else:
            terminateGif()
            continue

def terminateGif():
    global t
    global N
    N = 9999999

    try:
        t.cancel()
    except:
        t = "None"
        return

def UI():
    if cmds.window("win", exists = True):
        cmds.deleteUI("win")
    cmds.window("win", w = 500, h = 500)

    cmds.columnLayout()
    cmds.button("stop", c = lambda *args : terminateGif())
    cmds.button("start", c = lambda *args : initGif())

    cmds.showWindow("win")

UI()
initGif()

A: The fact that you're trying to get a gif working with threading and a timer is just asking for Maya to crash, or at least slow down the scene's performance.
Instead of bearing all of the overhead, I strongly recommend you just use PySide, which is built-in to Maya anyways. Here's a simple example without having to deal with the nightmare that is threading:
from PySide2 import QtCore
from PySide2 import QtGui
from PySide2 import QtWidgets

class Win(QtWidgets.QWidget):

    def __init__(self, parent=None):
        super(Win, self).__init__(parent)

        self.setWindowTitle("Gif Example")
        self.resize(500, 500)

        self.movie = QtGui.QMovie("/PATH/TO/YOUR/GIF.gif")  # Set your gif path here.
        self.movie.setScaledSize(QtCore.QSize(150, 150))  # You can resize it too.
        self.movie.start()

        self.gif = QtWidgets.QLabel(parent=self)  # Use QLabel to display the gif.
        self.gif.setMovie(self.movie)

        self.main_layout = QtWidgets.QVBoxLayout()
        self.main_layout.addWidget(self.gif)
        self.setLayout(self.main_layout)

win = Win()
win.show()


text:
Q: Issues using OleDbConnection to export an image in an excel document in c# I want to export an image to an excel document in c#
The image the following formats:
System.Windows.Media.Imaging.BitmapImage
These are the connection details:
private const string OleDbConnection = "provider=Microsoft.Jet.OLEDB.4.0;Data Source='{0}';Extended Properties=Excel 8.0;";
private const string OleDbInsert = "INSERT INTO [Report] ([Time], [Elapsed], [Description], [Picture]) values( @timestamp, @elapsed, @description, @pic);";
private const string OleDbCreate = "CREATE TABLE [Report] ([Time] varchar(255), [Elapsed] varchar(255), [Description] varchar(255), [pic] blob);";

I am using the following code to write the image in excel:
foreach (var e in Entries)
{

using(var command = new OleDbCommand { Connection = connection, CommandText = OleDbInsert })
{

    command.Parameters.Add(new OleDbParameter("@component", OleDbType.BSTR) { Value = e.val1 });
    command.Parameters.Add(new OleDbParameter("@result", OleDbType.BSTR) { Value = e.val2 });
    command.Parameters.Add(new OleDbParameter("@description", OleDbType.BSTR) { Value = e.val3});

    if (e.EncodedScreenshot != string.Empty)
                        {
                            byte[] imageContent = imageToByteArray(ImageWpfToGDI(e.Picture));
                            OleDbParameter ph = new OleDbParameter("@pic", OleDbType.Binary) { Value = imageContent};
                            ph.Size = imageContent.Length;
                            command.Parameters.Add(ph);
                        }
}

These are the methods I am using:
    public byte[] imageToByteArray(Image imageIn)
    {
        MemoryStream ms = new MemoryStream();
        imageIn.Save(ms, System.Drawing.Imaging.ImageFormat.Gif);
        return ms.ToArray();
    }

    private System.Drawing.Image ImageWpfToGDI(System.Windows.Media.Imaging.BitmapImage image)
    {
        MemoryStream ms = new MemoryStream();
        var encoder = new System.Windows.Media.Imaging.BmpBitmapEncoder();
        encoder.Frames.Add(System.Windows.Media.Imaging.BitmapFrame.Create(image as System.Windows.Media.Imaging.BitmapSource));
        encoder.Save(ms);
        ms.Flush();
        return System.Drawing.Image.FromStream(ms);
    }

All the data exports to the Excel file except the image (and there definitely exists an image). Could you please give me some advice on how to fix this? I have been searching online alot but I still cannot find a solution.
I made some modifications according to this link: Insert and retrieve Image in Access 2007 DB from C# App. I believe my error is because of the image datatypes. What datatype should I use for the image in the DB and OleDbParameter?
Could someone help me out please? I would be grateful with any response.
Many thanks! :)

A: Just incase someone stumbles across the same problem..
I could not find a way to export images to an excel file using OleDbParameter. If anyone knows how to do this then please correct me.
Instead I used this approach: http://csharp.net-informations.com/excel/csharp-insert-picture-excel.htm
With this help: How to insert a picture in to Excel from C# app?
And it works perfectly well.


text:
Q: Parsing adds AM/PM to the datetime for unknown reasons I have this piece of code:
string testdate = File.GetCreationTime(filePath + file).ToString("yyyy-MM-dd HH:mm:ss.fff");
DateTime test1 = DateTime.ParseExact(testdate, "yyyy-MM-dd HH:mm:ss.fff", new CultureInfo("en-US"), DateTimeStyles.None);

On testdate I have the following date: 2017-12-15 09:57:20.626
Now when I try to parse it into datetime this is the result:
test1: 12/15/2017 9:57:20 AM
What I want as result is the exact date on testdate but as a DateTime variable
Why is that happening if I'm using HH for the 24h format? I've seen many post removing the AM and PM, but with a string, I need it as datetime for a query.
EDIT:
Sql Server Query I'm trying to run
SELECT Transnum
FROM transactions
WHERE (txnnum = @Txnnum and txndatetime between @InitDate and @EndDate)

A: A DateTime doesn't "have" am or pm in terms of explicit additions - it just is the time as a pure number; and the time it represents will either be in the am or in the pm.
It is only showing that in your output because the output format (perhaps defaulted, or in the debugger) includes that.
If you don't want to display am or pm, then: change where-ever is displaying test1 to include a format specifier.


text:
Q: "ERROR Failed to write log event to MongoDB due to invalid result [0]" when using NoSQLAppender I get following message
ERROR Failed to write log event to MongoDB due to invalid result [0]

when using NoSQLAppender with log4j2 v2.0-beta8
Despite th error the log event gets written to MongoDB. Do you know how to suppress it ?
Here is my config
<?xml version="1.0" encoding="UTF-8"?>
<configuration status="WARN">
    <appenders>
        <NoSql name="databaseAppender" suppressExceptions="true">
            <MongoDb collectionName="applicationLog" factoryClassName="com.borsch.DBManager" factoryMethodName="getNewMongoClient" writeConcernConstant="NONE" username="root" password="qwe"/>
        </NoSql>
    </appenders>
    <loggers>
        <root level="error">
            <appender-ref ref="databaseAppender"/>
        </root>
    </loggers>
</configuration>

What's even more strange I can't find the code that generates it. I didn't find such string in sources of log4j2.

A: I reported this to maintainers and it was fixed.


text:
Q: EF6 how to check if database model is newer than app model I create an application where many clients use one database. When I create a migration, I have to update the applications to the latest version on all computers. Sometimes it is impossible at one moment. Clients then turn on my application and the application throws an error because it sees that the database is from a newer migration. How to check if the database is from a newer migration in EF6 to handle such an exception and display the appropriate message to the user? It is best to do it in Program.cs at the very beginning of the application start.
Thanks for any tips.

A: You can find the actual version of a database in the migration history table __MigrationHistory containing a MigrationId column which should give you what you want. Here's an article showing how to work with it: https://msdn.microsoft.com/en-us/data/dn456841.aspx

A: Better to use a web app but if you must go the desktop or mobile native route then you can safeguard your application by forcing users to update.
You can create a table in your database as follows:
Application | CurrentVersion| MinVersion

*

*If Client.Version < Server.CurrentVersion then provide the user with optional upgrade notification

*If Client.Version < Server.MinVersion then force the user to upgrade


text:
Q: How to spot a "greedy" algorithm? I am reading a tutorial about "greedy" algorithms but I have a hard time spotting them solving real "Top Coder" problems.
If I know that a given problem can be solved with a "greedy" algorithm it is pretty easy to code the solution. However if I am not told that this problem is "greedy" I can not spot it.
What are the common properties and patterns of the problems solved with "greedy" algorithms? Can I reduce them to one of the known "greedy" problems (e.g. MST)?

A: A part of your problem may be caused by thinking of "greedy problems". There are greedy algorithms and problems where there is a greedy algorithm, that leads to an optimal solution. There are other hard problems that can also be solved by greedy algorithms but the result will not necessarily be optimal.
For example, for the bin packing problem, there are several greedy algorithms all of them with much better complexity than the exponential algorithm, but you can only be sure that you'll get a solution that is below a certain threshold compared to the optimal solution.
Only regarding problems where greedy algorithms will lead to an optimal solution, my guess would be that an inductive correctness proof feels totally natural and easy. For every single one of your greedy steps, it is quite clear that this was the best thing to do.
Typically problems with optimal, greedy solutions are easy anyway, and others will force you to come up with a greedy heuristic, because of complexity limitations. Usually a meaningful reduction would be showing that your problem is in fact at least NP-hard and hence you know you'll have to find a heuristic. For those problems, I'm a big fan of trying out. Implement your algorithm and try to find out if solutions are "pretty good" (ideal if you also have a slow but correct algorithm you can compare results against, otherwise you might need manually created ground truths). Only if you have something that works well, try to think why and maybe even try to come up with proof of boundaries. Maybe it works, maybe you'll spot border cases where it doesn't work and needs refinement.

A: Formally, you'd have to prove the matroid property of course. However, I assume that in terms of topcoder you rather want to find out quickly if a problem can be approached greedily or not.
In that case, the most important point is the optimal sub-structure property. For this, you have to be able to spot that the problem can be decomposed into sub-problems and that their optimal solution is part of the optimal solution of the whole problem.
Of course, greedy problems come in such a wide variety that it's next to impossible to offer a general correct answer to your question. My best advice would hence be to think somewhere along these lines:

*

*Do I have a choice between different alternatives at some point?

*Does this choice result in sub-problems that can be solved individually?

*Will I be able to use the solution of the sub-problem to derive a solution for the overall problem?

Together with loads and loads of experience (just had to say that, too) this should help you to quickly spot greedy problems. Of course, you may eventually classify a problem as greedy, which is not. In that case, you can only hope to realize it before working on the code for too long.
(Again, for reference, I assume a topcoder context.. for anything more realistic and of practical consequence I strongly advise to actually verify the matroid structure before selecting a greedy algorithm.)

A: "A term used to describe a family of algorithms. Most algorithms try to reach some "good" configuration from some initial configuration, making only legal moves. There is often some measure of "goodness" of the solution (assuming one is found).
The greedy algorithm always tries to perform the best legal move it can. Note that this criterion is local: the greedy algorithm doesn't "think ahead", agreeing to perform some mediocre-looking move now, which will allow better moves later.
For instance, the greedy algorithm for egyptian fractions is trying to find a representation with small denominators. Instead of looking for a representation where the last denominator is small, it takes at each step the smallest legal denominator. In general, this leads to very large denominators at later steps.
The main advantage of the greedy algorithm is usually simplicity of analysis. It is usually also very easy to program. Unfortunately, it is often sub-optimal."
                                                                  --- ariels
(http://www.everything2.com/title/greedy+algorithm?searchy=search)


text:
Q: the location(x,y) of java swing 'JLabel' and Graphics elements are not same I have to draw a JLabel with an onclick event on an drawn circle. The newly created JLabel should be placed placed very closed a line which is already created. I was trying to draw this JLabel at the middle position of the line. But problem is, even after setting fixed calculated coordinates(x,y), the JLabel is not drawn in the given location.(unlike g.drawLine() or g.drawOval()). My code is given below: need help to fix it.
    public class ButtonExample extends JFrame{
    JFrame frame;
    JLabel label1, label2, label3;
    private Shape myShape;
    private int arrowAdded = 0;
    public ButtonExample() {
        super("Location test of JLabel and Graphics objects");

        label1 = new JLabel("0,0");
        //label2 = new JLabel("40,40");

        label1.setBounds(0, 0, 50, 50);
        label1.setBorder(BorderFactory.createLineBorder(Color.black));
        //label2.setBounds(100, 100, 50, 50);
        //label2.setBorder(BorderFactory.createLineBorder(Color.black));

        add(label1);
        //add(label2);

        repaint();

         addMouseListener(new MouseAdapter() {
             @Override
             public void mouseClicked(MouseEvent me) {
                super.mouseClicked(me);
                if (myShape.contains(me.getPoint())) {
                    arrowAdded = 1;
                    repaint();
                }
             }
         });

        setLayout(null);
        setSize(1000,600);
        setLocationRelativeTo(null);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setVisible(true);

    }

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

    public void paint(Graphics g){
        super.paint(g);
        int startX = 100;
        int startY = 100;
        int endX = 180;
        int endY = 120;

        g.setColor(new Color(0, 255, 0));
        myShape = new Ellipse2D.Double(startX, startY, 30, 30);
        Graphics2D g2d = (Graphics2D) g;
        g2d.draw(myShape);
        g.drawLine(startX, startY, endX, endY);

        int lX = (int)Math.abs(endX-startX)/2;
        int lY = (int)Math.abs(endY-startY)/2;

        if(endX>startX) {
            lX = lX+startX;
        }else {
            lX = lX+endX;
        }

        if(endY>startY) {
            lY = lY+startY;
        }else {
            lY = lY+endY;
        }

        if(arrowAdded == 1) {
            label3 = new JLabel();
            label3.setBounds(lX, lY, 20, 15);
            label3.setBorder(BorderFactory.createLineBorder(Color.black));
            add(label3);
            g.drawRect(lX, lY, 20, 15);
        }enter code here
    }

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

}

A: Change your code
int lX = (int)Math.abs(endX-startX) / 2;
int lY = (int)Math.abs(endY-startY) / 2;

to
int lX = (endX-startX) / 2;
int lY = (endY-startY) / 2;

and your rectangle (left upper corner) will be placed in the middle position of the line (you can still set an offset if it´s too close :-) )

A: Don't override paint() on a JFrame!
The frame includes the title bar and borders, so you can't just paint at (0, 0). You would need your painting to be offset by the frame decorations.
Instead, custom painting should be done by overriding the paintComponent(...) method of a JPanel and then you add the panel to the frame. Now the offsets will be relative to the panel, so you can use (0, 0). Of course you would also add the label to the panel at your desired location.
Read the section from the Swing tutorial on Custom Painting for more information and working examples.


text:
Q: Rewrite Custom Fields url I use custom fields named 'url' to add another website url (like http://www.youtube.com), I want to rewrite the 'url' as http://www.mysite.com/go/123.
I tried all rewrite plugins, no one could do this.
Can I set post id as 123? Or can I set a random number as it?

A: Take a look at this tutorial (Build a Short URL Service with WordPress Custom Post Types)
that show how to create this kind of redirection
or you can use a plugin that does that for you GoTo Redirect

A: Thanks for your reply, I want to auto rewrite link when I add it in custom fields named "url".
For example:
I named a "url" in custom fields add www.yahoo.com as value, I use <?php echo get_post_meta($post->ID, 'url', true); ?> to get it, I don't want to show the link www.yahoo.com, I want to rewrite it as www.mysite.com/29382 with random number automatically generated.


text:
Q: Error Binary XML file line #7: Error inflating class com.esri.android.map.MapView I set ArcGIS Runtime SDK for Android but run show error
 Binary XML file line #7: Error inflating class com.esri.android.map.MapView
Caused by: java.lang.UnsatisfiedLinkError: No implementation found for long com.esri.android.map.MapSurface.nativeMapCreate(java.lang.String, int, int, float, boolean) (tried Java_com_esri_android_map_MapSurface_nativeMapCreate and Java_com_esri_android_map_MapSurface_nativeMapCreate__Ljava_lang_String_2IIFZ)
And my code
dependencies {
compile fileTree(include: ['*.jar'], dir: 'libs')
androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
    exclude group: 'com.android.support', module: 'support-annotations'
})
compile 'org.slf4j:slf4j-api:1.7.25'
compile "org.jetbrains.kotlin:kotlin-stdlib-jre7:$kotlin_version"
compile 'com.android.support:appcompat-v7:25.3.1'
compile 'com.android.support:design:25.3.1'
compile 'com.google.android.gms:play-services-maps:11.0.4'
compile 'com.android.support:recyclerview-v7:25.3.1'
compile 'com.android.support:support-v4:25.3.1'
compile 'pl.bclogic:pulsator4droid:1.0.3'
compile 'com.esri.arcgisruntime:arcgis-android:100.1.0'
compile 'com.android.support.constraint:constraint-layout:1.0.2'
compile 'com.makeramen:roundedimageview:2.3.0'
testCompile 'junit:junit:4.12'

}
repositories {
    mavenCentral()
}
android {
    packagingOptions {
        exclude 'META-INF/LGPL2.1'
        exclude 'META-INF/DEPENDENCIES'
        exclude 'META-INF/NOTICE'
        exclude 'META-INF/LICENSE'
        exclude 'META-INF/LICENSE.txt'
        exclude 'META-INF/NOTICE.txt'
    }
}

And my fragment
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    // Inflate the layout for this fragment
    View view = inflater.inflate(R.layout.fragment_map, container, false);
    mMapView = (MapView) view.findViewById(R.id.map);
    try {
        shapefileTable = new ShapefileFeatureTable("file:///android_asset/yourPath/vietnam.shp");
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    }
    FeatureLayer featureLayer = new FeatureLayer(shapefileTable);

    UniqueValueRenderer uvRenderer = new UniqueValueRenderer();
    uvRenderer.setDefaultSymbol(new SimpleFillSymbol(R.color.colorPrimary, null));
    // set renderer
    featureLayer.setRenderer(uvRenderer);
    mMapView.addLayer(featureLayer);
    return view;
}

A: It looks like you're using code from the 10.2.x release but are importing the 100.1.0 release within your gradle script. The API has changed between those releases.

A: There is one more possibility to get this exception. If you don't add these lines in your app-level build.gradle file under android. As mentioned here
android {
    compileOptions {
        sourceCompatibility = 1.8
        targetCompatibility = 1.8
    }
}


text:
Q: Nested angular google maps components don't render I am using AGM (Angular Google Maps) and I want to create a set of my own custom components that wrap AGM components to allow high reuse within my app.
When I do this, however, the markers (in this example) don't seem to render on the map, yet I get no errors. I wonder if this is something to do with nesting the components within <ng-content>
Can anyone help? I have a stackblitz setup. Please see the updates at the bottom for an Angular 7 Stackblitz using Slot.
The TLDR: When I have nested custom components it creates an ng-content HTML element middle man which seems to break agm functionality.
My core component is vmap
@Component({
  selector: "v-map",
  template: `<agm-map flex [latitude]="lat" [longitude]="lng">
                    <ng-content></ng-content>
                    <!--agm-marker [latitude]="lat" [longitude]="lng"></agm-marker-->
                </agm-map>`
})
export class VMapComponent {
  lat: number = 51.678418;
  lng: number = 7.809007;

  constructor(private loader: MapsAPILoader) {
  }
}

Note that if I comment back in the agm-marker in the template, it renders.  It only seems to not work when within ng-content.
Here is the v-map-plots sub-component
@Component({
  selector: "v-map-plots",
  template: `<agm-marker *ngFor="let plot of plots" [latitude]="plot.Latitude" [longitude]="plot.Longitude"></agm-marker>`
})
export class VMapPlotsComponent {
  @Input() plots: IPlot[] = [];

  constructor(@Host() private parent: VMapComponent) {
    this.plots.push({ Latitude: 51.678418, Longitude: 7.809007 })
  }
}

Is this an AGM issue or an Angular issue?
Is this related to ng-content?
Is there a way around it?
Update
As per @Anytoe's comment here is my use case:
<v-map>
  <v-map-plots [plots]="displayPlots"></v-map-plots>
</v-map>

The idea being I can make a number of reusable maps components that I can then reuse throughout my app where needed.
Update 2 I read about Slot and thought that could help me, so setup a new Stackblitz for Angular 7 and used slot but also could not get this working

A: First of all, I you are working under the Angular ecosystem, I would recommend you to use ng-content and explote all its features. Slot tag is for projecting content into HTML5 template tag, the functionality is quite the same, but if you are working under Angular use ng-content since is more powerful and versatile.
Said that, I have watch your stackblitz, it says that ther is No provider for MarkerManager. This means that when the AgmsMarkers are created, the MarkerManager provider isn't instantiated.
I have search a little bit, and I saw that this way you compose the components, with v-map and v-map-plots, the order of creation is the next one:
1- v-map
   2- v-map-plots
      3- agm-marker
4- agm-map

Angular created first the projected content on v-map, so the AgmMarker is created before the AgmMap. This is the reason there is no provider for MarkerManager since it is created by AgmMap component.
Given this situation, what I would simply do is non wrapping the agm-map. I think it would have no impact in what you are trying to do, since you can compose as much components inside as you want, like this:
<agm-map flex [latitude]="lat" [longitude]="lng">
    <v-map-plots></v-map-plots>
</agm-map>

I made a fork of your stackblitz showing it: https://stackblitz.com/edit/angular-7-master-7jvsjr
Hope this helps!

A: As it is already described in the other answer the issue is that the design of the AGM library is such that it does not work with content projection. When you use it in your case the content elements are created before the component that wraps it which does not work in this case because the agm-marker-elements are created first and they need services from the agm-map component which has not yet been created. It gets created after the content has been prepared.
I suggest another workaround solution with which allows you to keep your design. For this solution you change the v-map-plots component into a directive so it does not have any rendering. This means that you don't need any content projection and instead just get all the v-map-plots directives by using the @ContentChildren decorator inside the v-map component. Then render both the agm-map and agm-markers in the v-map component using the data from the directives.
Here is how this would look like:
@Directive({
  selector: "v-map-plots"
})
export class VMapPlotsDirective {
  plots: IPlot[] = [];

  constructor(@Host() @Inject(forwardRef(() => VMapComponent)) private parent: VMapComponent) {

    this.plots.push({ Latitude: 51.678418, Longitude: 7.809007 })
    console.log("yo", this.plots);
  }
}

@Component({
  selector: "v-map",
  template: `<agm-map flex [latitude]="lat" [longitude]="lng">
              <ng-container *ngFor="let vMapPlotsDirective of vMapPlotsDirectives">
                <agm-marker *ngFor="let plot of vMapPlotsDirective.plots" [latitude]="plot.Latitude" [longitude]="plot.Longitude"></agm-marker>
              </ng-container>
            </agm-map>`
})
export class VMapComponent {
  lat: number = 51.678418;
  lng: number = 7.809007;
  @ContentChildren(VMapPlotsDirective) vMapPlotsDirectives;

  constructor(private loader: MapsAPILoader) {
  }
}

Here is also an implementation of this in StackBlitz so you can see it in action.


text:
Q: angular material md-error ngIf not work I'm trying to validate passwords with angular materials, but it don't work when tag <md-error> include in <md-form-field>. You can see where it works and where don't. What I do wrong?
  import { Component, OnInit } from '@angular/core';
  import 'rxjs/add/operator/map';
  import {
      AbstractControl,
      FormControl,
      Validators,
      FormGroup,
      FormBuilder,
      FormsModule,
      FormGroupDirective,
      NgForm
  } from '@angular/forms';

  function passwordMatcher(c: AbstractControl) {
      if (!c.get('password') || !c.get('confirm')) return null;
      return c.get('password').value === c.get('confirm').value ? null
   : {'nomatch': true};
  }

  @Component({
    selector: 'app-testing',
    template: `

        <form [formGroup]="form">

                <md-form-field>
                    <input mdInput
                           formControlName="password">
                </md-form-field>
                <md-form-field>
                    <input mdInput
                           formControlName="confirm">
                    <md-error
     *ngIf="form.hasError('nomatch','account')">
                        THIS DOESN'T WORK
                    </md-error>
                </md-form-field>

        </form>

        <md-error *ngIf="form.hasError('nomatch','account')">
            THIS WORK
        </md-error>

{{form.value | json}}

{{form.status}}

{{form.get('account.confirm').status}}

        {{form.hasError('nomatch', 'account')}}
    `,
    styleUrls: ['./testing.component.css']
  })
  export class TestingComponent implements OnInit {

      form: FormGroup;

      constructor(public fb: FormBuilder) {
          this.form = this.fb.group({
              account: this.fb.group({
                  password: '',
                  confirm: ''
              }, {validator: passwordMatcher})
          });
      }

      ngOnInit() {
      }

  }

A: try to add the following code
<md-form-field>
                <input mdInput
                       formControlName="confirm" [errorStateMatcher]="myErrorStateMatcher.bind(this)">
                <md-error
 *ngIf="form.hasError('nomatch','account')">
                    THIS DOESN'T WORK
                </md-error>
            </md-form-field>

in the component add function
    myErrorStateMatcher(){

  return  this.form.controls["account"].getError("nomatch");

}


text:
Q: Tips on using proguard for testing I need to use proguard when running my android app in debug mode. My app seems to be hitting the dreaded 64K method limit and so proguard is the only way my apk is built successfully.
That being said, using proguard for running tests take INFINITELY long. Running it through the emulator is slow enough, but adding the proguard processing makes it even more slower.
Q. Are there any tips on reducing the time proguard takes for processing?
Some possible ideas? :

*

*Instruct Proguard to only shrink and do absolutely nothing else (possibly saving in build time)

*Ability to run tests without building the apk?

A: After trying out a bunch of things, I've found that decreasing the number of things you do in your proguard configuration (like optimization passes/no obfuscation) shave off a couple of seconds, but it's all marginal compared to the amount of time introduced by proguard overall.
The wait time was unbearable, so i reverted to using jarjar and stripping off methods from my external libraries (google play services/guava). I use proguard only for release builds now, so atleast my debug builds are faster.


text:
Q: will this output a random shuffle a million times? rand() c++ i'm attempting to run a million simulations of a card game to return a percentage "casino house edge."
my understanding of the rand() function is not clear enough to know whether this will generate a new shuffle every time or if it has a limit. in other words, at some point into the million games, will the same patterns of shuffles emerge?
  srand(time(NULL));

for (int games=0;games<iGames;games++){

                  ///shuffle///
for (int i=0; i<(iUserDeckSize-1); i++) {
    int r = i + (rand() % (iUserDeckSize-i)); // Random remaining position.
    card temp = cards[i]; cards[i] = cards[r]; cards[r] = temp;
}

// rest of card game code goes here
}

A: I believe it's implementation specific, see here for instance What common algorithms are used for C's rand()?.  But I'd be astounded if practical implementations began repeating that quickly, I would have thought you'd at least get into the billions allowed by an int32.

A: No for 2 reasons (one you thought about and one not-so-obvious).
The algorithm you are using is wrong. Setting aside worrisome -1 (the last element will not be shuffled at all) you have n^n possible runs (space of received random numbers) while there is n! possible shuffles. In general n! is not a factor of n^n hence you have biased output (i.e. some outcomes will occur more often then others). I would recommend either implement the Knuth-Tares shuffle or use already implemented algorithm like random_shuffle from <algorithm>.
That said - you need to have the PRNG which have at least n! states. Depending on the deck size rand() may not be enough - it typically have ~48 bits while standard 52-card deck have ~225 bits of state (log2(52!)) - in other words there is no chance of hitting some sequences (it might not be a problem but overhead of better PRNG is negligible). I would look on boost random as it have several good PRNG implementations and at least one would probably be sufficiently good (say mt11213b for 52-card example).


text:
Q: What is the correct statement of this Erdös-Gallai-Tuza problem generalizing Turan's triangle theorem? In Zsolt Tuza's Unsolved combinatorial problems I, Problem 46 is the following conjecture:
Let $G$ be a graph on $n$ vertices. Let $\alpha_1$ be the maximum number of edges of $G$ such that every triangle in $G$ contains at most one of these edges. Let $\tau_1$ be the minimum number of edges of $G$ such that every triangle in $G$ contains at least one of these edges. Then, it is conjectured that $\alpha_1+\tau_1 \leq \dfrac{n^2}{4}$.
The reference given is Paul Erdös, Tibor Gallai, Zsolt Tuza, Covering and independence in triangle structures, Discrete Mathematics 150 (1996) pp. 89-101. However, in this reference, the conjecture is only formulated (Conjecture 11) for the case when $G$ is a triangular graph (i. e., every edge of $G$ is contained in a triangle). Maybe I am missing something completely obvious, but is this really equivalent, or did Tuza extend his conjecture after this publication? Or is one of the statements wrong resp. mistakenly specialized? (Note that the conjecture for generic $G$ clearly generalizes Turan's theorem for $K_3$'s, but in the triangular case I don't see how it yields Turan.)
(Also, are there any news on this question?)

A: I hope I am not violating any kind of MathOverflow etiquette by responding to a question 2 years after it has been asked, but your question is answered in the following preprint of mine that just hit the arXiv: http://arxiv.org/abs/1408.5176
The preprint shows that any vertex-minimal counterexample to the Erdős--Gallai--Tuza Conjecture has minimum degree greater than n/2; in particular, such graphs are triangular. Thus, the "triangular" version and the unrestricted version are equivalent.
The proof is not difficult, but (at the risk of flattering myself) I don't think it is entirely trivial either.


text:
Q: A ''strange'' integral from WolframAlpha I want integrate:
$$
\int \frac{1}{\sqrt{|x|}} \, dx
$$
so I divide for two cases
$$
x>0 \Rightarrow \int \frac{1}{\sqrt{x}} \, dx= 2\sqrt{x}+c
$$
$$
x<0 \Rightarrow \int \frac{1}{\sqrt{-x}} \, dx= -2\sqrt{-x}+c
$$
But WolframAlpha gives:
$$
\int \frac{1}{\sqrt{|x|}} \, dx=\left(\sqrt{-x}+\sqrt{x} \right)\operatorname{sgn}(x)-\sqrt{-x}+\sqrt{x}  +c
$$
How I can interpret this result? Maybe I'm wrong?

A: Since the function is not defined for $x=0$, it's not really meaningful to have a single constant of integration for the whole thing. The most general function $F$ (not defined at $0$) for which, at each point $x\ne0$, $F'(x)=\frac{1}{\sqrt{|x|}}$, is
$$
F(x)=\begin{cases}
-2\sqrt{-x}+c_1 & \text{if $x<0$}\\
2\sqrt{x}+c_2 & \text{if $x>0$}
\end{cases}
$$
where $c_1$ and $c_2$ are arbitrary constants.
Among these functions there are some that can be extended by continuity at $0$, namely those for which $c_1=c_2$, but they're just a special case. Note that none of these special functions is differentiable at $0$.

A: Using $\operatorname{sgn}(x)$ is just a (half-dirty) trick to put the two cases into one. Put in $-1$ vs. $+1$ for $\operatorname{sgn}(x)$ and your eyes will be open.


text:
Q: How to use optional command line arguments in a python function? I want a more compact and scalable way to use command line args to feed a python function, here is what i have:
def getRelevant (number = 5, sortBy = "Change"):
    number, sortBy = int(number), sortBy
    relevant = ...
    return relevant

if __name__ == "__main__":
    if len(sys.argv) == 3:
        print(getRelevant(sys.argv[1], sys.argv[2]))
    elif len(sys.argv) == 2:
        print(getRelevant(sys.argv[1]))
    else:
        print(getRelevant())

It works. But I'm not happy with this conditionals, is there a way to make it simpler?

A: You can try with argparse or Typer
argparse: https://docs.python.org/3/library/argparse.html
typer: https://typer.tiangolo.com/

A: Argparse should do this. It is feature rich and flexible.
For your case, the below does the job:
import argparse
parser = argparse.ArgumentParser(description='Description of your app here.')
parser.add_argument('-N', '--integers', default=5,  help='your help text here')
parser.add_argument('-S', '--sortby', default='Change', choices=['Change', 'SomeOtherOption'], help='some help text here ')

if __name__ == "__main__":
  args = parser.parse_args()
  print(args.integers) # prints 5 if nothing provided
  print(args.sortby)  # prints 'Change' if nothing provided

A: argparse is of course the tool you want to learn for commandline options and arguments - it's part of the tools alls devs should know about (with logging and pdb).
This being said, for this exact case, you could also solve the issue very simply without argparse:
if __name__ == "__main__":
    args = sys.argv[1:]
    print(getRelevant(*args))


text:
Q: Salesforce Console event not sent successfully when reloading page I'm working in the Salesforce Service Console with the console integration toolkit. This allows us to fire (HTML5) events with the sforce.console.fireEvent() command. I firing an event from one console component (a visualforce page) that will be caught by an event listener on another console component (another visualforce page). Normally this kind of event passing works, but when I try to fire an event and then refresh the page that I'm by setting location = ... my event does not fire successfully.
What am I doing wrong?

A: The events that are fired in the console are asynchronous events, similar to callouts to other web services. When you do something that refreshes the page (such as setting location=...) this triggers a Javascript unload() event. By design, when a browser is unloading a page it does a whole bunch of stuff, including dropping any asynchronous events it had initiated. This means that your fireEvent() call is just dropped and does nothing.
I've tried a number of workarounds to this, but the most reliable is to fire the event using it's optional callback function and then reload the page that you're firing the event from only after the event has been sent. For example:
var reloadPageAfterEventReturns = function(callResult) {
  if (callResult.success) {
    location = "/apex/newLocation";
  }
}
sforce.console.fireEvent("myEvent", "Event message", reloadPageAfterEventReturns);


text:
Q: SSO webapp: home-made or factory-made solution? Target
I have 2 webapps (in the future can be more) on the company server. User accounts in the first are different from those for the second webapp, but I can define a mapping among them.
My aim is to allow the user to login only once and gain access for both webapps. The solution is obviously the Single sign-on. I need a SSO webapp and the other webapps must rely on it to authenticate the users. I think I'll follow this good pattern.
I work on Tomcat 7.0.
Users and mapping

*

*Users for webapp1 are in a DB.

*Users for webapp2 should come from a mapping of the former ones.

E.g. user 'Alice' in webapp1 corresponds to user 'Lisa' in webapp2; so the SSO should communicate that the user who has just logged in is 'Alice' to webapp1 and 'Lisa' to webapp2).
Question
Is it better to write my home made SSO webapp or is there any useful open source webapp ready to use (also with a little customization) that can do SSO?
I also read about SAML, but I can't figure out if it's worth to implement such a protocol for my use case.
Thanks!

A: Use Tomcat Authentication. It includes a set of authentication modules and can be configured to allow access to configured websites. For more details see here.

A: At the end I realized it's better to build an home-made solution, even if you have to put attention on the security, because the task is not so hard and it's so difficult to find something that suits to my simple case without an overhead of too many features.


text:
Q: Oauth2 2LO between two apps in GAE I work in a project using GAE.
I have a GAE app that consume Rest services from others GAE apps (this apps uses different Google Apis with 2LO oauth2, eg: one app uses Gcalendar Api, other Gmail Api, ...). The REST apps are in Java and use GoogleCredential for consume Google Apis. All the apps are in same domain (Company is own of all projects).
I need migrate the principal GAE app (also in Java) from 2LO Oauth 1 to 2LO Oauth2.
I see this example but not is 2LO. https://code.google.com/p/google-oauth-java-client/wiki/Samples
Can I use Credential from Google-Oauth-api or GoogleCredential? Or GoogleCredential is only for Google Apis?
Thanks.

A: This [1] is the 2LO OAuth 2.0 implementation of Google OAuth you can use on App Engine and is usually refereed as the OAuth for Server to Server Applications on public documentation. This method requires of a Service Account that you can obtain on the Google Developers Console of your app. More info here [2].
[1] https://developers.google.com/accounts/docs/OAuth2ServiceAccount
[2] https://developers.google.com/api-client-library/java/google-api-java-client/app-engine


text:
Q: Angular 7 animations - Transition not working I looked at other questions around the same issue and none of the solutions provided worked for me.
I'm using Angular 7.2 with "@angular/animations": "~7.2.0".
I have a div which I want to fade in and fade out. So I have applied an opacity animation to it. This same div, I use *ngIf to add it and remove it from HTML.
The problem is, the animation styles (opacity) is getting applied correctly but it's not transitioning nicely from opacity 1 > 0 or 0 > 1.
HTML:
<div *ngIf="divToShow.value !== 'none'" [@openClose]="openState">Dynamic Content Here</div>

Animation:
animations: [
    trigger('openClose', [
      state('true', style({
        opacity: '1'
      })),
      state('false', style({
        opacity: '0'
      })),
      transition('true => false', [
        animate('10s')
      ]),
      transition('false => true', [
        animate('10s')
      ]),
    ]),
  ],

Getter:
public get openState(): string {
    if (this.divToShow.value !== 'none') {
      return 'true';
    } else {
      return 'false';
    }
  }

divToShow will be 'none' when no div is to be shown. When it does need to show a div it will have the div name as a string.
Can you please advice what I'm doing wrong here?

A: *ngIf="divToShow.value !== 'none'"

The above will remove the <div> when the condition is false, but you can't fade in or out if the <div> doesn't exist.
Angular gives you a transition state to apply animations for when elements are added or removed from the DOM.
        trigger('openClose', [
            transition(':enter', [
                style({opacity: 0}),
                animate('10s', style({opacity: 1}))
            ]),
            transition(':leave', [
                style({opacity: 1}),
                animate('10s', style({opacity: 0}))
            ])
        ])

See: https://angular.io/guide/transition-and-triggers#enter-and-leave-aliases


text:
Q: How to Start and Terminate HTTP server using a bat file in Jenkins in build step I Have a bat script that starts a simple node http server .
Here is my scenario

1)Start HTTP server using bat file (When i include this in build step
  in jenkins the jenkins do not move furthur and keep on waiting and
  does not execute rest of steps) 2) Run some test case 3 )Terminate the
  HTTP server

A: You need to make sure that your batch file starts the HTTP server process in the background, which will prevent Jenkins from waiting.
This answer to the question on running bat files in the background should be able to help.


text:
Q: Trying to convert a variable in PHP to an array I've got a variable that I've retrieved from an API call, and am trying to convert the output in to an array.  Below is an example of the output:
{"id":"4335416","linkId":4335416,"title":"Website 1","slashtag":"1","destination":"http://website1.com","createdAt":"2017-09-20T12:10:56.000Z","updatedAt":"2017-12-01T13:59:35.000Z","status":"active","clicks":722,"lastClickDate":"2018-01-28T15:47:21.000Z","lastClickAt":"2018-01-28T15:47:21.000Z","isPublic":false,"shortUrl":"url.st/1","domainId":"abc123","domainName":"url.st","domain":{"id":"abc123","ref":"/domains/abc123","fullName":"url.st","active":true},"https":false,"favourite":false,"creator":{"id":"321cba","fullName":"user123","avatarUrl":"https://s.gravatar.com/avatar/"}},
{"id":"4335402","linkId":4335402,"title":"Website 2","slashtag":"2","destination":"http://website2.com","createdAt":"2017-09-20T12:09:29.000Z","updatedAt":"2017-12-01T13:58:56.000Z","status":"active","clicks":234,"lastClickDate":"2018-01-28T13:44:29.000Z","lastClickAt":"2018-01-28T13:44:29.000Z","isPublic":false,"shortUrl":"url.st/2","domainId":"abc123","domainName":"url.st","domain":{"id":"abc123","ref":"/domains/abc123","fullName":"url.st","active":true},"https":false,"favourite":false,"creator":{"id":"321cba","fullName":"user123","avatarUrl":"https://s.gravatar.com/avatar/"}},
{"id":"4335375","linkId":4335375,"title":"Website 3","slashtag":"3","destination":"http://website3.com","createdAt":"2017-09-20T12:07:23.000Z","updatedAt":"2017-12-20T18:43:17.000Z","status":"active","clicks":111,"lastClickDate":null,"lastClickAt":null,"isPublic":false,"shortUrl":"url.st/3","domainId":"abc123","domainName":"url.st","domain":{"id":"abc123","ref":"/domains/abc123","fullName":"url.st","active":true},"https":false,"favourite":false,"creator":{"id":"321cba","fullName":"user123","avatarUrl":"https://s.gravatar.com/avatar/"}}

I would like it to create an array within an array, as below:
$myArray = array( array( id => "4335416",
                      linkId => 4335416,
                      title => "Website 1",
                      slashtag => "1",
                      destination => "http://website1.com",
                      ...
                    ),
               array( id => "4335402",
                      linkId => 4335402,
                      title => "Website 2",
                      slashtag => "2",
                      destination => "http://website2.com",
                      ...
                    )
               array( id => "4335375",
                      linkId => 4335375,
                      title => "Website 3",
                      slashtag => "3",
                      destination => "http://website3.com",
                      ...
                    )
             );

Completely stumped on this...  Although my head has been spinning all day trying to do stuff :(
Thanks a lot :)

A: You can convert it to an array with:
json_decode($myArray, true);
The second argument true will make it an associative array which has the named keys from your JSON data.
json_decode documentation

A: You are looking for json_decode('APIcallValue', true)
PHP manual

A: This API response appears to be JSON.
Try doing:
$myArray = json_decode($api_response, true);

Where $api_response is the API response variable

A: Thanks for that guys...
json_decode($api_response, true)

worked perfect.  How simple when you know all the different commands!  lmao.  Should've just posted here first off...  Saved me a couple of hours...
Thanks again


text:
Q: What is x-axis in variable importance in R? I am using package caret in R to measure variable importance of random forest model.
My question is, what is the X-axis of the importance plot caret provided? An example could be found at http://topepo.github.io/caret/varimp.html, at the bottom of the web page. The X-axis range from 0 to 20, but what does it mean?
Thanks,

A: It looks to be a combination of the importance functions from the RandomForest and party packages, Partial Least Squares and Recursive Partitioning. More info here under Details when going down to Random Forest.
http://www.inside-r.org/packages/cran/caret/docs/varimp


text:
Q: Filtering an array with multiple conditions I got two arrays with some objects which I receive from API calls.
I need to combine those in one single array, but some objects are in different states on my app. So, if the objects in both array got the same "Code" attribute, I need to keep the one with more information.
I tried to make and nested loop (yeah, from what I read it's a poor technique, but I will never get more than 5 items at the same time). Then I tried to compare both "code objects", and push the equal results on a new array, which works fine. When I try to use a second condition on the same loop, it just doesn't work.

let array1 = [{
    'DataCad': "2019-01-04T15:04:02.663",
    'Field1': "rt",
    'Code': "DFG3456",
  },
  {
    'DataCad': "2019-01-07T11:37:31.8",
    'Field1': "TESTE2",
    'Code': "TYU1235",
  },
  {
    'DataCad': "2019-01-07T13:15:48.97",
    'Field1': "Uppercase",
    'Code': "JJJ1212",
  },
  {
    'DataCad': "2019-01-07T16:35:32.697",
    'Field1': "234",
    'Code': "OOO1111",
  },
  {
    'DataCad': "2019-01-07T10:46:46.437",
    'Field1': "TESTE1",
    'Code': "GHJ1234",
  }
]

let array2 = [{
    'DataAge': "2019-01-07",
    'DataCad': "2019-01-04T15:04:49.05",
    'HoraAge': "12:25",
    'Field1': "rt",
    'Pag': "N",
    'Code': "DFG3456",
  },
  {
    'DataAge': "2019-01-07",
    'DataCad': "2019-01-07T11:17:57.583",
    'HoraAge': "13:15",
    'Field1': "TESTE1",
    'Pag': "N",
    'Code': "GHJ1234",
  },
  {
    'DataAge': "2019-01-08",
    'DataCad': "2019-01-07T11:38:46.08",
    'HoraAge': "10:15",
    'Field1': "TESTE2",
    'Pag': "N",
    'Code': "TYU1235",
  },
  {
    'DataAge': "2020-01-7 ",
    'DataCad': "2019-01-07T13:16:00.567",
    'HoraAge': "15:15",
    'Field1': "Uppercase",
    'Pag': "N",
    'Code': "JJJ1212",
  }
]

let finalArray = [];

for (var i in array1) {

  for (var j in array2) {
    if (array1[i].Code == array2[j].Code && !array1[i].DataAge) {
      finalArray.push(array1[i].Code)
    }
  }
}

console.log(finalArray);
}

Need to get one single array with those filtered results. Is there a better solution?

A: You could use map method by passing a provided callback function as argument which is applied for every item from your given array.
Also, use find method in order to make Code property matching.

I need to keep the one with more information.

Use Object.keys method in order to decide which object contains more information.

let array1 = [ { 'DataCad': "2019-01-04T15:04:02.663", 'Field1': "rt", 'Code': "DFG3456", }, { 'DataCad': "2019-01-07T11:37:31.8", 'Field1': "TESTE2", 'Code': "TYU1235", }, { 'DataCad': "2019-01-07T13:15:48.97", 'Field1': "Uppercase", 'Code': "JJJ1212", }, { 'DataCad': "2019-01-07T16:35:32.697", 'Field1': "234", 'Code': "OOO1111", } , { 'DataCad': "2019-01-07T10:46:46.437", 'Field1': "TESTE1", 'Code': "GHJ1234", } ]

let array2 = [ { 'DataAge': "2019-01-07", 'DataCad': "2019-01-04T15:04:49.05", 'HoraAge': "12:25", 'Field1': "rt", 'Pag': "N", 'Code': "DFG3456", }, { 'DataAge': "2019-01-07", 'DataCad': "2019-01-07T11:17:57.583", 'HoraAge': "13:15", 'Field1': "TESTE1", 'Pag': "N", 'Code': "GHJ1234", }, { 'DataAge': "2019-01-08", 'DataCad': "2019-01-07T11:38:46.08", 'HoraAge': "10:15", 'Field1': "TESTE2", 'Pag': "N", 'Code': "TYU1235", }, { 'DataAge': "2020-01-7 ", 'DataCad': "2019-01-07T13:16:00.567", 'HoraAge': "15:15", 'Field1': "Uppercase", 'Pag': "N", 'Code': "JJJ1212", } ]

let finalArray = array1.map(function(item){
   let foundItem = array2.find(({Code}) => Code == item.Code);
   if(foundItem)
      return Object.keys(item).length > Object.keys(foundItem).length ? item : foundItem;
   return item;
});
console.log(finalArray);

Here's a short hand and slightly more functional approach too, this approach makes use of techniques such as currying and whatnot, if you'd like to look into functional programming, maybe look up Eric Elliot.

let array1 = [ { 'DataCad': "2019-01-04T15:04:02.663", 'Field1': "rt", 'Code': "DFG3456", }, { 'DataCad': "2019-01-07T11:37:31.8", 'Field1': "TESTE2", 'Code': "TYU1235", }, { 'DataCad': "2019-01-07T13:15:48.97", 'Field1': "Uppercase", 'Code': "JJJ1212", }, { 'DataCad': "2019-01-07T16:35:32.697", 'Field1': "234", 'Code': "OOO1111", } , { 'DataCad': "2019-01-07T10:46:46.437", 'Field1': "TESTE1", 'Code': "GHJ1234", } ]

let array2 = [ { 'DataAge': "2019-01-07", 'DataCad': "2019-01-04T15:04:49.05", 'HoraAge': "12:25", 'Field1': "rt", 'Pag': "N", 'Code': "DFG3456", }, { 'DataAge': "2019-01-07", 'DataCad': "2019-01-07T11:17:57.583", 'HoraAge': "13:15", 'Field1': "TESTE1", 'Pag': "N", 'Code': "GHJ1234", }, { 'DataAge': "2019-01-08", 'DataCad': "2019-01-07T11:38:46.08", 'HoraAge': "10:15", 'Field1': "TESTE2", 'Pag': "N", 'Code': "TYU1235", }, { 'DataAge': "2020-01-7 ", 'DataCad': "2019-01-07T13:16:00.567", 'HoraAge': "15:15", 'Field1': "Uppercase", 'Pag': "N", 'Code': "JJJ1212", } ];

// Finds an object in the givne array based on the code property.
let find = i => a => a.find(({Code}) => Code == i.Code)

// Returns the object with more keys.
let longer = i => o => Object.keys(i).length > Object.keys(o).length ? i : o;

// Returns the relevant array of objects.
let filter = a1 => a2 => a1.map(i => find(i)(a2) ? longer(i)(find(i)(a2)) :  i);

// Fire the filter function.
let finalArray = filter(array1)(array2);

console.log(finalArray); // Log it!

A: You can iteterate over array1 and find the matching element in array2 and then push the element with more information (with more number of properties) in your final array.
let finalArray = [];

let array1 = [
    {
        'DataCad': "2019-01-04T15:04:02.663",
        'Field1': "rt",
        'Code': "DFG3456",
    },
    {
        'DataCad': "2019-01-07T11:37:31.8",
        'Field1': "TESTE2",
        'Code': "TYU1235",
    },
    {
        'DataCad': "2019-01-07T13:15:48.97",
        'Field1': "Uppercase",
        'Code': "JJJ1212",
    },
    {
        'DataCad': "2019-01-07T16:35:32.697",
        'Field1': "234",
        'Code': "OOO1111",
    },
    {
        'DataCad': "2019-01-07T10:46:46.437",
        'Field1': "TESTE1",
        'Code': "GHJ1234",
    }
]

let array2 = [
    {
        'DataAge': "2019-01-07",
        'DataCad': "2019-01-04T15:04:49.05",
        'HoraAge': "12:25",
        'Field1': "rt",
        'Pag': "N",
        'Code': "DFG3456",
    },
    {
        'DataAge': "2019-01-07",
        'DataCad': "2019-01-07T11:17:57.583",
        'HoraAge': "13:15",
        'Field1': "TESTE1",
        'Pag': "N",
        'Code': "GHJ1234",
    },
    {
        'DataAge': "2019-01-08",
        'DataCad': "2019-01-07T11:38:46.08",
        'HoraAge': "10:15",
        'Field1': "TESTE2",
        'Pag': "N",
        'Code': "TYU1235",
    },
    {
        'DataAge': "2020-01-7 ",
        'DataCad': "2019-01-07T13:16:00.567",
        'HoraAge': "15:15",
        'Field1': "Uppercase",
        'Pag': "N",
        'Code': "JJJ1212",
    }
]

array1.forEach(function (element1) {
    var found = array2.find(function (element2) {
        return element2.Code == element1.Code;
    });
    if (found) {
        var requiredElement = Object.keys(element1).length > Object.keys(found).length ? element1 : found;
        finalArray.push(requiredElement);
    }
});
console.log(finalArray);


text:
Q: How I can verify Date input in HTML 5? How I can check if the date input is in the format D/M/Y ?
This is my code :
<input type = "date">test</input>

A: You can use regex to validate any string with javascript:
isValidateDate: (str) => {
  let pattern = /^(?:(?:31(\/|-|\.)(?:0?[13578]|1[02]))\1|(?:(?:29|30)(\/|-|\.)(?:0?[1,3-9]|1[0-2])\2))(?:(?:1[6-9]|[2-9]\d)?\d{2})$|^(?:29(\/|-|\.)0?2\3(?:(?:(?:1[6-9]|[2-9]\d)?(?:0[48]|[2468][048]|[13579][26])|(?:(?:16|[2468][048]|[3579][26])00))))$|^(?:0?[1-9]|1\d|2[0-8])(\/|-|\.)(?:(?:0?[1-9])|(?:1[0-2]))\4(?:(?:1[6-9]|[2-9]\d)?\d{2})$/;
  return pattern.test(str);
}

D/M/Y is not really a standard format for date. I suggest you test with dd/mm/yyyy or yyyy-mm-dd. And you can find the answer here: (Regex to validate date format dd/mm/yyyy)

A: *

*The date input needs a name attribute to be able to be verified

*You can't verify inputs in HTML, you need another language, for example php


text:
Q: cut: the delimiter must be a single character I am just using the script to pull lines count from the file unfortunately I see an error and haven't got the expected count from the file. Kindly someone can help me to get the lines to count from Linux.
LINE_COUNT=`wc -l $TEMP_FILE | cut -d "$TEMP_FILE" -f 1 | sed 's/ //g'`

A: Did you mean cut -d " "? Using a filename as delimiter seems not right to me.

A: Use input redirection instead of a filename argument, then wc won't output the filename, and you won't have to remove it.
line_count=$(wc -l < "$TEMP_FILE" | sed 's/^ *//'g)

Also:

*

*Use $(...) rather than archaic `...`. They're more readable and nest more easily.

*Don't use all-uppercase variables, they're conventionally reserved for environment variables.

*Don't forget to quote the $TEMP_FILE variable.

*Even with this method you still need to remove leading spaces from the output of wc. Or you could skip this step and just not quote $line_count when you use it, as the shell's word splitting will discard the spaces (my generally advice is to quote variables unless you have a good reason not to, and this is one of those reasons).

A: you can use awk
wc -l $TEMP_FILE  | awk '{print $1}'

LINE_COUNT=$(wc -l $TEMP_FILE  | awk '{print $1}')

A: The $TEMP_FILE as the delimiter argument to cut is nonsense; replace it with a space. Besides that, the | sed … is not needed.

A: You could use awk altogether:
$ awk 'END{print NR}' file

It is slower than wc, thou.


text:
Q: Migrate Magnolia from Enterprise Edition to Community Edition Is it possible to migrate Magnolia 5.5 from Enterprise Edition to Community Edition. We have been using Magnolia Enterprise Edition Pro with multisite und commercetools module. We do not need any Professional Edition features and want to keep on our web presence on Magnolia.
Mit freundlichen Grüßen
Alexander Fuchs

A: You can use community licence as long as you don't have any enterprise modules in the webapp. That being said, multisite is an enterprise feature so you have to replace it one way or the other.
Cheers,
Ilgun


text:
Q: Are rolling forecasts more accurate that full-sample forecasts? I compared the auto.arima forecast checkts below  to the rolling forecast fc and noticed that every of the error measures is lower for fc.
Will rolling forecasts have lower errors than a forecasted auto.arima model in general?
Why might that happen?
The data to run the code below is in the "fpp" package. Code:
library("fpp")
library("forecast")

##Multi-step forecasts without re-estimation

h <- 5
train <- window(hsales,end=1989.99)
test <- window(hsales,start=1990)
n <- length(test) - h + 1
fit <- auto.arima(train)
fc <- ts(numeric(n), start=1990+(h-1)/12, freq=12)
for(i in 1:n)
{
  x <- window(hsales, end=1989.99 + (i-1)/12)
  refit <- Arima(x, model=fit)
  fc[i] <- forecast(refit, h=h)$mean[h]
}

checkts<-forecast(fit,h=71)

accuracy(checkts$mean,test)
 accuracy(fc,test) ##All Error measures are lower than Checkts$mean

A: That the rolling forecast is better is not mandatory, but it should not suprise you either. In fact, with the "static" forecast you are using less information (in this example) and have a longer forecast horizon than with the rolling forecast (in this example), so the results tend to be inferior.
For example, if you want to forecast the last value (Nov 95) with the static model, you use information from Jan 73 to Dec 89 and have a forecast horizon of 71 periods. Meanwhile, with the dynamic forecast you use information from Jan 73 to Jun 95 and have a forecast horizon of 5 periods.


text:
Q: SC create binpath error I am trying to run the following command in the PowerShell
sc create StrongSwan binpath= "C:\Users\Kanishk\Desktop\Strong\Strong\stronswan\strongswan-5.6.3\src\charon-svc\charon-svc.exe"

I have checked the path to the .exe is correct and I can cd to it also.
For reference I am following this: https://wiki.strongswan.org/projects/strongswan/wiki/Charon-svc
I am receiving the following error:
Set-Content : A positional parameter cannot be found that accepts argument 'binpath='.
At line:1 char:1
+ sc create NewService binpath= C:\Users\Kanishk\Desktop\Strong\Strong\ ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo          : InvalidArgument: (:) [Set-Content], ParameterBindingException
+ FullyQualifiedErrorId : PositionalParameterNotFound,Microsoft.PowerShell.Commands.SetContentCommand

So my problem is the same command is working on cmd but not on PowerShell. Any reasons why?

A: I ran into this also. It looks like the error happens at line:1 char:1. So I assumed it doesn't understand what "sc" is. So I changed sc create .. to sc.exe create .. and it worked for my service.

A: I was trying with powershell for a while but it didn't work. I thought maybe try it on Command Prompt (as an admin).
[SC] CreateService SUCCESS

A: I ran into this with Powershell as well.
To expand on the answer:
"sc" is an alias in Powershell for "Set-Content" which is confirmed in your output and by the Powershell "Get-Alias" command. That's why sc fails but sc.exe is successful, and why sc works in cmd and fails in powershell.

A: Use Powershell -> Run As Administrator
sc.exe create TestService binPath= "D:\Windows Services\TestService\TestService.exe"
may have to put path under "" if it contains spaces in between


text:
Q: Difference between importing a class or creating an instance of it I have a subclass (Item) in a java class named (tools) that I would like to use in a few different classes in my app now what I would like to know is what is the difference between using
import com.example.tools;

and creating an instance of the class :
Tools item = new Tools();

do they both get the same results and is one slower than the other or is there a reason why I would use one instead of the other . thanks for your answers.

A: import just gives you a shortcut to the name of the class. You could (although it's not recommended) not import the class and simply refer to it as com.example.Tools everywhere. new Tools() actually creates an instance of the class, that you can call methods on, etc.

A: Keep in mind what blm. Furthermore, take a look on basic concepts to help you begin on the right way: http://www.codeproject.com/Articles/22769/Introduction-to-Object-Oriented-Programming-Concep

A: Well, your question seems to be a typical Java (or maybe more: object-oriented programming) question. Please, feel free to read this really good article Java - Object & Classes.
I also recommend you read at least parts of this classic programming book:
Thinking in Java
Like @blm said, import is just a shortcut to existing object, where new means that you' ve created a new instance of it and 'new Human()' called 'paul' can do what every 'Human()' does.
Remember, that in Android you can't create instance of some main classes like Activity. Too learn more about it visit:
Create instance of new class in Android
Creating an instance using the class name and calling constructor


text:
Q: Determine if 3 parametric curves have same plot I have to determine if those three parametric curves have the same plot:
$\gamma_1(t) = (\cos(t), \sin (t))$ for $t \in \mathbb{R}$
$\gamma_2(t) = (\cos(t), \sin (t))$ for $t \in [0,2\pi]$
$\gamma_3(t) = (\frac{1-t^2}{1+t^2}, \frac{2t}{1+t^2})$ for $t \in \mathbb{R}$
I don't have any idea on how to resolve this, checked several times on my lessons but I don't get how to calculate parametric plot. Any help (not answer of course, I want to understand this question :)) please?

A: Hints:

*

*What is different about $\gamma_1$ and $\gamma_2$?  Does this difference change how the plot looks?  Why or why not?  (Bonus hint:  Don't let your head spin around in circles.)

*The curve $\gamma_3$ is more different, but the main question is this:  Do the reals map to the same locus of points as the other two functions?

A: It is clear that both $\gamma_1$ and $\gamma_2$ are unit circles centered in the origin. The difference is that $\gamma_1$ just goes around once, while $\gamma_3$ go on and on. And you can check that the trace of $\gamma_3$ is contained in the unit circle by checking that the functions $x(t) = (1-t^2)/(1+t^2)$ and $y(t) = 2t/(1+t^2)$ satisfy the relation $$x(t)^2+y(t)^2 = 1.$$
(familiar?)

A: All three plots are the same. The first two are simply the parametrization of the unit circle by trigonometric functions with period $2\pi$. The last one is a rational parametrization of the unit circle.


text:
Q: Colorear el texto de una celda en DataGridView C# ¿Cómo puedo cambiar color del texto dentro de una celda de un DataGridView?
Les comento actualmente creo una DataTable con el cual lleno el DataGridView. Pero al momento de la creación del DataTable realizo un serie de validaciones para saber si ese dato sera cambiado de color para lo cual tomo la posición y la almaceno en otro DataTable1.
El primer DataTable lo asigno en el DataSource del DataGridView, Para después cambiar el color las celdas con el otro Databla1 con el siguiente código.
private void DataGridView1_DataBindingComplete(object sender, DataGridViewBindingCompleteEventArgs e){
        if (Indicador.AsEnumerable().Any()){
            foreach (DataRow celda in Indicador.Rows){ /// Recorre las posiciones marcadas para pode cambiar el color de la celda

                this.dataGridView1.Rows[Convert.ToInt32(celda["Posicion"].ToString())].Cells[celda["Columna"].ToString()].Style.ForeColor = Color.Red;
            }

        }
    }

El detalle con este código es que cuando utilizo el ordenamiento de las columnas se mantiene el color en la celda y no se cambia junto con la fila.

Asi es como funciona, el problema que cuando preciono el ordenamiento en el header de la celda, pasa lo siguiente.

A: puedes probar con este codigo:
dataGridView1.Rows[0].Cells[1].Style.BackColor = Color.Red;

Obviamente en el 0 de rows indicas tu fila y en el 1 de Cells indicas tu celda.
Edit: Disculpa, no habia visto lo de abajo. Deberias ponerle a cada fila una forma de identificarlos(un ID por ejemplo) luego, en el evento reordenar del datagrid, volver a pintar(vas a tener que buscar cada ID en las filas y pintar la celda de esa fila)


text:
Q: How to wait for two actions in NGXS I am trying to execute some code after two actions completed in Angular using NGXS. The code would look something like this:
this._subscription.add(
      this._actions$
        .pipe(
          ofActionCompleted(Actions.action1),
          map(({ action1 }) => action1 as Actions.action1),
          ofActionCompleted(Actions.action2),
          map(({ action2 }) => action2 as Actions.action2)
        )
        .subscribe({
          next: ({ payload1, payload2 }) => {
              // execute code using payload1
              // execute code using payload2
          }
        })
    );

What would be the proper way to do this?

A: I would use zip to group both the actions:
zip(
  this.actions$.pipe(ofActionCompleted(Add)),
  this.actions$.pipe(ofActionCompleted(Add2))
).subscribe(([action1, action2]) => {
  console.log(action1);
  console.log(action2);
});

The idea being that you want both of the actions, not just either/or, at the same time.
Example: https://stackblitz.com/edit/ngxs-multi-actions?file=src/app/app.component.ts