text:
Q: Netlogo - Behavior Space I want to run experiments using behavior space. However, the number of experiments needed is depending on the length of a list which is dynamic subject to the external data loaded. Hence , I want to do something like below which is not supported:

what is the correct way to do so? thanks

A: You note that you do this with a .bat or .sha file. If that's the case, here's a .bat solution. However, I'm not sure what your data looks like- in this example I just used the number of entries in a csv file to determine the number of runs needed.
So, I have a data file called 'example_data.csv' that looks like this:
1
100
1000
10000

I have an .nlogo file with an Input widget that defines a global variable called n_runs. I pulled out the xml for an BehaviorSpace experiment and saved it in a file called "experiment_base.xml"- it looks like:
<experiments>
  <experiment name="experiment" repetitions="1" sequentialRunOrder="false" runMetricsEveryStep="false">
    <setup>setup</setup>
    <go>tick</go>
    <timeLimit steps="5"/>
    <metric>count turtles</metric>
    <steppedValueSet variable="n_runs" first="1" step="1" last="1"/>
  </experiment>
</experiments>

I have a .bat file that:

*

*counts the number of entries in my 'example_data.csv"

*reads in the 'experiment_base.xml' file and replaces the last="1" with the number read above, then writes this as a new experiment called 'mod_experiments.xml'

*runs the experiment using the newly generated experiments file

This entire bat file looks like:
@echo off
cls
setlocal EnableDelayedExpansion
set "cmd=findstr /R /N "^^" example_data.csv | find /C ":""

for /f %%a in ('!cmd!') do set number=%%a

powershell -Command "(gc experiment_base.xml) -replace '<steppedValueSet variable=\"n_runs\" first=\"1\" step=\"1\" last=\"1\"/>', '<steppedValueSet variable=\"n_runs\" first=\"1\" step=\"1\" last=\"%number%\"/>' | Set-Content mod_experiments.xml

echo "Running experiment..."

netlogo-headless.bat ^
--model dynamic_behaviorspace.nlogo ^
--setup-file mod_experiments.xml ^
--table table-output.csv

This outputs results for 4 experiments, since I had 4 values in my data file. If I modify the number of entries in the csv and rerun the .bat file, I get results for a corresponding number of runs.


text:
Q: Text wrap not working on Label inside wrappers - CSS I have some scrolling elements which are set up with some CSS. It all works fine but in the following code, I need lblStallMessage1 to have a max width of 200px so that text over that width will wrap around to the next line. I have tried adding..
word-break: break-word; max-width:200px;

to the
 which surrounds the Label control. I've also tried it inside the Label Control itself
But nothing is changing.

<asp:HyperLink ID="hypStall1" runat="server" ><asp:Image ID="imgStall1" width="260px" ImageUrl="~/files/images/car1.gif" runat="server" /></asp:HyperLink><asp:HyperLink ID="hypStall1Avatar" runat="server" ><asp:Image ID="imgStall1Avatar" style="position:relative; float:left; margin-top:-70px; margin-right:-70px;" width="100px" runat="server" /></asp:HyperLink>
<asp:Label ID="lblName1" runat="server" Text="" ></asp:Label>

<asp:Label ID="lblStallMessage1" runat="server" Text="" ></asp:Label>

Here's the CSS..
.wrapper {
    width: 100%;
    margin: auto;
    border: 1px solid #333;
    background-image:url(images/field.jpg);
    background-repeat:no-repeat;
 }
.horizontal-scroll {
     overflow: hidden;
     overflow-x: scroll;
     overflow-y: hidden;
     white-space: nowrap;
     padding: 0px 0;
     height:380px;
 }
.item {
     border: 0px solid #333;
     display: inline-block;
     width: 260px;
     text-align: center;
     padding: 20px 0px;
     font-size: 20px;
     margin-left: 50px;
     margin-bottom: 60px;
 }

redpajama_set_name: RedPajamaStackExchange


text:
Q: Get reference to the document library sharepoint 2013 I want to get reference to document library in code using SP 2013 by url, I am trying the SPWeb.GetList(url); but it works for lists only.
any help?

A: Try:
var list = web.Lists["Documents"];
SPDocumentLibrary doclib =   (SPDocumentLibrary)list;


text:
Q: SQL error converting data type datetime to smalldatetime? In my SQL stored procedure:
@StartDate as smalldatetime,
@EndDate as smalldatetime

In my C# code:
StartDate = new DateTime(1901,01,01,00,00,00);
EndDate = new DateTime(2200,01,01,00,00,00);

var StartDate2 = StartDate.ToString("dd/MM/yyyy HH:mm:ss");
StartDate2 = DateTime.ParseExact(StartDate2, "dd/MM/yyyy HH:mm:ss", CultureInfo.InvariantCulture).ToString("dd/MM/yyyy HH:mm:ss");
StartDate = Convert.ToDateTime(StartDate2);

var EndDate2 = EndDate.ToString("dd/MM/yyyy HH:mm:ss");
EndDate2 = DateTime.ParseExact(EndDate2, "dd/MM/yyyy HH:mm:ss", CultureInfo.InvariantCulture).ToString("dd/MM/yyyy HH:mm:ss");
EndDate = Convert.ToDateTime(EndDate2);

The column is as a smalldatetime type in the db. I'm going round in the circles with this! whats the correct way to parse my Dates to the correct format for querying in the db?
UPDATE:
Changed code to this and worked fine.
SqlParameter parameter = daHoliday.SelectCommand.Parameters.Add("@StartDate", System.Data.SqlDbType.SmallDateTime);
SqlParameter parameter2 = daHoliday.SelectCommand.Parameters.Add("@EndDate", System.Data.SqlDbType.SmallDateTime);
parameter.Value = StartDate;
parameter2.Value = EndDate;

A: Don't convert them to string, just pass them as DateTime type object through Command Parameters.
DateTime should never be converted to string to match format of data in database table. If the datatype in table is DateTime then its always better to pass the .Net framework DateTime object as parameter to command.


text:
Q: SWF file stops after 2nd loop I have a swf file which I created using Adobe Flash professional CS5.5, it's a basic animation of some birds with an audio, it is meant to reply every 5 seconds, but for some reason after it starts to play the second loop it stops mid way and restarts the video from the beginning. Can anyone help me fix this?
This is my actionscript:
stop();
setInterval(wait, 10000);
function wait(){
    gotoAndPlay(1);
}

This is my javascipt to embed the movie on an html page:
<script type="text/javascript" src="/js/swfobject.js"></script>
<script type="text/javascript">
    var flashvars = {};
    var params = {};
    params.wmode = "transparent";
    var attributes = {};
    swfobject.embedSWF("/js/birdmovie.swf", "myAlternative", "290", "163", "9.0.0", "/js/expressInstall.swf", flashvars, params, attributes);
</script>

A: Don't use setInterval because it's going to repeat indefinitely, especially if you keep creating interval at the end of your loop. Use setTimeout instead:
stop();
setTimeout(wait, 5000);
function wait(){
    gotoAndPlay(1);
}

A: so it gets to the end, stops, waits 10 seconds and then goes back to the beginning, but while it's playing, it's still counting another 10 seconds, in which it will loop.
So basically use
setTimeout(wait, 10000);

rather than
setInterval(wait, 10000);

A: I would recommend to name your setInterval and make sure you clear it first before starting it, otherwise you might get some unwanted confusing loops there.
stop();
clearInterval(my_interval);
my_interval = setInterval(wait, 10000);
function wait(){
    gotoAndPlay(1);
}

That way it will always clear any previous interval when it goes to first frame again, avoiding multiple intervals.


text:
Q: Setting boundary within MYSQ Query LIKE I need to search products that are B196 not B196Y.   Products are saved within Database in following format

B196 - Hair Band - Pink

SELECT * FROM
sn_unit
where
product LIKE  'B196%Hair Band%Pink';

A: You could just add space:
SELECT *
FROM sn_unit
where product LIKE 'B196 %Hair Band%Pink';

A: LIKE can be used to filter out results as well; something like this would be more precise.
SELECT *
FROM sn_unit
WHERE product LIKE 'B196%Hair Band%Pink'
  AND product NOT LIKE 'B196Y%'
;

A: As you are looking your product store with string B196 so, you can search for that string LIKE %B196%. That will find out B196 and you are not looking for B196Y that need to exclude from your query. Thats why exlude it using NOT LIKE %B196y%. This query using AND operator that will return true when string contain only B196.
   SELECT *
   FROM sn_unit
   WHERE product LIKE '%B196%'
   AND product NOT LIKE '%B196Y%' ;


text:
Q: Retrieve NSAttributedString from CTFramesetterRef? Is there a way that I could retrieve the NSAttributedString from my CTFramesetter? When I keep the Framesetter [and the NSMutableAttributedString that it uses via (__bridge CFAttributedStringRef)] in memory, I see a second CFString with about the same size in instruments. When I release the CTFramesetter property, there's only the original String left in memory. Because the String can have a size up to 1.5MiB, it would be great if I could just release the original one and use the "embedded" one to do further drawing.
Many thanks

A: If you don't need the attributed string to remain mutable, make an immutable copy before you create the framesetter.  Release the mutable original and use the immutable copy to create the framesetter.


text:
Q: How can i add a second time zone?
Possible Duplicate:
How can I get a world clock indicator?

In 11.04 i had a second time zone in the Clock/Date Dropdown. In 11.10 there seems to be no obvious way to do this, is there one?

A: In the Time and Date drop-down, click "Time and Date Settings".
Click on the "Clock" tab.
Enable the check-box "Time in Other Locations".
Click "Choose Locations". Then, add as many cities and regions as you want :)
The times for those regions will be shown in the dropdown.


text:
Q: How to authenticate devices across organisation boundaries without a third party CA I'm currently working on a protocol which passes automated instructions between separate organisations.  I'm looking for a way to delegate authentication of devices to which ever organisation a device belongs to.  This doesn't affect authorisation models, only authentication.
So to put this in terms of DNS domains:

*

*organisation foomy.tld should be able to authenticate (eg: sign the certificate for?) new_deive.foomy.tld.

*organisation acme.tld could choose to trust foomy.tld:

*

*It should then be able to trust new_device.foomy.tld is what it says it is on the authority of foomy.tld

*BUT organisation acme.tld should NEVER trust foomy.tld to authenticate any device outside the domain of foomy.tld.

Considering using x509 and SSL
In the case of x509 CA certificates, the CA role is usually performed by a third party CA.  But that isn't appropriate for this purpose:

*

*The creation / destruction of device IDs (services) is too rapid to consider a traditional CA (too expensive, too slow).

*This mechanism needs to authenticate clients and servers.  Devices / services do not always have public IP addresses so CA solutions such as LetsEncrypt aren't an option.

*Creating a dedicated CA for this single purpose is not cost effective and likely to damage adoption.

So this leads to the idea of an organisation acting as their own CA for this purpose.  But as it turns out, x509 really doesn't support this well, because once you accept a CA as being trustworthy you cannot limit the scope of that trust enough.  IE: You cannot trust it to only sign certificates for it's own domain.
Considering re-purposing single sign on mechanisms
The single sign-on mechanisms I've looked at appear to be built around the concept of authenticating users.  Background automated services don't appear to be well supported.
Maybe I missed something here.
Question - Keeping it as narrow as possible.
Is there another approach allowing this type of cross organisation authentication which I can use for my problem ?

A: X509 certificates may contain namecontraints (see https://knowledge.digicert.com/solution/SO4583.html for a brief summary of the fields).  You might be able to use these.
Openssl documents these nameconstraints as well https://www.openssl.org/docs/man1.0.2/man5/x509v3_config.html, so it can probably handle them in certificates.
I found this blog by Vadims Podāns: https://www.sysadmins.lv/blog-en/x509-name-constraints-certificate-extension-all-you-should-know.aspx
It claims that both Windows cryptoAPI and OpenSSL support name constrains.  It gives a sample of how to configure Microsft certreq.exe.  And it describes some scenarios where this may be useful.
On security.stackexchange there is a question about whether MacOS supports them: https://security.stackexchange.com/questions/95600/are-x-509-nameconstraints-on-certificates-supported-on-os-x
And MacOS does not support name constraints.
Thomas Pornin on security.stackexchange describes why name constraints do not work in SSL.  Your situation is not SSL tough, you might be able to enforce checking the name constraint not not falling back to the common name.
I haven't tried nameconstraints though.


text:
Q: xslt completely remove duplicates from string I have a variable containing non-numerical values, and I need to completely remove duplicate entries from this string using XSLT:
$string = a,b,c,c,d,d,e,f,g
needs to become: $newstring = a,b,e,f,g
An alternative option would be to compare the two variables and ignore/remove the overlapping entries.
$stringA = a,c
$stringB = a,b,c,d,e,f
needs to become:
$newstring = b,d,e,f
Concatenating the variables is straightforward but I need the opposite of that!
Please help,

A: XSLT is designed to process XML, not strings. XSLT 1.0 in particular is a  poor tool for manipulating text.
IMHO, the best way to proceed here is to convert the problem to XML first. If you're using libxslt (as xsltproc does), this is quite easy to do using an extension function:
XSLT 1.0
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns:str="http://exslt.org/strings"
extension-element-prefixes="str">
<xsl:output method="xml" version="1.0" encoding="UTF-8" indent="yes"/>

<xsl:param name="stringA">a,c,g</xsl:param>
<xsl:param name="stringB">a,b,c,d,e,f</xsl:param>

<xsl:variable name="setA" select="str:tokenize($stringA, ',')" />
<xsl:variable name="setB" select="str:tokenize($stringB, ',')" />

<xsl:template match="/">
    <test>
        <xsl:for-each select="$setA[not(.=$setB)] | $setB[not(.=$setA)]">
            <xsl:value-of select="."/>
            <xsl:if test="position()!=last()">,</xsl:if>
        </xsl:for-each>
    </test>
</xsl:template>

</xsl:stylesheet>

Result:
<?xml version="1.0" encoding="UTF-8"?>
<test>g,b,d,e,f</test>


text:
Q: onLocationChanged pointing to wrong Location(Barents Sea)? build.grade
  compile 'com.android.support:appcompat-v7:25.3.0'
  compile 'com.android.support.constraint:constraint-layout:1.0.1'
  compile 'com.google.android.gms:play-services:10.2.1'

AndroidManifest.xml
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>

<meta-data android:name="com.google.android.geo.API_KEY"
        android:value="@string/str_map_key"/>

<meta-data android:name="com.google.android.gms.version"
        android:value="@integer/google_play_services_version"/>

MainActivity.java
public class MainActivity extends AppCompatActivity
    implements OnMapReadyCallback,
    ActivityCompat.OnRequestPermissionsResultCallback,
    GoogleApiClient.ConnectionCallbacks,
    GoogleApiClient.OnConnectionFailedListener,
    LocationListener {

private GoogleMap mGoogleMap;
private static final int LOCATION_PERMISSION_REQUEST_CODE = 1;
private boolean mPermissionDenied = false;

private GoogleApiClient mGoogleApiClient;

private Location mLastLocation;

//TextView
TextView longitudeTextView;
TextView lattitudeTextView;

private LocationRequest mLocationRequest;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);

    mGoogleApiClient = new GoogleApiClient.Builder(this)
            .addConnectionCallbacks(this)
            .addOnConnectionFailedListener(this)
            .addApi(LocationServices.API)
            .build();

    MapFragment mapFragment = (MapFragment) getFragmentManager().findFragmentById(R.id.map_view);
    mapFragment.getMapAsync(this);

    longitudeTextView = (TextView) findViewById(R.id.main_longitude_text);
    lattitudeTextView = (TextView) findViewById(R.id.main_lattitude_text);
}

@Override
protected void onStart() {
    //when activity is create GoogleMapApiClient is build there under onCreate
    //than on activity start we gonna connect it to Google
    mGoogleApiClient.connect();
    super.onStart();
}

@Override
protected void onStop() {
    //when activity is stopped disconnect GoogleApiClient
    super.onStop();
    mGoogleApiClient.disconnect();
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.menu_main, menu);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
    int id = item.getItemId();

    //noinspection SimplifiableIfStatement
    if (id == R.id.action_settings) {
        return true;
    }

    return super.onOptionsItemSelected(item);
}

@Override
public void onMapReady(GoogleMap googleMap) {
    mGoogleMap = googleMap;

    enableMyLocation();
}

private void enableMyLocation() {
    if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION)
            != PackageManager.PERMISSION_GRANTED) {
        //Permission to access the location is missing
        ActivityCompat.requestPermissions(this, new String[]{android.Manifest.permission.ACCESS_FINE_LOCATION},
                LOCATION_PERMISSION_REQUEST_CODE);
    } else {
        //Access to location has been granted to app
        mGoogleMap.setMyLocationEnabled(true);
    }
}

@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions,
                                       @NonNull int[] grantResults) {
    if (requestCode != LOCATION_PERMISSION_REQUEST_CODE) {
        return;
    }

    if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION)
            != PackageManager.PERMISSION_GRANTED) {
        // Enable the my location layer if the permission has been granted.
        enableMyLocation();
    } else {
        // Display the missing permission error dialog when the fragments resume.
        mPermissionDenied = true;
    }

}

@Override
public void onConnected(@Nullable Bundle bundle) {
    mLocationRequest = LocationRequest.create()
            .setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY)
            .setInterval(100);

    if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
        Toast.makeText(this, "Location permission missing !!", Toast.LENGTH_LONG).show();
        return;
    }
    LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);
}

@Override
public void onConnectionSuspended(int i) {

}

@Override
public void onConnectionFailed(@NonNull ConnectionResult connectionResult) {

}

@Override
public void onLocationChanged(Location location) {
    //displaying coordinates on screen for test purpose only
    longitudeTextView.setText(String.valueOf(location.getLongitude()));
    lattitudeTextView.setText(String.valueOf(location.getLatitude()));

    LatLng latLng = new LatLng(location.getLongitude(), location.getLatitude());
    CameraUpdate cameraUpdate = CameraUpdateFactory.newLatLngZoom(latLng, 15);
    mGoogleMap.moveCamera(cameraUpdate);
}
}

Very Basic app to move camera to new coordinates.
onLocationChanged is called whenever location is changed . It should move camera to new coordinates but instead of this it starts pointing to somewhere in Barents sea. I have gone throw whole documentation more than 5 times still didn't get it.
On app start
https://s10.postimg.org/xywc61w2x/Screenshot_20170325-123853.png
Where i am actually
https://s10.postimg.org/d4ol1yr3d/Screenshot_20170325-132620.png
Tested on both Emulator and Real Device.

A: Those coordinates 75.8467264/30.862686 and 75.8467229/30.862678 are at the Barents sea.
Change
LatLng latLng = new LatLng(location.getLongitude(), location.getLatitude());

to
LatLng latLng = new LatLng(location.getLatitude, location.getLongitude()());

in onLocationChanged() to view northern India on the map.


text:
Q: How to evaluate XSLT expression and skip node by condition? How can I add evaluation on a xslt property, and skip a for-each node by condition of that evaluation?
<some>
    <deep>
        <level availability="10" code="A"/>
    </deep>
</some>

<xsl:template match="some">
    <xsl:for-each select="//deep//level">
        <xsl:value-of select=".//@code, .//@availability" separator=";"/>
    <xsl:for-each>
</xsl:template>

Question: how can I skip if availability < 5?

A: Rather than thinking about "skipping" elements, think about what you want to select, and then put a condition for this in square brackets after the nodes you select
Try this template....
<xsl:template match="some">
    <xsl:for-each select="deep/level[number(@availability) ge 5]">
        <xsl:value-of select="@code, @availability" separator=";"/>
    </xsl:for-each>
</xsl:template>

Note that // will search all descendant nodes, not just the immediate child node, which I am not sure you need here.


text:
Q: What did Noether meant with "inner ground for equality"? Several days ago, I found the following quote by Emmy Noether:

If one proves the equality of two numbers $a$ and $b$ by showing first that $a \leqq b$ and then that $a \geqq b$, it is unfair; one should instead show that they are really equal by disclosing the inner ground for their equality.

It seems this comes from Weyl's Levels of Infinity. I own a copy of the book and puzzled by the meaning of the quote, I tried to read trying to obtain more context:

But I'm still puzzled by what it may mean, I must also admit I know a very limited amount of algebra (supposing such is needed). I know what are groups, fields, rings, isomorphisms, automorphisms. But I can't give meaning to the quote only with that. I am also assuming that the content of the quote is not too vague to be interpreted.


text:
Q: Custom aggregate function in pandas groupby I have a dataframe like following
    Client          Month        Amount
     ABC           201601       -4563
     BHG           201602          321
     HTD           201601       -5234
     BTD            201603         342
     ERT.            201601        234

I want to find how many customer's amount is in negative for every month. It should be percentage of total clients e.g 201601 month 2 clients amount is in negative and one client's amount is in positive so the ratio should be 2/3 (total clients amount in negative)/(total clients for that specific month) like wise.
I am using following code but it does not work.
  df.groupby('Month')['Client'].count()

A: I think you need mean of boolean mask created x<0:
df = df.groupby('Month')['Amount'].apply(lambda x: 100 * (x<0).mean())
print (df)
Month
201601    100.0
201602      0.0
201603      0.0
Name: Amount, dtype: float64

EDIT:
df = df.groupby('Month')['Amount'].apply(lambda x: 100 * (x<0).mean())
print (df)
Month
201601    66.666667
201602     0.000000
201603     0.000000
Name: Amount, dtype: float64

df = df.groupby(['Month', 'Client'])['Amount'].apply(lambda x: 100 * (x<0).mean())
print (df)
Month   Client
201601  ABC       100.0
        HTD       100.0
201602  BHG         0.0
201603  BTD         0.0
Name: Amount, dtype: float64


text:
Q: Kafka "Topic is empty" showing in UI after the producer code compilation successfully I am trying to write and run my own producer code so I have written the code in IntelliJ and compiled successfully with process finished with exit code 0.
But there has no message is showing in the UI, it is showing that the topic is empty, meanwhile if I am trying to produce some message using terminal in docker then the topic is behaving properly.
How can I fix this?

Code:
import org.apache.kafka.clients.producer.Producer;
import org.apache.kafka.clients.producer.ProducerRecord;
import org.apache.kafka.common.serialization.IntegerDeserializer;
import org.apache.kafka.common.serialization.StringSerializer;

import java.util.Properties;

public class KafkaProducer {
    public static void main(String[] args) {
        Properties properties = new Properties();

        // kafka bootstrap server
        properties.setProperty("bootstrap.servers", "127.0.0.1:9092");
        properties.setProperty("key.serializer", StringSerializer.class.getName());
        properties.setProperty("value.serializer", StringSerializer.class.getName());
        // producer acks
        properties.setProperty("acks", "1");
        properties.setProperty("retries", "3");
        properties.setProperty("linger.ms", "1");

        Producer<String, String> producer = new org.apache.kafka.clients.producer.KafkaProducer<String, String>(properties);

        for (int key=0; key < 10; key++){
            ProducerRecord<String, String> producerRecord =
        new ProducerRecord<String, String>("second_topic", Integer.toString(key), "message that has key: " + Integer.toString(key));
            producer.send(producerRecord);
        }
        producer.close();
    }
}

pom.xml:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>org.dataoverflow.kafka</groupId>
    <artifactId>kafka-dataoverflow</artifactId>
    <version>1.0-SNAPSHOT</version>

    <dependencies>
        <dependency>
            <groupId>org.apache.kafka</groupId>
            <artifactId>kafka-clients</artifactId>
            <version>1.1.0</version>
        </dependency>
    </dependencies>

</project>

I have tried by adding Asynchronous Call Back Function in my code which is failing to push the message into Broker. What should I do?
package com.dataoverflow.kafka;

import org.apache.kafka.clients.producer.Producer;
import org.apache.kafka.clients.producer.ProducerRecord;
import org.apache.kafka.common.serialization.IntegerDeserializer;
import org.apache.kafka.common.serialization.StringSerializer;
import org.apache.kafka.clients.producer.*;

import java.util.Properties;

public class KafkaProducer {
    public static void main(String[] args) {
        Properties properties = new Properties();

        // kafka bootstrap server
        properties.setProperty("bootstrap.servers", "127.0.0.1:9092");
        properties.setProperty("broker.list", "127.0.0.1:9092");
        properties.setProperty("key.serializer", StringSerializer.class.getName());
        properties.setProperty("value.serializer", StringSerializer.class.getName());
        // producer acks
        properties.setProperty("acks", "all");
        properties.setProperty("timeout.ms", "20000");

        properties.setProperty("retries", "3");
        properties.setProperty("linger.ms", "10");
        //Specify buffer size in config
        properties.put("batch.size", 16384);
        properties.put("buffer.memory", 33554432);

        Producer<String, String> producer = new org.apache.kafka.clients.producer.KafkaProducer<String, String>(properties);

        for (int key=0; key < 10; key++){
            ProducerRecord<String, String> record =
        new ProducerRecord<String, String>("second_topic", Integer.toString(key), "message that has key: " + Integer.toString(key));
            producer.send(record, new MyProducerCallback());
            System.out.println("AsynchronousProducer call completed");
        }
        producer.close();
    }
}

class MyProducerCallback implements Callback{

    public  void onCompletion(RecordMetadata recordMetadata, Exception e) {
        if (e != null) {
            System.out.println("AsynchronousProducer failed with an exception");
            System.out.println(e.getStackTrace());
        }
        else
            System.out.println("AsynchronousProducer call Success:");
    }
}

Output:
SLF4J: Failed to load class "org.slf4j.impl.StaticLoggerBinder".
SLF4J: Defaulting to no-operation (NOP) logger implementation
SLF4J: See http://www.slf4j.org/codes.html#StaticLoggerBinder for further details.
AsynchronousProducer failed with an exception
AsynchronousProducer call completed
AsynchronousProducer failed with an exception
AsynchronousProducer call completed
AsynchronousProducer failed with an exception
AsynchronousProducer call completed
AsynchronousProducer failed with an exception
AsynchronousProducer call completed
AsynchronousProducer failed with an exception
AsynchronousProducer call completed

A: I have successfully fixed it. Here is the thread.


text:
Q: Generate the output on a particular cell ID in CSV What I am trying to achieve here is to extract the values from  tags HTML to a CSV file which I am succesful. What I want to is to get some control over the output being generated.
HTML values are:
<input type=hidden id=batterystatus value="Charging" >
<input type=hidden id=batterylevel value="80 %" >
<input type=hidden id=signalStrength value="4" >
<input type=hidden id=ulCurrentDataRate value="5 Kbps" >
<input type=hidden id=dlCurrentDataRate value="136 Kbps" >
<input type=hidden id=ConnectionTime value="00:15:33:10" >
<input type=hidden id=noOfClient value="2" >

Now, I wrote the script using perl.
#!usr/bin/perl

use strict;
use warnings;
use HTML::TokeParser::Simple;

my $url = 'http://192.168.225.1';
my $parser = HTML::TokeParser::Simple->new(url => $url);
my %tags;
while (my $tag = $parser->get_tag('input')) {
           my $id=$tag->get_attr('id'); # get id attribute value
           my $value = $tag->get_attr('value'); # get value attribute value
           $tags{$id}=$value;
 }
my @tags;
my @values;
for (keys %tags){
   push (@tags, $_);
   push (@values, $tags{$_});
}

open(my $OUTFILE, ">", "test.csv")
    or die "Unable to open testfile for writing : $!";
print $OUTFILE join(",",@tags)."\r\n";
print $OUTFILE join(",",@values)."\r\n";

The data that is generated in CSV file is:

and then again when I re-ran this code I found something like this:

Questions:

*

*How do I fix the cell id, such that I always get IMSI in Cell A1
and also the other output in particular cell?

*How to I rename each cell header? For example batterylevel to be renamed as Battery Level or connectedStatus to be renamed as Connected Status.

A: You are using a hash to store the data and are not sorting it when accessing the values. A hash in Perl is not sorted. The order of the keys is random and (at least in recent Perls) you cannot rely on the order. You need to sort the keys yourself. That is a feature.
The easiest way to do that is to just hardcode the order, since it looks like you are always expecting the same input. For renaming the columns, just use a hash as a lookup table.
I used Text::CSV because it is well-tested and pretty good at handling even arcane border cases.
use strict;
use warnings;
use HTML::TokeParser::Simple;
use Text::CSV;

my $html = <<HTML;
<input type=hidden id=imsi value="406E+14" >
<input type=hidden id=batterystatus value="Charging" >
<input type=hidden id=batterylevel value="80 %" >
HTML

my $parser = HTML::TokeParser::Simple->new( string => $html );

# mapping for the column headers
my %names = (
    imsi          => 'IMSI',
    batterylevel  => 'Battery Level',
    batterystatus => 'Battery Status',
);

my %tags;
while ( my $tag = $parser->get_tag('input') ) {
    my $id    = $tag->get_attr('id');       # get id attribute value
    my $value = $tag->get_attr('value');    # get value attribute value
    $tags{$id} = $value;
}

# use meaningfull names and sort in the loop
my @headers;
my @values;
foreach my $tag (qw(imsi batterylevel batterystatus)) {
    push @headers, $names{$tag};
    push @values,  $tags{$tag};
}

# create a T::CSV handle with Win line endings
my $csv = Text::CSV->new({
  sep_char => ',',
  eol => "\r\n",
  quote_char => q{},
});

# write out headers and values
$csv->print(\*STDOUT, \@headers);
$csv->print(\*STDOUT, \@values);


text:
Q: How to customize the encoding of a text file in c++? I am working on huffman file compression project. Till now I know it works something like:
file.txt(original) -> file.huf(encoded, compressed) -> file.txt(decoded)

What I have to do is to open the txt file, generate the huffman code, but how can I replace those code in the binary code file of the original file. For example, if file.txt stores abc then its ASCII encoded file will store 01100001 01100010 01100011 and huffman-coded file i.e file.huf should store 10 11 0 and then this file should be decoded using the encoding map generated.
My question is to how can I do this in C++ at the file  implementation level, how can I alter the binary file?

A: I have figured it out, in simple words, make the code for an alphabet and then for another and combine, iterate this till the code is equal to or more than 8 characters containing 1 and 0, then this sequence of 8 digits is encoded to some character and stored in a file.
This way file can be compressed.


text:
Q: Callback function in Swift to return value during JSON task I asked this question which was closed yesterday and I was provided a similar question with how to implement call back. I am still struggling with this and have updated my code to try and use it but I seem to be running into an array of problems. All that I am trying to do is return the value of results as an Array so that I can easily manipulate it later. Is there a better/easier way to do what I am trying to accomplish?
The function takes a parameter of an array from the previous view, and uses some of the values to push to the endpoint. The resulting. JSON is what I am trying to get as an array. Current error is of course results is not defined when called in ViewDidLoad
EDIT:
results looks like:
["BRLBGN": 0.4699, "BGNBRL": 2.1691]

In ViewDidLoad:
calculateRate(value: codesToConvert, completionHandler: results)

In the function:
func calculateRate(value: [String], completionHandler: (_ results: [String: Any])->()){

    let url = URL(string: "domain.com")!
    var request = URLRequest(url: url)
    request.httpMethod = "POST"
    let postString = "pairs=\(value[0] + value[2])&pairs=\(value[2]+value[0])"
    print(postString)
    request.httpBody = postString.data(using: String.Encoding.utf8)

    let task = URLSession.shared.dataTask(with: request) {(data, response, error) in
        do  {
            let jsonResult = try  JSONSerialization.jsonObject(with: data!)
            let results = jsonResult as! [String: Any]
            completionHandler(results)

        } catch {
            print(error)
        }
    }
    task.resume()
}

A: Assuming that you're getting proper result in calculateRate method, call the method calculateRate(value:completionHandler:) like so,
var arrayResults = [String:Any]()

calculateRate(value: ["a", "b", "c"]) {(results) in
    arrayResults = results
}

completionHandler is a closure. So, when calling calculateRate, you need to pass a closure there accepts a parameter results of type [String:Any].
Edit:
Also add @escaping with completionHandler in the calculateRate(value:completionHandler:) method's signature.
func calculateRate(value: [String], completionHandler: @escaping (_ results: [String: Any])->()){
    //rest of the code
}


text:
Q: Angular formly: is there a way to set default options for all inputs I'm having a formly form with many mat-inputs (yes, I'm using Material) inside. I want each of them have appearance=outline of cause I can put it inside templateOptions of each input. But that's not DRY. Is there a way to set default appearance for each mat-input in my app and do not put it in each input description?
UPD. I'm using formly form component in the following way
<formly-form [form]="form" [fields]="fieldsDescription"></formly-form>

form is generated with cycle (looping over fieldsDescription array) and angular form builder. fieldsDescription is downloaded from backend. Right now I put appearance=outline in each input. So fieldsDescription is an array of objects like the following
{
    "key": "field_key",
    "type": "input",
    "templateOptions": {
        "label": "A label",
        "appearance": "outline",
        "placeholder": "",
        "required": true
    }
}

A: why not use as provider MAT_FORM_FIELD_DEFAULT_OPTIONS { appearance: 'outline' }? I imagine you want all yours inputs apparence outline. In your module
  providers: [
    { provide: MAT_FORM_FIELD_DEFAULT_OPTIONS, useValue: { appearance: 'outline' } },
  ]

A: why not using inside template <mat-form-field appearance="outline"> ? assuming you use an ngFor there.
le:
  fields: FormlyFieldConfig[] = [
    {
      key: 'Input',
      type: 'input',
      templateOptions: {
        label: 'Input',
        placeholder: 'Placeholder',
        description: 'Description',
        required: true,
        appearance: 'outline',
      },
    },
  ];

for Formly, you can use templateOptions to define appearance outline in your form fields configuration. source here


text:
Q: On 18.04 LTS, how can the TrackPoint driver be changed from libinput back to Synaptics? I want to change the TrackPoint driver from libinput to Synaptics. I am using a ThinkPad X390 and I have tried the latest version of the libinput driver and I have tried to find out why the libinput driver is behaving in a way that makes the TrackPoint unpleasant for me and I now want to change back to Synaptics until libinput is developed further. I have verified that the TrackPoint seems to be running well on 16.04, which features the Synaptics driver.
How might this switch be done from libinput to Synaptics on Ubuntu 18.04 LTS?
I have already run the following:
sudo apt install xserver-xorg-input-synaptics-hwe-18.04 xserver-xorg-input-evdev-hwe-18.04
sudo apt remove xserver-xorg-input-libinput-hwe-18.04

A: sudo apt install xserver-xorg-input-synaptics-hwe-18.04
sudo apt install xserver-xorg-input-evdev-hwe-18.04
sudo apt remove xserver-xorg-input-libinput
sudo apt remove xserver-xorg-input-libinput-hwe-18.04

Whether libinput or Synaptics is in use can be ascertained by getting the device name from the output of xinput --list and then listing the properties of the device using a command like the following:
xinput --list-props "TPPS/2 Elan TrackPoint"


text:
Q: Creating a custom column Trying to create a 2 column section at the beginning of the page as shown in the image below - basically 2 column at the top but then rest as one column. One column will have an image and the other will have promoted links. Any (relatively easy) way of doing this?

A: You can use colspan as below

Promoted Links</h2


text:
Q: Get class name of enum by its value I have some enum
public enum MyEnum
{
    Field1,
    Field2
}

and pass value in function
DoSmth(MyEnum.Field1);

How can i get classname "MyEnum" in that function
void DoSmth(Enum enumArg)
{
    string className = Magic(enumArg); // className = "MyEnum"
}

A: Note that the code you've posted doesn't compile. enum is a reserved word and cannot be used as a variable name. The following will work, however.
void DoSmth(Enum e)
{
    string className = e.GetType().Name; // className = "MyEnum"
}

A: If you just need to check if enum is MуEnum then it's better to check as if (enum is MyEnum)
If you need type name then you need enum.GetType().Name


text:
Q: JavaScript Destructive Map Function I'm trying to make this map function a more destructive version of itself. Meaning the map function modifies the original array instead of a new one.
function map (array, callback) {
  var result = []
  for (var i = 0; i < array.length; i++) {
    result.push(callback(array[i]))
  }
  console.log("Array",array, "Result",result)
  return result
}

The console.log returns:
   Array [ 5, 2, 1 ] Result [ 6, 3, 2 ]

The array should be [5,2,1] and it's currently [6,3,2]

A: Your var result = [] creates a new array. If you want to modify the old array, you should assign to it (assign to properties of the array parameter):

function map (array, callback) {
  array.forEach((item, i) => {
    array[i] = callback(item);
  });
  return array;
}

const arr = [1, 2];
map(arr, e => e + 1);
console.log(arr);

Note that calling this function map might be a bit misleading, because Array.prototype.map does something similar, but creates an entirely separate array, like your original code is doing. You might want to call this function something other than map, perhaps changeEvery or something like that.

A: You can follow this code...I hope your problem solved
function map(array, callback) {
    var result=[]
    for (var i = 0; i < array.length; i++) {
       result.push(callback(array[i]))
    }
    console.log(result)
}
map([5, 2, 1], (value) => {
   return value
})


text:
Q: R:: Substring a character till a numeric value is found I want to substring the below words in R till it finds a numeric character.
BARCLAYS BANK PLC 6.860

The answer should be
BARCLAYS BANK PLC

I tired to used substr but I am not sure how to remove the numeric variables.

A: We can use sub to match one or more space (\\s+) followed by numbers till the end of the string ($) (this is based on the example provided), and replace by ''.
sub("\\s+[0-9.]+$", '', str1)
#[1] "BARCLAYS BANK PLC" "US TREASURY"       "NEW BRUNSWICK"

Or using the OP's description (to keep only characters till a numeric character is found), we match all non-numeric characters from the beginning of the string (^), keep it in a capture group and replace with the backreference (\\1).
sub("^([^0-9.]+)\\s+.*", '\\1', str1)
#[1] "BARCLAYS BANK PLC" "US TREASURY"       "NEW BRUNSWICK"

data
str1 <- c("BARCLAYS BANK PLC 6.860", "US TREASURY 2.500",
      "NEW BRUNSWICK 4.800")


text:
Q: How to slice all elements in a list to a certain length Assuming I have a list with multiple strings in there.
x = ["red", "green", "black", "orange", "purple"]

I want to slice every element in the list to a certain length, eg. 4 characters. Then the list should look like this:
x = ["red", "gree", "blac", "oran", "purp"]

I tried it with x[0:4], but doing so only sliced the list to 4 elements like
x = ["red", "gree", "blac", "oran"]

How can I do this?

A: With x[0:4] you are accessing the list's items, not the list items' items. This will work:
x = ["red", "green", "black", "orange", "purple"]
for index, item in enumerate(x):
    x[index] = x[index][0:4]


text:
Q: C program to filter elements of type anyURI from string XML using XSLT I have a XML string, I want to apply XSLT string on this XML to filter elements of type anyURI.
I am interested to use libxslt. But It transforms the xml present in file. I want to transform xml string.
How to write a C program to transform this xml string?

A: In terms of XSLT, libxslt is an XSLT 1.0 processor so it doesn't support W3C schema types like xs:anyURI in XSLT, you would need to use an XSLT 2 or 3 processor. Therefore I am not sure how you expect your XSLT program, whether you have it in a file or in a string, to filter out elements of type xs:anyURI.
In terms of C, I guess, depending on your "string" representation, you need to use http://www.xmlsoft.org/html/libxml-parser.html#xmlReadMemory or xmlReadDoc to get an http://www.xmlsoft.org/html/libxml-tree.html#xmlDocPtr for both the XML "string" input and the XSLT "string" input and then the libxslt APIs allow you to use http://xmlsoft.org/XSLT/html/libxslt-xsltInternals.html#xsltParseStylesheetDoc to get an xsltStylesheetPtr and then to run xsltApplyStylesheet.


text:
Q: Nightwatch assert present an anchor tag with class names I'm trying to write a Nightwatch test targeting the following anchor tag:

Operational

In Chrome's dev tools console, I can reference this anchor via
$('a.ui.label.transition.visible') where I get: …
In Nightwatch, I cannot reference this anchor.
  'a simple test': function (browser) {
    const devServer = browser.globals.devServerURL
    browser
      .url(devServer+endpoint)
      .waitForElementVisible('.qpi-category-selector.ui.fluid.multiple.selection.normal.dropdown', 5000)
      .assert.elementPresent('a.ui.label.transition.visible')
      .end()
  }

Result:
FAILED: 1 assertions failed and  1 passed (29.052s)
   Testing if element  is present. - expected "present" but got: "not present"
       at <anonymous>
       at process._tickCallback (internal/process/next_tick.js:188:7)
_________________________________________________

TEST FAILURE:  1 assertions failed, 1 passed. 31.138s

 ✖ study/test
 – QPI filter test (29.052s)
   Testing if element  is present. - expected "present" but got: "not present"

Using Nightwatch 1.0.4
Is there something obvious I'm missing?

A: Answering my own question because this is actually an issue with http vs https.
The test url was set to http://localhost... but our dev environment is set up to use https.
Without https our internal server was unable to communicate:
No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost.qdss.io:8080' is therefore not allowed access
Hence, some of the anchor tags we expected to show up did not. I changed the url to https and used
chromeOptions: {
  args: ['disable-web-security', 'ignore-certificate-errors']
}

tldr: if Nightwatch is not picking up on something that should obviously be there, the problem is probably somewhere else.


text:
Q: at command throws 'cannot set egid: Operation not permitted error' I'm trying to execute a command using the following command:
/usr/local/bin/php xxx.php | at now + 10 minutes

However, terminal throws this error:
cannot set egid: Operation not permitted error

I tried adding the user to /etc/at.allow but that doesn't help. I also removed /etc/at.deny, but that also didn't help. Any ideas what is up? How can I give permission to the user to utilize the at command?

A: The permissions on /usr/bin/at are incorrect, it needs to be setuid to root:
sudo chmod u+s /usr/bin/at


text:
Q: Python: Count word frequencies and put them into multiple dictionaries I'm new to python, now I have a txt file like this:
Doc 1
aaa bbb ccc ddd ...

Doc 2
eee fff ggg hhh ...

Doc 3
aaa ggg iii kkk ...

...

Doc 11
eee ttt uuu zzz ...

Basically what I want to do is to count term frequency for each document and put them into 11 different dictionaries (like "For Doc1, {'aaa':10, 'bbb':5 ...}", build Term - Document matrix at the end. My current code is like following:
# split te text file into 11 documents(paragraphs)
f = open('filename.txt', 'r')
data = f.read()
docs = data.split("\n\n")

# creat 11 tf dictionaries
dictstr = 'tf'
dictlist = [dictstr + str(i) for i in range(10)]

for i in range(10):
    for line in docs[i]:
        tokens = line.split()
        for term in tokens:
            term = term.lower()
            term = term.replace(',', '')
            term = term.replace('"', '')
            term = term.replace('.', '')
            term = term.replace('/', '')
            term = term.replace('(', '')
            term = term.replace(')', '')

            if not term in dict['tfi']:
                dict['tfi'][term] = 1

            else:
                dict['tfi'][term] += 1

There are some problems in the last "if - else" step, I'm stuck here. Can anyone tell me how to deal with it? (Don't want to use other packages like "panda") Thank you!
The txt resource's here

A: This code reads in the file you provided, removes the unwanted characters in one pass (VS creating a new string for each use of .replace) and saves the word counts in a dict called result. The keys are the doc nums ('XXX9' -> 'tf9') and the values are collections.Counter objects with the word counts.
>>> import re
... from collections import Counter
...
... with open('filename.txt', 'r') as f:
...     data = f.read().lower()
...
... clean_data = re.sub(r'[,"./()]', '', data)
...
... result = {}
... for line in clean_data.splitlines():
...     if not line:
...         continue  # skip blank lines
...     elif line.startswith('xxx'):
...         doc_num = 'tf{}'.format(line[3:])
...     else:
...         result[doc_num] = Counter(line.split())
...
>>> list(result.keys())
['tf7', 'tf10', 'tf5', 'tf2', 'tf9', 'tf4', 'tf11', 'tf3', 'tf6', 'tf8', 'tf1']

>>> for k, v in list(result['tf1'].items())[:15]:
...     print("'{}': {}".format(k, v))
...
'class': 1
'then': 1
'emerge': 1
'industry': 1
'common': 1
'ourselves': 2
'models': 1
'short': 1
'mgi': 1
'it': 1
'actionable': 1
'time': 1
'why': 1
'theory': 1
'equip': 2

Let me know if any changes need to be made to help answer your question!


text:
Q: Handle all http errors in the same way All calls to my api are made through a service I created with the "GET, POST, PUT, DELETE, PATCH" methods. If any of these calls fail I would like to show the error in an alert and if the error status is 401 redirect the user to the login. How can I make a generic error handler?
api.service.ts
import { Injectable } from '@angular/core';
import { Http, RequestOptions, RequestOptionsArgs, Response, URLSearchParams } from '@angular/http';
import { Observable } from 'rxjs/Observable';

import lodash from 'lodash';

@Injectable()
export class ApiService {

  url: string = 'https://leetags-api.herokuapp.com';
  options: RequestOptions = new RequestOptions({
    withCredentials: true
  });

  constructor(private http: Http) {}

  get(endpoint: string, params?: any, options: RequestOptionsArgs = {}): Observable<Response> {
    if (params) {
      const urlSearchParams: URLSearchParams = new URLSearchParams();
      lodash.forEach(params, (value: any, key: string): void => urlSearchParams.set(key, value));
      options.search = !options.search ? urlSearchParams : options.search;
    }

    return this.http.get(`${this.url}/${endpoint}`, this.options.merge(options));
  }

  post(endpoint: string, body: any, options?: RequestOptionsArgs): Observable<Response> {
    return this.http.post(`${this.url}/${endpoint}`, body, this.options.merge(options));
  }

  put(endpoint: string, body: any, options?: RequestOptionsArgs): Observable<Response> {
    return this.http.put(`${this.url}/${endpoint}`, body, this.options.merge(options));
  }

  delete(endpoint: string, options?: RequestOptionsArgs): Observable<Response> {
    return this.http.delete(`${this.url}/${endpoint}`, this.options.merge(options));
  }

  patch(endpoint: string, body: any, options?: RequestOptionsArgs): Observable<Response> {
    return this.http.put(`${this.url}/${endpoint}`, body, this.options.merge(options));
  }

}

A: You can also make a catch() method in your service and assign it to the catch handler of your http call. The .catch block is automatically called whenever a api call fails.
Your above http statement should then look like following (for GET):
get() {
        return this._http.get(this.getUserUrl)
                .map((response: Response) => response.json())
                .catch(this.myCatchFunction);
    }

myCatchFunction(error: Response){
 //look here for specific codes present in response error and handle accordingly
}

Hope this helps


text:
Q: Massive versus Massless $\phi^4$ Sunset Diagram - does $\frac{1}{\epsilon^2}$ term vanish for $m=0$? In a real scalar massive $\phi^4$-interacting theory consider the amputated sunset diagram. This is the integral out of Kleinert and Schulte-Frohlinde Critical Properties of $\phi^4$-Theories:

The above two-loop integral is in Euclidean space, and $\mathbf{q}$ is the incoming momentum.
Using dimensional regularization, where $\epsilon = \frac{4-D}{2}$ and $\mu$ is the reference scale, the above integral takes on the following form when regularized:

Now consider that we take $m \to 0^{+}$ and consider the diagram in the massless case. Then the above simplifies to:
$$
- \frac{g^2}{(4\pi)^4} \frac{\mathbf{q}^2}{2\epsilon} + \mathcal{O}(\epsilon^{0})
$$
So we see in the massless case, the $\frac{1}{\epsilon^2}$ term vanishes.
Why does this happen? My understanding is that a $\frac{1}{\epsilon^2}$ signifies a quadratic UV-divergence, while a $\frac{1}{\epsilon}$ signifies a logarithmic UV divergence (maybe this is wrong?).
From a naive power-counting point of view if we look at the original loop integral, we have an integral roughly like $\frac{d^{8}\mathbf{p}}{\mathbf{p}^6}$ for large momenta, which looks like a quadratic divergence - independent of whether $m$ has vanished or not.
Why does the power-counting argument fail when $m=0$? Or is it false that $\frac{1}{\epsilon^2}$ signifies a quadratic UV divergence?

A: The order of the $\varepsilon$ pole is not related to the power of the divergence. Indeed the poles are only sensitive to $\log$-like divergences. Power-like divergences are killed by dimensional regularization. By this I mean that if you were to regularize with a cutoff, terms with $\Lambda^k$ will disappear and terms with $\log\Lambda$ will become poles in $\varepsilon$. This is related to the fact that in dim-reg the following class of integrals vanish:
$$
\int d^Dp\, (p^2)^\alpha = 0\,.\tag{1}\label{int}
$$
There is however a way to determine the order of the poles in $\varepsilon$. For an integral with $L$ loops it's bounded by $L$, but it might be less. A theorem shows that the maximal order of the pole of an $L$ loop diagram with $V$ vertices in the massless theory is given by $\min(V-1,L)$. This is in agreement with what you found as $m\to 0$ because $V=2$.
This theorem can also be used in general, upon considering massive propagators are vertices with two legs (with coupling $m^2$).
The intuitive explanation of this particular case is as follows: the "overall" divergences (i.e. those that show up when all loop momenta are sent to infinity at the same speed) only produce simple poles in $\varepsilon$, while the higher poles are given by subdivergences. Subdivergences can be interpreted as subdiagrams of the original diagram that are themselves divergent. In this case the only subdiagrams are the two single loop tadpoles, which are known to vanish when $m^2 = 0$.

I can suggest a book that shows both that the integral $\eqref{int}$ vanishes (around p. 63) and proves the theorem for the maximal order of the poles (Sec. 2.8).

A: The power counting of momentum $p$ has nothing to do with the divergence power like $1/\epsilon^a$, actually what we are doing here for calculating loop diagrams is translating(mapping) divergence into the language of Gamma function. I think we can call it Gamma function regularization. I will show you examples as the following,
as we know the $\beta$-function is defined to be
\begin{align}
B(\alpha, \beta ) \equiv \int_0^1 d x x^{\alpha-1}(1-x)^{\beta-1}=\frac{\Gamma(\alpha)\Gamma(\beta)}{\Gamma(\alpha+\beta)}.
\end{align}
All the divergence like $1/\epsilon$ comes from $\Gamma(\epsilon)$, for example,
\begin{align}
B(\epsilon, 1 ) \equiv \int_0^1 d x x^{-1+\epsilon}=\frac{\Gamma(\epsilon)\Gamma(1)}{\Gamma(1+\epsilon)}=\frac{1}{\epsilon}.
\end{align}
However, the power counting of $x$ tell us the integral is approximately $x^{\epsilon}$. Also, we can see
\begin{align}
B(-1+\epsilon, 1 ) \equiv \int_0^1 d x x^{-2+\epsilon}=\frac{\Gamma(-1+\epsilon)\Gamma(1)}{\Gamma(\epsilon)}=-1-\epsilon+O(\epsilon^2).
\end{align}
Thus, we can conclude
\begin{align}
\int_0^1 d x \frac{1}{x^2}=-1.
\end{align}
It looks like regularization always gives us weird results, for example, Riemann Zeta regularization can give us $1+2+3+4+\cdots =-1/12$. Anyway, here, the power of momentum $p$ has nothing to do with the the power of $\epsilon$, at least, they are not simply related with the same power.


text:
Q: Joins in sql not to consider for null in left outer join employee table containing empCode (fk), empName etc
role table containing roleCode (fk), roleName etc
employeeRoleMap table contains data of Many-To-Many of both (id, empCode, roleCode, isPrimaryRole etc)
One Employee can have many roles, among them only 1 primary role (isPrimary = 1)
To display employee details and primary role, I need to work on employee and employeeRoleMap table
So, query
select em.empCode, em.empName, em.roleCode
FROM employee em
left join employeeRoleMap erm
    on (em.empCode=erm.empCode AND erm.isPrimary=1)

For which primary role is not there, it will show null. Okay.
But, now I want addition role details field like roleName.
So, I tried cross-join
select em.empCode, em.empName, em.roleCode
FROM employee em
LEFT JOIN employeeRoleMap erm
    on (em.empCode=erm.empCode AND erm.isPrimary=1)
CROSS JOIN role r
WHERE em.roleCode = r.roleCode

It's working for who has roleCode, for employee having null as primary role code, those rows are getting ignored.
But, it shouldn't be the case right as employee is the left outer join even if rolecode is there or not, it should show

A: Instead of using CROSS JOIN, You can use LEFT JOIN
select em.empCode, em.empName, em.roleCode,r.RoleName
FROM employee em
LEFT JOIN employeeRoleMap erm
    on (em.empCode=erm.empCode AND erm.isPrimary=1)
LEFT JOIN role r ON em.roleCode = r.roleCode

A: You could try
Select em.empCode, em.empName, em.roleCode
     FROM employee em
 LEFT JOIN employeeRoleMap erm
     on (em.empCode=erm.empCode AND erm.isPrimary=1)
 LEFT JOIN role r
    on em.roleCode = r.roleCode

Without sample data it would be very difficult to know whether this would work or not.


text:
Q: cordova saveToPhotoAlbum changes the name of the picture env: cordova-2.9.0rc1, android 4.4
I use the following code:
        navigator.camera.getPicture(
            that.uploadPhoto,
            that.onCaptureFail, {
                destinationType: Camera.DestinationType.FILE_URI,
                sourceType: Camera.PictureSourceType.CAMERA,
                mediaType: Camera.MediaType.PICTURE,
                saveToPhotoAlbum: true
            }
        );

it works fine ONLY that there is a race condition:
the saveToPhotoAlbum apparently change the name of the picture,
therefore the uploadPhoto fail (if it happens after the saveToPhotoAlbum).
This is an educated guess about what really going on there...
any info, or solution is welcome
I will try to upgrade cordova to see if it solve this.

A: It seems that cordova upgrade (to 5.1.1) solve this issue.


text:
Q: Creating a common method for Capistrano tasks Let's say in my standard deploy.rb file I have a set of namespaces. I have a common task that lists RPM packages based on a variable I pass to it. When I run this as is, it complains about capture being an undefined method. If I include that method inside the deploy.rb file, it works just fine.
Mind you, I'm new to ruby and to OOP so I'm sure I'm doing this the wrong way. :-)
deploy.rb
load 'config/module'

namespace :lp_app do
desc "LP tasks"

co = Tasks::Commands.new()

    task :list do
        co.list_pkg("LP")
    end
end

module.rb
module Tasks
    class Commands
        def list_pkg(component)
            File.open("#{component}.file.list", "r").each_line do |line|
                pkg_name = "#{line}".chomp

                set :server_pkg, capture("rpm -q #{pkg_name}")

                puts "#{server_pkg}"
            end
        end
    end
end

A: You are trying to use Capistano specific commands outside of Capistrano.  If you want to set a variable to the result of something you run on the command line, try the backtick (`).
module Tasks
    class Commands
        def list_pkg(component)
            File.open("#{component}.file.list", "r").each_line do |line|
                pkg_name = "#{line}".chomp

                server_pkg = `rpm -q #{pkg_name}`

                puts server_pkg
            end
        end
    end
end


text:
Q: Can't disable adaptive brightness I have a dell latitude 3410 laptop with intel i7 10510u CPU and windows 10 pro 20H2. This device has an adaptive brightness feature (windows feature I guess) I don't like it at all. So I tried to disable it in many ways but failed. Here are the methods I tried:

*

*I tried to disable it under power settings on the control panel but here is what I got: Power plans
Power plan settings
That is, there is no power plan other than balanced, and there is no setting for adaptive brightness in the advanced options of the plan. So I tried these commands on cmd to add the other plans but it did not work:
(Power saver)
"powercfg -duplicatescheme a1841308-3541-4fab-bc81-f71556f20b4a"
(High Performance)
"powercfg -duplicatescheme 8c5e7fda-e8bf-4a96-9a85-a6e23a8c635c"

*I tried the intel graphics command centre but there is no power options section there.intel command centre I tried to reinstall the graphics driver but nothing has changed.

*I tried to disable adaptive brightness service in services.msc but there was no service with that name.

A: It is in the BIOS settings.
Click on the display option in the left menu and disable the ecopower option on the screen that appears.
Thanks to Aganju for their comment.

A: I have seen a lot of answers attempting to address this problem that did not work for me. I have an HP Envy with Windows 10 and this is what did work for me.

*

*Go to the device manager, find the Display drivers, and disable the Intel graphics driver.

*Go to regedit or the Windows Registry Editor and do a global search for brightnessoverride. Mine was in HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\SideBySIde\Winners\amd64_microsoft-windows-g..-brightnessoverride...[some value here].
2a. Open the Default Value and change it to 0.0. Mine was originally 10.0.
2b. Global search for IsAutobrightnessOnByDeafult. Mine was in HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\PolicyManager\default\DispalyEnhancement\IsAutobrightnessOnByDefault. Open up the IsSetting and change the value to 0.0.

*Reboot.

*Go back to the device manager and enable the Intel graphics driver.


text:
Q: get index and id of selected edittext for further processing New to android and programming in general, so learning concepts as I go.
I have a LinearLayout to which I am adding edittexts dynamically.
I need to be able to get the Index AND Id of any edittext when it is selected or in focus.
I have tried looping through a child count to check for selected like so:
int count = llmain.getChildCount();
      for (int i=0; i< count; ++i) {
          if ((llmain.getChildAt(i).isSelected()) == true){
            //Do Stuff
          }

but I have no idea if its even close, and that would be only for index.....
Help would be greatly appreciated!
Thanks
EDIT: still dont have a reliable way to achieve this. The example below with the
if(v instanceOf EditText) {
id = v.getId();
index = ll.indexOfChild(v);

returns a -1 for index and a ten digit number for the id, however, i am assigning an id on creation. ?The odd thing is that the code inside the "if" is running, so it at least thinks it has the focused view. Now, if I change the "instanceof" to a null check like
if (v != null){
            id = v.getId();
            index = llmain.indexOfChild(v);

AND I add a setFocusableInTouchMode(true), I get a proper return, however, it then acts like i called clearFocus(), because none of the EditTexts are focused. Here is my full proof of concept code that returns the correct values but no longer lets the EditTexts actually have focus.
@Override
public boolean dispatchKeyEvent(KeyEvent event) {

    if ((event.getAction() == KeyEvent.ACTION_DOWN) &&(event.getKeyCode() == 66)) // KeyEvent.* lists all the key codes u pressed
    {
        View myView = linflater.inflate(R.layout.action, null);
        myView.setId(pos);
        pos++;
        myView.setFocusableInTouchMode(true);
        llmain.addView(myView);
        myView.requestFocus();
        View v = llmain.findFocus();

        if (v != null){
            id = v.getId();
            index = llmain.indexOfChild(v);
            Context context = getApplicationContext();
            CharSequence text = "index is:" + index + "id is:" + id;
            int duration = Toast.LENGTH_SHORT;

            Toast toast = Toast.makeText(context, text, duration);
            toast.show();
            }

    }
    return false;
}

This returns the correct values unless I comment the setFocusableInTouchMode line, then it goes back to the odd -1 for index and ten digit for ID.   What am I doing wrong? going to have to be a good (and working) answer to get over half of my rep.....
So nobody has a solution for this? its still driving me nuts!
thanks again

A: My initial thought would be to set the ID equal to the index when adding an EditText, assuming only EditTexts will be in this particular layout:
LinearLayout llMain = (LinearLayout)findViewById(R.id.llmain);
EditText editText = new EditText(this);
//0-based index, so get the number of current views, and use it for the next
editText.setId(llMain.getChildCount());
llMain.addView(editText);

Then, to retrieve the info, put a check into a listener of some sort (onTouch, onFocus, something like that):
@Override
public void onTouch(View v, MotionEvent ev) {
    int indexAndId = v.getId();
}

Give this a shot:
LinearLayout ll = (LinearLayout)findViewById(R.id.ll);
int index, id;

//finds the currently focused View within the ViewGroup
View v = ll.findFocus();

if(v instanceOf EditText) {
    id = v.getId();
    index = ll.indexOfChild(v);
}

A: That seems like it would work to me, have you tested it and it isn't working?
llmain.getChildAt(i).getId(); will return the views ID to you.


text:
Q: Best practice for extracting Razor-embedded JavaScript code into a separate file I have a large .cshtml file that contains a lot of inline JavaScript. To me the ability to do something like this is very useful:
function submitForm() {
    $.ajax({
        url: "@Url.Action("Action", "Controller")",
        type: "post",
        data: $form.serialize()
    });
}

However as the code size grows, Intellisense is getting extremely slow and I would like to extract my JavaScript code into a separate .js. file. I know there is RazorJS but I prefer not to use that in my project.
Should I extract these Razor expressions into JavaScript variables, extract the remaining code into a separate file and then reference the values from there instead? What's the best practice for this?

A: You can do some of this with unobtrusive JS techniques, e.g. putting the action on the form (even if you don't actually submit the form).
View
<!-- Of course, you would probably use Html.BeginForm() here -->
<form action="@Url.Action("Action", "Controller")" id="form1"></form>

Script File
function submitForm() {

    // you can abstract this further if you don't like having IDs
    // hardcoded (I don't). Data attributes can help with this.
    var form = $("#form1");

    $.ajax({
        url: form.attr("action"),
        type: "post",
        data: form.serialize()
    });
}

However as the code size grows, Intellisense is getting extremely slow
  and I would like to extract my JavaScript code into a separate .js.
  file.

You perform more extensive abstraction by adding data-* attributes to relevant elements. While this is very clean, it can also make your code unduly complex.
If you have hundreds of lines of JavaScript, definitely spend the time to extract it. If you only have a few dozen lines of pure "plumbing" code, I'd try to find out why Intellisense is slow.

A: There is another technique to do what you want to do, but I'm not sure it is ideal.
Simply create a partial view (.cshtml), only containing a <script></script> element, and inside place the js you are willing to extract.
You can then leave your Html helpers just like they were in your JS, and simply use the Html.Partial helper in the original page, to display your newly created partial view with your JS code.
As your file IS a cshtml file, razor will parse it, as it is already doing it in your current page.


text:
Q: Flex SDK missing fundamental things alt text http://img710.imageshack.us/img710/4107/flashbuildershite.jpg
All of a sudden Flash Builder 4 is missing all kinds of fundamental things and is generating incorrect errors. I've had the same issue yesterday, where I fixed it by downloading a new Flex SDK and importing that into FB. I did this again, but this time it fixed nothing.
I don't think it's something I did, like removing critical references from the build path. The errors also appeared on projects I was not working on at the time. It occurs for ActionScript, Flex and Flex Library projects alike.

Update 3: Well, i've singled the problem down to a single piece of code, though a very simple one. I can make a new workspace in FB and things work ok, then screw the workspace up forever by adding this code to a project. All projects will have errors and closing or even removing the faulty project does not change this. Making another new workspace (without the faulty code) makes my projects compile again.
Link: http://www.the3rdage.net/files/2745/Main.as
(i've uploaded the file in case an odd character or encoding error causes the error)

Update 2: I've tried manual compiling with mxmlc, the same errors occur. It appears to be an SDK problem, not Flash Builder.

Update: I find this stack trace in the Flash Builder error log:

!ENTRY com.adobe.flexbuilder.project 4 43 2010-05-11 11:55:47.495
!MESSAGE Uncaught exception in compiler
!STACK 0
java.lang.NullPointerException
    at macromedia.asc.semantics.ConstantEvaluator.evaluate(ConstantEvaluator.java:2592)
    at macromedia.asc.parser.VariableBindingNode.evaluate(VariableBindingNode.java:64)
    at macromedia.asc.semantics.ConstantEvaluator.evaluate(ConstantEvaluator.java:2233)
    at macromedia.asc.parser.ListNode.evaluate(ListNode.java:44)
    at macromedia.asc.semantics.ConstantEvaluator.evaluate(ConstantEvaluator.java:2578)
    at macromedia.asc.parser.VariableDefinitionNode.evaluate(VariableDefinitionNode.java:48)
    at macromedia.asc.semantics.ConstantEvaluator.evaluate(ConstantEvaluator.java:2310)
    at macromedia.asc.parser.StatementListNode.evaluate(StatementListNode.java:60)
    at macromedia.asc.semantics.ConstantEvaluator.evaluate(ConstantEvaluator.java:2503)
    at macromedia.asc.parser.WithStatementNode.evaluate(WithStatementNode.java:44)
    at macromedia.asc.semantics.ConstantEvaluator.evaluate(ConstantEvaluator.java:2310)
    at macromedia.asc.parser.StatementListNode.evaluate(StatementListNode.java:60)
    at macromedia.asc.semantics.ConstantEvaluator.evaluate(ConstantEvaluator.java:2891)
    at macromedia.asc.parser.FunctionCommonNode.evaluate(FunctionCommonNode.java:106)
    at macromedia.asc.semantics.ConstantEvaluator.evaluate(ConstantEvaluator.java:2905)
    at macromedia.asc.parser.FunctionCommonNode.evaluate(FunctionCommonNode.java:106)
    at macromedia.asc.semantics.ConstantEvaluator.evaluate(ConstantEvaluator.java:3643)
    at macromedia.asc.parser.ClassDefinitionNode.evaluate(ClassDefinitionNode.java:106)
    at macromedia.asc.semantics.ConstantEvaluator.evaluate(ConstantEvaluator.java:3371)
    at macromedia.asc.parser.ProgramNode.evaluate(ProgramNode.java:80)
    at flex2.compiler.as3.As3Compiler.analyze4(As3Compiler.java:709)
    at flex2.compiler.CompilerAPI.analyze(CompilerAPI.java:3089)
    at flex2.compiler.CompilerAPI.analyze(CompilerAPI.java:2977)
    at flex2.compiler.CompilerAPI.batch2(CompilerAPI.java:528)
    at flex2.compiler.CompilerAPI.batch(CompilerAPI.java:1274)
    at flex2.compiler.CompilerAPI.compile(CompilerAPI.java:1496)
    at flex2.tools.oem.Application.compile(Application.java:1188)
    at flex2.tools.oem.Application.recompile(Application.java:1133)
    at flex2.tools.oem.Application.compile(Application.java:819)
    at flex2.tools.flexbuilder.BuilderApplication.compile(BuilderApplication.java:344)
    at com.adobe.flexbuilder.multisdk.compiler.internal.ASApplicationBuilder$MyBuilder.mybuild(ASApplicationBuilder.java:276)
    at com.adobe.flexbuilder.multisdk.compiler.internal.ASApplicationBuilder.build(ASApplicationBuilder.java:127)
    at com.adobe.flexbuilder.multisdk.compiler.internal.ASBuilder.build(ASBuilder.java:190)
    at com.adobe.flexbuilder.multisdk.compiler.internal.ASItemBuilder.build(ASItemBuilder.java:74)
    at com.adobe.flexbuilder.project.compiler.internal.FlexProjectBuilder.buildItem(FlexProjectBuilder.java:480)
    at com.adobe.flexbuilder.project.compiler.internal.FlexProjectBuilder.build(FlexProjectBuilder.java:306)
    at com.adobe.flexbuilder.project.compiler.internal.FlexIncrementalBuilder.build(FlexIncrementalBuilder.java:157)
    at org.eclipse.core.internal.events.BuildManager$2.run(BuildManager.java:627)
    at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42)
    at org.eclipse.core.internal.events.BuildManager.basicBuild(BuildManager.java:170)
    at org.eclipse.core.internal.events.BuildManager.basicBuild(BuildManager.java:201)
    at org.eclipse.core.internal.events.BuildManager$1.run(BuildManager.java:253)
    at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42)
    at org.eclipse.core.internal.events.BuildManager.basicBuild(BuildManager.java:256)
    at org.eclipse.core.internal.events.BuildManager.basicBuildLoop(BuildManager.java:309)
    at org.eclipse.core.internal.events.BuildManager.build(BuildManager.java:341)
    at org.eclipse.core.internal.events.AutoBuildJob.doBuild(AutoBuildJob.java:140)
    at org.eclipse.core.internal.events.AutoBuildJob.run(AutoBuildJob.java:238)
    at org.eclipse.core.internal.jobs.Worker.run(Worker.java:55)

A: Did you get a chance to list this issue in their bugs list. I have not yet tried Flex 4. did you try to refresh your project and re open your flash builder.
Update:
What about a simple project. I think you are trying to load something which its not able to get.
mxmlc - verify-digests

Try this.

A: Problems I've had that were somewhat similar, once I had FB running under the wrong version of Java. Another time I had done some edits to the flex-config.xml file in order to make it work with a Maven plugin we had written in house. After that we made the plugin look at a copy of the original xml file, so that problem went away.
hth.

A: Might i recommend HFCD? The HellFire Compile Daemon is an out of process flex compiler that speeds up compile times immensely, and almost more importantly runs in a separate process from FlashBuidler. I have had some absolutely horrendous errors with Flash Builder due to the complexity and size of our project, where HFCD has helped tremendously here.


text:
Q: Does the phrasal verb "show X around" need an indirect object? I am not sure if the phrasal verb "show X around" needs an indirect object, X being a direct object. I am thinking you need to show a person around somewhere, but I am also thinking it might not be necessary given the context might make it clear, but I am not sure if you can just omit it.
Here's an example sentence, so that the question is more easily understood:

The plant manager showed investors around the plant.

A: You can say both, and you don't have to be too explicit about the place: it's the place where the people are.

*

*The plant manager showed investors around the plant

*The plant manager welcomed the investors to the plant and showed them around

*Welcome.  Let me show you around.


text:
Q: Solving errors when trying to call unmanaged C++ from C++/CLI I have some native C++ code that I want to use in C# and after doing some research I decided to create a C++/CLI wrapper for the native code. So far, so good. When running the program that contains the C++/CLI class, it works perfectly, but when I try to create the library that will provide me the chance of using the functionality of the native code in C#, I get the aforementioned errors (LNK2028 and LNK2019). Although I have tried several configurations for the linker and the compiler, I still cannot manage to get rid of these errors.
This is the code for the working wrapper:

//Wrapper_src.h

#include <cstdio>
#include "Project_Manager.h"

using namespace System;

public ref class WrapperParabola
{
private:
    ProjectManager *mainPM; //ProjectManager is the main class from the native code

public:
    WrapperParabola()
    {
        mainPM = new ProjectManager;
    }

    void InitSphereInfo(float R, float Cx, float Cy, float Cz, float H0, float H1, float dH, int segm)
    {
        mainPM->Init_SphereInfo(R, Cx, Cy, Cz, H0, H1, dH, segm);
    }

    void InitParableInfo(float P, float Refl, int Lsegm, int HSegm, float Lng)
    {
        mainPM->Init_ParableInfo(P, Refl, Lsegm, HSegm, Lng);
    }

    void InitRaysSetUpInfo(float Ora0, float Ora1, float dOra, int GridN, int NRays)
    {
        mainPM->Init_RaysSetUpInfo(Ora0, Ora1, dOra, GridN, NRays);
    }

    void InitSTPInfo(int zi, int luna, float LongLegala, float LongLoc, float Latitudine, float OraLegala, float UnghiInclinare, float UnghiAbatere)
    {
        mainPM->Init_STPInfo(zi, luna, LongLegala, LongLoc, Latitudine, OraLegala, UnghiInclinare, UnghiAbatere);
    }

    void ProcessData(void)
    {
        mainPM->ProcessData();
    }

    void PrintOutputData(void)
    {
        mainPM->PrintOutputData();
    }

    ~WrapperParabola()
    {
        this->!WrapperParabola();
    }

    !WrapperParabola()
    {
        delete mainPM;
    }
};

int main(void)
{
/*********************Test**********************/
WrapperParabola^ wrapperP = gcnew WrapperParabola;

//Init input data
wrapperP->InitSphereInfo(0, 0, 0, 0, 0, 0, 0, 0);
wrapperP->InitParableInfo(0, 0, 0, 0, 0);
wrapperP->InitRaysSetUpInfo(0, 0, 0, 0, 0);
wrapperP->InitSTPInfo(0, 0, 0, 0, 0, 0, 0, 0);

//Process read data
wrapperP->ProcessData();

//Print the results
wrapperP->PrintOutputData();

Console::WriteLine("Data Processed Successfully!");
std::getchar();

return 0;
}

And this is the code for the Library that I am trying to build:
// CppCodeManagerLib.h
#pragma once

#include "Project_Manager.h"

using namespace System;

namespace CppCodeManagerLib {

public ref class CodeManager
{
private:
    ProjectManager *mainPM;
public:
    CodeManager()
    {
        mainPM = new ProjectManager;
    }

    void InitSphereInfo(float R, float Cx, float Cy, float Cz, float H0, float H1, float dH, int segm)
    {
        mainPM->Init_SphereInfo(R, Cx, Cy, Cz, H0, H1, dH, segm);
    }

    /*...*/
};
}

As I said, I am interested in the changes that I have to make to the code (either to the native one or to the managed one) or to the commands and restrictions provided to the linker and to the compiler, in order to make the code usable in C#.
P.S: The complete errors are:
Error   2   error LNK2028:unresolved token (0A00003A) "public: void __thiscall ProjectManager::Init_SphereInfo(float,float,float,float,float,float,float,int)"
(?Init_SphereInfo@ProjectManager@@$$FQAEXMMMMMMMH@Z) referenced in function "public: void __clrcall CppCodeManagerLib::CodeManager::InitSphereInfo(float,float,float,float,float,float,float,int)"
(?InitSphereInfo@CodeManager@CppCodeManagerLib@@$$FQ$AAMXMMMMMMMH@Z) E:\Documents and Settings\zalman\Desktop\CppCodeManagerLib\CppCodeManagerLib\CppCodeManagerLib.obj CppCodeManagerLib

and
Error   3   error LNK2019: unresolved external symbol "public: void __thiscall ProjectManager::Init_SphereInfo(float,float,float,float,float,float,float,int)"
(?Init_SphereInfo@ProjectManager@@$$FQAEXMMMMMMMH@Z) referenced in function "public: void __clrcall CppCodeManagerLib::CodeManager::InitSphereInfo(float,float,float,float,float,float,float,int)"
(?InitSphereInfo@CodeManager@CppCodeManagerLib@@$$FQ$AAMXMMMMMMMH@Z)    E:\Documents and Settings\zalman\Desktop\CppCodeManagerLib\CppCodeManagerLib\CppCodeManagerLib.obj  CppCodeManagerLib

Thanks!

A: According to the MSDN page for LNK2028, it's due to having mismatched calling conventions specified (or defaulted). http://msdn.microsoft.com/en-us/library/ms235590%28v=vs.80%29.aspx


text:
Q: @Autowired objects getting null value Trying to set up a project but fail at Autowiring objects through Spring.
package se.hsr.web;

public class TestRunner {

    public static void main(String[] args) {
        ContactDAO cd = new ContactDAOImpl();
        Contact contact = new Contact();
        contact.setFirstname("Zorro");
        cd.addContact(contact);
    }

}

package se.hsr.web;

Running this gives me a NullPointerException when cd.addContact is invoked.
The ContactDaoImpl:
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

@Repository
public class ContactDAOImpl implements ContactDAO {

    @Autowired
    private SessionFactory sessionFactory;

    public void addContact(Contact contact) {
        sessionFactory.getCurrentSession().save(contact);
    }

My servlet file:
    <?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:p="http://www.springframework.org/schema/p"
    xmlns:tx="http://www.springframework.org/schema/tx"
    xmlns:context="http://www.springframework.org/schema/context"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context-3.0.xsd">

    <context:component-scan
        base-package="se.hsr.web"/>

    <bean id="viewResolver"
        class="org.springframework.web.servlet.view.UrlBasedViewResolver">
        <property name="viewClass"
            value="org.springframework.web.servlet.view.JstlView" />
        <property name="prefix" value="/WEB-INF/jsp/" />
        <property name="suffix" value=".jsp" />
    </bean>

    <bean id="propertyConfigurer"
        class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"
        p:location="/WEB-INF/jdbc.properties" />

    <bean id="dataSource"
        class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close"
        p:driverClassName="${jdbc.driverClassName}"
        p:url="${jdbc.databaseurl}" p:username="${jdbc.username}"
        p:password="${jdbc.password}" />

     <bean id="sessionFactory"
        class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
        <property name="dataSource" ref="dataSource" />
        <property name="configLocation">
            <value>classpath:hibernate.cfg.xml</value>
        </property>
        <property name="configurationClass">
            <value>org.hibernate.cfg.AnnotationConfiguration</value>
        </property>
        <property name="hibernateProperties">
            <props>
                <prop key="hibernate.dialect">${jdbc.dialect}</prop>
                <prop key="hibernate.show_sql">true</prop>
            </props>
        </property>
    </bean>

    <bean id="contactDAOImpl"
        class="se.hsr.web.ContactDAOImpl"/>

    <context:annotation-config/>

</beans>

My hibernate.cfg.xml file:
<?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
    "-//Hibernate/Hibernate Configuration DTD//EN"
    "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">

<hibernate-configuration>
    <session-factory>
        <mapping class="se.hsr.web.Contact" />
    </session-factory>

</hibernate-configuration>

My web.xml file:
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns="http://java.sun.com/xml/ns/javaee"
    xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
    id="WebApp_ID" version="2.5">
    <display-name>HSRMVC</display-name>
    <welcome-file-list>
        <welcome-file>index.jsp</welcome-file>
    </welcome-file-list>

    <servlet>
        <servlet-name>HSR</servlet-name>
        <servlet-class>
            org.springframework.web.servlet.DispatcherServlet
        </servlet-class>
        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>HSR</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>
</web-app>

I suppose the error is that the SessionFactory isn't getting initialized via @Autowired correctly, but why is that? Could it be a simple directory structure/filepath problem or is it something more complicated?
Thanks in advance.
UPDATE:
ContactDAOImpl class:
@Repository
public class ContactDAOImpl extends HibernateDaoSupport implements ContactDAO{

    @Autowired
    @Qualifier("sessionFactory")
    private SessionFactory sessionFactory;

    public void addContact(Contact contact) {
        sessionFactory.getCurrentSession().save(contact);
    }

A: You need this at the top of your test class:
@RunWith(SpringJUnit4ClassRunner.class)
// ApplicationContext will be loaded from "/applicationContext.xml" and "/applicationContext-test.xml"
// in the root of the classpath
@ContextConfiguration(locations={"/applicationContext.xml", "/applicationContext-test.xml"})
public class MyTest {

I assumed JUnit4; my oversight.
You do need the context configuration tag in an application context somewhere, but I don't see anyplace in your code where you're actually opening an application context file and creating an ApplicationContext.  Usually that's done in a set up method for your test.  You'll have better luck if you actually create an ApplicationContext somewhere.  Try reading the XML from your CLASSPATH in a setup method and see if that helps.

A: In order to use Spring features (autowiring, call to post construct methods or aspects) you need to let Spring instanciate the instances instead of using new.
For instance:
public static void main(String[] args) {
    ApplicationContext context = AnnotationConfigApplicationContext("se.hsr.web")
    ContactDAO cd = (ContactDAO)context.getBean("contactDAOImpl");
    Contact contact = new Contact();
    contact.setFirstname("Zorro");
    cd.addContact(contact);
}

AnnotationConfigApplicationContext will scan the classes in the classes in the se.hsr.web package to for classes with Spring annotations. It requires Spring 3.0 to work. Before that you should add the following line in your applicationContext.xml file:
<context:component-scan base-package="se.hsr.web" />

A: You need this in your Spring configuration for autowiring to work
xmlns:context="http://www.springframework.org/schema/context"
....
<context:annotation-config/>

A: Add @Component/@Repository to the DAO/DAOImpl.

A: you are creating the POJO outside of the spring context.
if you really want to be able to instanciate "manually", you can fix this, by adding <context:spring-configured /> to your configuration, and then annotating ContactDAOImpl with @Configurable

A: You need to retrieve the ContactDAO instance from Spring context. You are initing yourself with new keyword.
See the below link;
@Autowired annotation not able to inject bean in JUnit class
or if not unit test
ClassPathResource resource = new ClassPathResource("beans.xml");
BeanFactory factory = new XmlBeanFactory(resource);
beanFactory.getBean("nameOfYourBean");

http://static.springsource.org/spring/docs/2.0.x/reference/beans.html


text:
Q: AppleMusicKit SDK / Sample Project - UserToken issue I'm currently experimenting with the Adding-Content-to-Apple-Music code found here: https://developer.apple.com/musickit/
I'm using:
XCode 9 beta 2,
iOS 11 (iPhone 5s)
I have a developer token (which works when I query the Apple Music API searching songs etc...) but I now want to use this to exchange for a User Token so I can perform write actions against my Apple Music account.
The test app fires up and allows me to request authentication. From this I can see:

*

*MPMedia Library - Authorized

*SKCloudServicesController - Authorized

*Capabilities:

*

*Add to Cloud Music Library

*Music Catalog Playback

My next obvious step is to use the developer token to gain the user token. However, as soon as I call the following:
cloudServiceController.requestUserToken(forDeveloperToken: developerToken, completionHandler: completionHandler)
i see the following error in the completionHandler  - can anyone help?
2017-07-14 10:05:39.179300+0100 Adding-Content-to-Apple-Music[1326:172100] [MC] Reading from public effective user settings.
2017-07-14 10:05:40.635503+0100 Adding-Content-to-Apple-Music[1326:172299] [core] "Error returned from daemon: Error Domain=com.apple.accounts Code=9 "(null)""
2017-07-14 10:05:40.636449+0100 Adding-Content-to-Apple-Music[1326:172100] SSAccountStore: Failed to fetch the backing accounts. error = Error Domain=com.apple.accounts Code=9 "(null)"
2017-07-14 10:05:40.800933+0100 Adding-Content-to-Apple-Music[1326:172297] [core] "Error returned from daemon: Error Domain=com.apple.accounts Code=9 "(null)""
2017-07-14 10:05:40.801259+0100 Adding-Content-to-Apple-Music[1326:172299] SSAccountStore: Failed to fetch the backing accounts. error = Error Domain=com.apple.accounts Code=9 "(null)"
An error occurred when requesting user token: The operation couldn't be completed. (SKErrorDomain error 1.)
In Settings > iTunes & App Store on my device I am logged in with my Apple ID. Same goes for Apple Music too.

A: Update on this:
I also posted about this over on the Apple dev forums. It was an error on their side and now appears to be fixed. I can get a UserToken in both iOS 10 and 11 now.


text:
Q: ASP nested if not working The following code snippet isn't working, can someone help me identify the problem. I'm using ASP on IIS 7.0
Code:
<%If session("var") <> "" Then
    If( instr(strSQL("Platform"), session("osversion")) > 0  ) Then %>
        <input type="image" src="images/download2.gif" name="submit" value="submit" />
    <%Else %>

 SOME ERROR MESSAGE

    <%End If %>
<%Else %>
    <input type="image" src="images/download2.gif" name="submit" value="submit" />
<%End If %>

Is the problem related to IIS 7.0 configuration for classic ASP?

A: Try to remove the "()" in the nested If. Like code below:
<%If session("var") <> "" Then
    If instr(strSQL("Platform"), session("osversion")) > 0  Then %>
        <input type="image" src="images/download2.gif" name="submit" value="submit" />
    <%Else %>

 SOME ERROR MESSAGE

    <%End If %>
<%Else %>
    <input type="image" src="images/download2.gif" name="submit" value="submit" />
<%End If %>

Now, what ever happends in the first if condition If session("var") <> "" Then, there should always be an output because of <%Else %>. The problem will be trim to the nested if. Check the values of strSQL("Platform") and session("osversion"). If those two are OK, check now instr(,). You can even do If instr(strSQL("Platform"), session("osversion")) > 0  Then changed to If true  Then just to check if it works.

A: *

*Try to avoid the cluttering of <% and %>, it makes it unreadable.

*Second do not repeat the same strings in different places in your
code.

*Third try to combine logic.

*Fourth pull out the strings

the code...

*

*Proposition A: session("var") <> ""

*Proposition B: instr(strSQL("Platform"), session("osversion")) > 0

Your code:
if a
    if b
        do alfa
    else
        do bravo
else
    do alfa

rewritten:
if not a or b
    do alfa
else
    do bravo

and now in ASP
<%
dim showButton, errMsg
showButton = "<input type='image' src='images/download2.gif' name='submit' value='submit' />"
errMsg = "
 SOME ERROR MESSAGE
"
If session("var") <> "" Then
    If( instr(strSQL("Platform"), session("osversion")) > 0  ) Then
        response.write showButton
    Else
        response.write errMsg
    End If
Else
    response.write showButton
End If
%>

<%
dim showButton, errMsg
showButton = "<input type='image' src='images/download2.gif' name='submit' value='submit' />"
errMsg = "
 SOME ERROR MESSAGE
"
If session("var") = "" or  (instr(strSQL("Platform"), session("osversion")) > 0) Then
    response.write showButton
Else
    response.write errMsg
End If
%>

<%
If session("var") = "" or (instr(strSQL("Platform"), session("osversion")) > 0) Then
    response.write "<input type='image' src='images/download2.gif' name='submit' value='submit' />"
Else
    response.write "
 SOME ERROR MESSAGE
"
End If
%>


text:
Q: eclipse Description: Type internal_static_callRequest_descriptor cannot be resolved or is not a field callRequest.java Java Problem I am building up a gRPC project (study purpose only) on eclipse, but my java files aren't being generated as their should be.
Below I will describe all the step that I did to start the project:

*

*First of all, created the project and named the package (groupId) and the class (artifactID).

*I copied and pasted all the necessaries dependencies on my pom file

*I created my proto files.

*I run the proto files and I got the error "Type internal_static_callRequest_descriptor cannot be resolved or is not a field"
The java files were created, but with a compile error.
No idea what I am suppose to do as I cannot edit the generated files.
I am brand new on gRPC, trying to learn it now. Then, any help or advice will be awesome
Thanks a million =)


text:
Q: How to make two pixel width splitter in Android I'm developing a simple Android application that would have an action bar on the top of the screen:

I already have the bar with the gradient background (drawable) and the arrow icon set but I'm not sure how to create that two pixel width splitter.
The color of the left column of pixels is #5e5e5e and the right one is #181818.
What is the best way (optimized for performance) to create such a reusable splitter?
The best would be to make this splitter as a widget.
Any help would be greatly appreciated!
UPDATE:
The bar is a LinearLayout with a gradient background and the arrow is a single transparent ImageView.

A: Use right margin on the left column. Or left margin on the right column. No need for a dedicated splitter view.
If you absolutely need the splitter to be a view, use View. You can give it a background and a size, that should be sufficient.

A: I ended up creating a 2x1 pixel PNG image and use it as a background of a View widget:
<View
     android:layout_width="2px"
     android:layout_height="fill_parent"
     android:background="@drawable/splitter"
/>


text:
Q: Input type[file] doesnot display the name of the file. Angularjs I am new to angularjs. The project is getting transitioned from jquery to angular. Initially, it was a nightmare with all the new terms and scarry topics. I am getting used to it now and actually enjoying working on angular.
I am stuck at one part and i hope someone could help me or suggest me here. Please refer to the jsfiddle.
http://jsfiddle.net/ash12/kk1s3a1d/12/
Here is th HTML code....

     File:

      Name:
      City:

    <input type='file' ng-model="activeItem.name">
    <select name="singleSelect" ng-model="activeItem.content">
          <option  value="" disabled="" selected="" style="display:none;">Select Name</option>
          <option>Rob</option>
          <option>Dilan</option>
    </select>
     <select name="singleSelect1" ng-model="activeItem.content1">
          <option value="" disabled="" selected="" style="display:none;">Select City</option>
          <option>China</option>
          <option>Korea</option>
          <option>United States</option>
    </select>
    <button ng-click="addItem()">+</button>

  {{item.name}}{{item.content}}
                 {{item.content1}}

Here is the controller function...
function ListController($scope) {
$scope.items = [{
    }];

$scope.activeItem = {
    name: '',
    content: '',
    content1:''
}

$scope.addItem = function () {
    $scope.items.push($scope.activeItem);
    $scope.activeItem = {} /* reset active item*/
}

}

Here, if i select the file name, name and city and then press on add button. It shows the list below. The problem is that it doesnot show the file which we have selected.
Can someone please tell me what to do in this case ? Also, i need the click button to be active only for 6 times. after adding the 6th time, it should not let me add any further. can someone suggest here ??

A: You need to do that by handling the onchange event of the file input
<input type='file' onchange="angular.element(this).scope().fileNameChanged(this)">

and In your controller
 $scope.fileNameChanged = function(el){
        $scope.activeItem.name = el.files[0].name
    }

To disable your add button, in your additem check for the length of your items array and disable the button using ng-disabled
See the updated fiddle here : http://jsfiddle.net/kk1s3a1d/15/

A: here is the working jsfiddle of your problem
http://jsfiddle.net/adiioo7/fA968/
you need to use onchange as mentioned below as ng-model and ng-change doesnt work with input type="file"
 <input type="file" ng-model="image" onchange="angular.element(this).scope().uploadImage(event)" />


text:
Q: Shell script that passes date from file to mysql How can I execute a linux batch script that reads a date from a file, passes it as a parameter into mysql script and then write current date into file?
Something like:

*

*read datefile   (one line with date as yyyy-mm-dd)

*mysql -u user -ppass < update.sql

*update.sql:   update table set x=y where date between $datefrom1 and curdate()

*write curdate() to datefile

A: Here is a proof of concept to learn from. You can figure the solution from here.

$ cat data
fox
$ aa=`cat data`
$ echo $aa
fox
$ echo The quick $aa jumped
The quick fox jumped over the lazy dog
$ echo The quick $aa jumped over the lazy dog > bb
$ more bb
The quick fox jumped over the lazy dog