text:
Q: Why does audit2why have nothing to do? I know I have an issue with SElinux. So I am following a tutorial that will help me understand the nature of the file access problems I am having. That was I can still have SElinux enforce as supposed to just disabling it.
Basically I have set SElinux set to permissive mode, for testing, and done a file action that would fail while it is enforcing. That way I will see what the message in the log looks like. Such a line looks like this:
type=USER_CMD msg=audit(1452912989.069:324790): pid=66581 uid=1001 auid=1001 ses=1352 subj=unconfined_u:unconfined_r:unconfined_t:s0-s0:c0.c1023 msg='cwd="/srv/dpca/www" cmd=7461696C202F7661722F6C6F672F61756469742F61756469742E6C6F67 terminal=pts/0 res=success'

Now since I am really new to this I refered to the tutorial and how it talks about getting audit2why to lay this out for me.
[matt@localhost www]$ sudo grep 1452912989.069:324790 /var/log/audit/audit.log | audit2why
Nothing to do

The grep does return the correct text. However audit2why appears to be returning "Nothing to do".
Is there something fundamental that I am doing wrong? End of the day I am trying to figure out what context to assign to some NGINX directories. I am sure I can just look them up but I wanted also to understand what I am doing as supposed to just running commands I see on the internet.
In case you are curious this is a small snippet of my web root directory context
drwxr-xr-x. nginx nginx unconfined_u:object_r:httpd_sys_content_t:s0 administrator
drwxr-xr-x. nginx nginx unconfined_u:object_r:httpd_sys_content_t:s0 bin
drwxr-xr-x. nginx nginx unconfined_u:object_r:httpd_sys_content_t:s0 cache

A: Note: I am still interested in an answer to my issue but I did want to post a work-around that I am using that gives just as useful information if audit2why was working how I would have expected.
Under the Howto for SELinux on CentOS.org there is a troubleshooting section. Therein is talks about how to use sealert to give human readable information parsed from the log "/var/log/audit/audit.log". So simply running
sudo sealert -a /var/log/audit/audit.log > ~/logfile.txt

allowed me to read the information I wanted and get suggestions about the proper security context for my web directories.
SELinux is preventing /usr/sbin/php-fpm from write access on the directory /srv/dpca/www/images.

*****  Plugin httpd_write_content (92.2 confidence) suggests   ***************

If you want to allow php-fpm to have write access on the images directory
Then you need to change the label on '/srv/dpca/www/images'
Do
# semanage fcontext -a -t httpd_sys_rw_content_t '/srv/dpca/www/images'
# restorecon -v '/srv/dpca/www/images'

Again, if someone knows about my original question about audit2why I would still like to know.

A: /var/log/audit/audit.log is a binary file. You can grep for the content with
grep -a AVC /var/log/audit/audit.log | audit2why


text:
Q: Rails - Knowing the model/action from a route I have a basic route :
get '/patients/:id/edit', to: 'patients#edit', as: 'patient_edit'

From the path "patient_edit_path", it is possible to reverse the link to have the model (Patient) and action (edit) linked?

A: Yes, you can use Rails.application.routes.recognize_path
Example:
patient_id = 1
Rails.application.routes.recognize_path(patient_edit_path(patient_id))
=> {:action=>"edit", :controller=>"patients", :id=>"1"}

redpajama_set_name: RedPajamaStackExchange


text:
Q: Python - not getting correct datetime upon reading time from excel file I have an excel file which has 3 columns as either date-time or date or time fields. I am reading it via xlrd package and I am getting time as milliseconds I suppose and when I am trying to convert it back to datetime I am getting wrong results.
I tried with converting the file to csv as well. That too doesn't help and I get weird datetime format which I am not able to comprehend.
Here is what I tried with the xlrd format. I prefer to use files with .xlrs extension as input because otherwise I have to convert excel files to .csv every time I get a new input file.
from xlrd import open_workbook
import os,pickle,datetime

def main(path, filename, absolute_path_organisation_structure):
    absolute_filepath = os.path.join(path,filename)

    wb = open_workbook(absolute_filepath)
    for sheet in wb.sheets():
        number_of_rows = sheet.nrows
        number_of_columns = sheet.ncols

        for row_index in xrange(1, sheet.nrows):
            row=[]
            for col_index in xrange(4,7): #4th and 6th columns are date fields
                row.append(sheet.cell(row_index, col_index).value)

            print(row)  #Relevant list formed with 4th, 5th and 6th columns
            print(datetime.datetime.fromtimestamp(float(row[0])).strftime('%Y-%m-%d %H:%M:%S'))

path = "C:\\Users\\***************\\NEW DATA"
MISfile  = "P2P_2015 - Copy.xlsx"
absolute_path_organisation_structure = "C:\\Users\\******************NEW DATA\\organisation.csv"
main(path, MISfile, absolute_path_organisation_structure)

Result:
[42011.46789351852, u'Registered', 42009.0]
1970-01-01 17:10:11
[42011.46789351852, u'Sent for CTG1 approval', 42010.0]
1970-01-01 17:10:11
[42011.46789351852, u'Sent back', 42010.0]
1970-01-01 17:10:11
[42011.46789351852, u'Registered', 42011.0]
1970-01-01 17:10:11
[42011.46789351852, u'Sent for CTG1 approval', 42011.0]
1970-01-01 17:10:11
[42011.46789351852, u'Sent for CTG2 approval', 42012.0]
1970-01-01 17:10:11
[42011.46789351852, u'CTG2 Approved', 42012.0]
1970-01-01 17:10:11
[42011.46789351852, u'Sent back', 42013.0]
1970-01-01 17:10:11
[42170.61667824074, u'Registered', 42144.0]
1970-01-01 17:12:50
[42170.61667824074, u'Registered', 42144.0]
1970-01-01 17:12:50
[42170.61667824074, u'Sent back', 42165.0]
1970-01-01 17:12:50
[42170.61667824074, u'Sent back', 42165.0]
1970-01-01 17:12:50
[42170.61667824074, u'Registered', 42170.0]
1970-01-01 17:12:50
[42170.61667824074, u'Registered', 42170.0]
1970-01-01 17:12:50

Actual input file:  (copied from excel)
1/7/2015 11:13  Registered  1/5/2015 0:00
1/7/2015 11:13  Sent for CTG1 approval  1/6/2015 0:00
1/7/2015 11:13  Sent back   1/6/2015 0:00
1/7/2015 11:13  Registered  1/7/2015 0:00
1/7/2015 11:13  Sent for CTG1 approval  1/7/2015 0:00
1/7/2015 11:13  Sent for CTG2 approval  1/8/2015 0:00
1/7/2015 11:13  CTG2 Approved   1/8/2015 0:00
1/7/2015 11:13  Sent back   1/9/2015 0:00
6/15/2015 14:48 Registered  5/20/2015 0:00
6/15/2015 14:48 Registered  5/20/2015 0:00
6/15/2015 14:48 Sent back   6/10/2015 0:00
6/15/2015 14:48 Sent back   6/10/2015 0:00
6/15/2015 14:48 Registered  6/15/2015 0:00
6/15/2015 14:48 Registered  6/15/2015 0:00

Why am I not able to read dates correctly? Why are they not simply coming up as strings so that I can easily convert them?

A: The issue is that you are interpreting the Excel datetime value as a UNIX timestamp, when they are not the same thing. The warning flag to look for is that the resulting values are all near the UNIX epoch (1970-01-01).
You can convert from an Excel datetime to UNIX by using the method described in this answer.
Windows/Mac Excel 2011
Unix Timestamp = (Excel Timestamp - 25569) * 86400

Mac Excel 2007
Unix Timestamp = (Excel Timestamp - 24107) * 86400

If you apply this conversion you should get the correct output:
timestamp = (float(row[0]) - 25569) * 86400
datetime.datetime.fromtimestamp(timestamp).strftime('%Y-%m-%d %H:%M:%S')

A:
xldate_as_tuple(xldate, datemode) [#]
Convert an Excel number (presumed to represent a date, a datetime or a time) into a tuple suitable for feeding to datetime or mx.DateTime constructors.

Source: http://www.lexicon.net/sjmachin/xlrd.html#xlrd.xldate_as_tuple-function
Usage Example: How to use ``xlrd.xldate_as_tuple()``

A: If the Excel file to read is a table can be simple and straightforward to use pandas.read_excel.
After transforming dates with pandas.to_datetime
from __future__ import absolute_import, division, print_function
import os
import pandas as pd

def main(path, filename, absolute_path_organisation_structure):
    absolute_filepath = os.path.join(path,filename)
    #Relevant list formed with 4th, 5th and 6th columns
    df = pd.read_excel(absolute_filepath, header=None, parse_cols=[4,5,6])
    # Transform column 0 and 2 to datetime
    df[0] = pd.to_datetime(df[0])
    df[2] = pd.to_datetime(df[2])
    print(df)

path = "C:\\Users\\***************\\NEW DATA"
MISfile  = "P2P_2015 - Copy.xlsx"
main(path, MISfile,None)


text:
Q: How do I check a row for a condition, and then once found change subsequent rows until a second condition is met in pandas? I'm struggling with some time series data in Pandas.  Basically I have a time series of hourly snow depth change over 15 days.  Its VERY jumpy and I would like to remove the spurious jumps (see graph of raw data linked).Snotel_TimeSeries
The data is something like this:
import pandas as pd
snofall_df = pd.DataFrame({'DateTime':['12/13/2021 2:00', '12/13/2021 3:00', '12/13/2021 4:00','12/13/2021 5:00', '12/13/2021 6:00', '12/13/2021 7:00', '12/13/2021 8:00', '12/13/2021 9:00','12/13/2021 10:00', '12/13/2021 11:00'], 'Raw': [25, 25, 79, 134, 134, 134, 134, 25, 26, 27]}

The best way I could think of to remove these jumps is to calculated a rate of change between each observation (since its hourly data this ends up being the hourly snowfall rate) using
snofall_df['Rate']=snofall_df['Raw'].diff()

This gives me the following table:

DateTime
Raw
Rate

#########
25
n/a

#########
25
0

#########
79
54

#########
134
55

#########
134
0

#########
134
0

#########
134
0

#########
25
-109

#########
26
1

#########
27
1

I would like to find all rows where the rate of change jumps unrealistically (like it would be crazy to have a snowfall rate of 10 inches in an hour!) and then set the values of snow depth to "n/a" UNTIL the snowfall rate decreases unrealistically (like the -109 in the rate column) while leaving all other values alone.
Basically I would like an "Adj_Depth" column added to the table like this:

DateTime
Raw
Rate
Adj_Depth

#########
25
n/a
25

#########
25
0
25

#########
79
54
n/a

#########
134
55
n/a

#########
134
0
n/a

#########
134
0
n/a

#########
134
0
n/a

#########
25
-109
25

#########
26
1
26

#########
27
1
27

I have tried things like
snofall_df['Adj_Depth]` = np.where((snofall_df['Rate'] >= 10) | (snofall_df['Rate'].shift(-1) <= -10), np.nan, snofall_df['Raw'])

This gets rid of all values where the rate increases or decreases to fast but it leaves all the high spurious points in between. I'm trying to avoid iterating over the column if possible as with large datasets this becomes quite cumbersome.
Does anyone know a "pythonic" way of doing the above operation within Pandas?  Thanks so much for any help anyone can provide on this.


text:
Q: Can I use Alloy to solve linear programming like problems? I want to find a solution for set of numerical equations and I wondering whether Alloy could be used for that.
I've found limited information on alloy that seem to suggest (to me, at least) that it could be done, but I've found no examples of similar problems.
It certainly isn't easy, so before investing time and some money in literature I'd like to know if this is doable or not.
Simplified example:
(1) a + b = c, (2) a > b, (3) a > 0, (4) b > 0,  (5) c > 0

One solution would be
a = 2, b = 1, c = 3

Any insights on the usability of Alloy or better tools / solutions would be greatly appreciated.
Kind regards,
Paul.

A: Daniel Jackson discourage using Alloy for numeric problems. The reason is that Alloy uses a SAT solver and this does not scale well since it severely limits the range of available integers. By default Alloy uses 4 bits for an integer: -8..7. (This can be enlarged with the run command but will of course slow down finding an answer.)  The mindset of not to use numbers also influenced the syntax, there are no nice operators for numbers. I.e. addition is 5.plus[6].
That said, your problem would look like:
pred f[a,b,c : Int] {
    a.plus[b] = c
    a > b
    a > 0
    b > 0
    c > 0
}

run f for 4 int

The answer can be found in the evaluator or text view. The first answer I got was a=4, b=1, c=5.
Alloy was developed around 2010 and since then there are SMT solvers that work similar to SAT solvers but can handle numeric problems as well. Alloy could be made to use those solvers I think. Would be nice because the language is incredibly nice to work with, the lack of number is a real miss.
Update Added a constraint puzzle at https://github.com/AlloyTools/models/blob/master/puzzle/einstein/einstein-wikipedia.als

A: Alloy is specialized as a relational constraint solver. While it can do very simple linear programming, you might want to look at a specialized tool like MiniZinc instead.


text:
Q: How to seamlessly decorate class I have some complex class hierarchy that realize all needed functionality. I'm referencing base abstract class from that hierarchy in my serialiazable class. I just need to add one extra property during serialization, but from side it should like that property has always been in that class. Right now json.net wraps it into name of property.
public class SerializeMe
{
  AbstractValidation _validation;
  public SerializeMe(AbstractValidation validation)
  {
     this._validation = validation;
  }

  [JsonProperty(PropertyName = "designer|displayName")]
  public string DisplayName
  {
    get { return string.Concat(_validation.Field, _validation.Type); }
  }

  public AbstractValidation Validation
  {
     get
     {
        return _validation;
     }
  }
}

What I get, for example:
 {
   "DisplayName":"F_Director_Empl_Rolepresence",
   "Validation":{
      "type":"presence",
      "field":"F_Director_Empl_Role"
    }
  }

I need:
 {
   "DisplayName":"F_Director_Empl_Rolepresence",
   "type":"presence",
   "field":"F_Director_Empl_Role"
 }

Here I need to get rid of Validation section - as if DisplayName is part of AbstractValidation class. I could inherit classes from ancestors of AbstractValidation but hierarchy is quite complex. Instead, I'm searching the way to decorate classes.

A: You would need to make a custom JsonConverter for your SerializeMe class in order to do what you want.  Perhaps something like this:
class CustomConverter : JsonConverter
{
    public override bool CanConvert(Type objectType)
    {
        return objectType == typeof(SerializeMe);
    }

    public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
    {
        SerializeMe sm = (SerializeMe)value;

        // Get child properties into a JObject
        JObject obj = JObject.FromObject(sm.Validation);

        // Now add the parent properties we're interested in
        obj.Add("DisplayName", sm.DisplayName);

        // Write the object to the output
        obj.WriteTo(writer);
    }

    public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
    {
        throw new NotImplementedException();
    }
}

Once you have the converter, decorate your SerializeMe class with a [JsonConverter] attribute so that Json.Net knows to use the custom converter:
[JsonConverter(typeof(CustomConverter))]
public class SerializeMe
{
    ...
}

Then, serialize as usual.  Here is a demo:
AbstractValidation av = new AbstractValidation
{
    Field = "F_Director_Empl_Role",
    Type = "presence"
};
SerializeMe sm = new SerializeMe(av);

string json = JsonConvert.SerializeObject(sm, Formatting.Indented);
Console.WriteLine(json);

Output:
{
  "Type": "presence",
  "Field": "F_Director_Empl_Role",
  "DisplayName": "F_Director_Empl_Rolepresence"
}


text:
Q: How to open bridge IP address in web browser? I have a few virtual machines that are set up on bridge network. One of this virtual machines (HDP sandbox) has the web ui and I wanna use it but it's IP is not opened on the browser. What's should i do?

A: As i understand it,your vm has a web server.if so,check the status of apache service.If it is not running,you have to start it.
service apache2 status
service apache2 start

after you run the commands above(command may be different due to linux distro),
enter ip address into the web browser.
also,you must be sure that HDP services are running.


text:
Q: Obter todos os elementos de uma lista cujo valor seja igual ao maior Tenho uma lista:
// pseudo-código
List<Object> abc = Arrays.asList({id: 7}, {id: 3}, {id: 7}, {id: 1}, {id: 4}, {id: 7}, {id: 7});

E quero pegar via stream apenas os objetos com o maior valor de id, ou seja, quero como resultado:
// pseudo-código
List<Object> abc = Arrays.asList({id: 7}, {id: 7}, {id: 7}, {id: 7});

A: Supondo que o objeto seja algo assim:
public class MyObject {
    private int id;
    public MyObject(int id) {
        this.id = id;
    }
    public int getId() {
        return id;
    }
}

Basta você agrupar os elementos de acordo com o id, ou seja, crie um Map que mapeia cada id para uma lista contendo os elementos que possuem aquele id.
Depois, basta pegar a lista correspondente ao maior id:
List<MyObject> list = Arrays.asList(new MyObject(7), new MyObject(3), new MyObject(7), new MyObject(1), new MyObject(4), new MyObject(7), new MyObject(7));
List<MyObject> objetosComMaiorId = list.stream()
        .collect(Collectors.groupingBy(MyObject::getId, TreeMap::new, Collectors.toList()))
        .lastEntry()
        .getValue();
System.out.println(objetosComMaiorId);

O método collect recebe um collector, que no caso é criado por groupingBy: é ele que faz o mapeamento de cada id para uma lista contendo os elementos que possuem aquele id.
E para fazer o mapeamento eu uso um TreeMap, que ordena as chaves automaticamente. E como as chaves são os id's, basta pegar o último (lastEntry) para ter a lista que corresponde ao maior id.

Claro que você também pode percorrer a lista duas vezes: uma para ver qual é o maior id, e outra para filtrar os elementos que possuem tal id:
int maiorId = list.stream()
        .mapToInt(MyObject::getId)
        .max()
        .orElse(-1);
List<MyObject> objetosComMaiorId = list.stream()
        .filter(o -> o.getId() == maiorId)
        .collect(Collectors.toList());

Esta solução percorre a lista duas vezes e só cria a sub-lista referente ao maior id, já a solução com TreeMap percorre a lista apenas uma vez, porém gera as sub-listas para todos os id's. É o velho e conhecido space-time tradeoff.

Sem stream
Só para constar, streams geralmente são mais lentas que um loop simples, e daria para resolver sem elas.
Seja usando o Map (e daria para obter o maior valor separadamente, aí nem precisaria usar TreeMap):
int maiorId = Integer.MIN_VALUE;
Map<Integer, List<MyObject>> map = new HashMap<>();
for (MyObject obj : list) {
    int id = obj.getId();
    if (id > maiorId) {
        maiorId = id;
    }
    if (!map.containsKey(id)) {
        map.put(id, new ArrayList<>());
    }
    map.get(id).add(obj);
}
List<MyObject> objetosComMaiorId = map.get(maiorId);

Ou percorrendo a lista duas vezes (uma para achar o maior id, outra para filtrar os elementos com este id):
int maiorId = Integer.MIN_VALUE;
for (MyObject obj : list) {
    if (obj.getId() > maiorId) {
        maiorId = obj.getId();
    }
}
List<MyObject> objetosComMaiorId = new ArrayList<>();
for (MyObject obj : list) {
    if (obj.getId() == maiorId) {
        objetosComMaiorId.add(obj);
    }
}


text:
Q: Add classpath from XML file How to add this XML file to classpath?
command line
# java -classpath . dk.firma.klient.webservice.OiosiRaspClient

.classpath
<?xml version="1.0" encoding="UTF-8"?>
<classpath>
    <classpathentry kind="src" path="src"/>
    <classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER/org.eclipse.jdt.internal.debug.ui.launcher.StandardVMType/JavaSE-1.6"/>
    <classpathentry kind="lib" path="lib/axis2/transport/axis2-transport-base-1.0-SNAPSHOT.jar"/>
    <classpathentry kind="lib" path="lib/axis2/transport/axis2-transport-mail-1.0-SNAPSHOT.jar"/>
    <classpathentry kind="lib" path="lib/axis2/core/axis2-adb-1.5.1.jar"/>
    <classpathentry kind="lib" path="lib/axis2/core/axis2-adb-codegen-1.5.1.jar"/>
    <classpathentry kind="lib" path="lib/axis2/core/axis2-ant-plugin-1.5.1.jar"/>
    <classpathentry kind="lib" path="lib/axis2/core/axis2-clustering-1.5.1.jar"/>
    <classpathentry kind="lib" path="lib/axis2/core/axis2-codegen-1.5.1.jar"/>
    <classpathentry kind="lib" path="lib/axis2/core/axis2-corba-1.5.1.jar"/>
    <classpathentry kind="lib" path="lib/axis2/core/axis2-fastinfoset-1.5.1.jar"/>
    <classpathentry kind="lib" path="lib/axis2/core/axis2-java2wsdl-1.5.1.jar"/>
    <classpathentry kind="lib" path="lib/axis2/core/axis2-jaxbri-1.5.1.jar"/>
    <classpathentry kind="lib" path="lib/axis2/core/axis2-jaxws-1.5.1.jar"/>
    <classpathentry kind="lib" path="lib/axis2/core/axis2-jibx-1.5.1.jar"/>
    <classpathentry kind="lib" path="lib/axis2/core/axis2-json-1.5.1.jar"/>
    <classpathentry kind="lib" path="lib/axis2/core/axis2-kernel-1.5.1.jar"/>
    <classpathentry kind="lib" path="lib/axis2/core/axis2-metadata-1.5.1.jar"/>
    <classpathentry kind="lib" path="lib/axis2/core/axis2-mtompolicy-1.5.1.jar"/>
    <classpathentry kind="lib" path="lib/axis2/core/axis2-spring-1.5.1.jar"/>
    <classpathentry kind="lib" path="lib/axis2/core/axis2-saaj-1.5.1.jar"/>
    <classpathentry kind="lib" path="lib/axis2/core/axis2-transport-http-1.5.1.jar"/>
    <classpathentry kind="lib" path="lib/axis2/core/axis2-transport-local-1.5.1.jar"/>
    <classpathentry kind="lib" path="lib/axis2/core/axis2-xmlbeans-1.5.1.jar"/>
    <classpathentry kind="lib" path="lib/apache_commons/collections/commons-collections-3.2.1.jar"/>
    <classpathentry kind="lib" path="lib/apache_commons/configuration/commons-configuration-1.6.jar"/>
    <classpathentry kind="lib" path="lib/apache_commons/jxpath/commons-jxpath-1.3.jar"/>
    <classpathentry kind="lib" path="lib/apache_commons/lang/commons-lang-2.4.jar"/>
    <classpathentry kind="lib" path="lib/axis2/core/activation-1.1.jar"/>
    <classpathentry kind="lib" path="lib/axis2/core/axiom-api-1.2.8.jar"/>
    <classpathentry kind="lib" path="lib/axis2/core/axiom-dom-1.2.8.jar"/>
    <classpathentry kind="lib" path="lib/axis2/core/axiom-impl-1.2.8.jar"/>
    <classpathentry kind="lib" path="lib/axis2/core/bcel-5.1.jar"/>
    <classpathentry kind="lib" path="lib/axis2/core/commons-codec-1.3.jar"/>
    <classpathentry kind="lib" path="lib/axis2/core/commons-fileupload-1.2.jar"/>
    <classpathentry kind="lib" path="lib/axis2/core/commons-httpclient-3.1.jar"/>
    <classpathentry kind="lib" path="lib/axis2/core/commons-io-1.4.jar"/>
    <classpathentry kind="lib" path="lib/axis2/core/commons-lang-2.3.jar"/>
    <classpathentry kind="lib" path="lib/axis2/core/commons-logging-1.1.1.jar"/>
    <classpathentry kind="lib" path="lib/axis2/core/geronimo-annotation_1.0_spec-1.1.jar"/>
    <classpathentry kind="lib" path="lib/axis2/core/geronimo-jaxws_2.1_spec-1.0.jar"/>
    <classpathentry kind="lib" path="lib/axis2/core/geronimo-stax-api_1.0_spec-1.0.1.jar"/>
    <classpathentry kind="lib" path="lib/axis2/core/geronimo-saaj_1.3_spec-1.0.1.jar"/>
    <classpathentry kind="lib" path="lib/axis2/core/geronimo-ws-metadata_2.0_spec-1.1.2.jar"/>
    <classpathentry kind="lib" path="lib/axis2/core/httpcore-4.0.jar"/>
    <classpathentry kind="lib" path="lib/axis2/core/jalopy-1.5rc3.jar"/>
    <classpathentry kind="lib" path="lib/axis2/core/jaxb-api-2.1.jar"/>
    <classpathentry kind="lib" path="lib/axis2/core/jaxb-impl-2.1.7.jar"/>
    <classpathentry kind="lib" path="lib/axis2/core/XmlSchema-1.4.3.jar"/>
    <classpathentry kind="lib" path="lib/axis2/mercury/mercury-core-0.91.jar"/>
    <classpathentry kind="lib" path="lib/axis2/mercury/mercury-persistence-0.91.jar"/>
    <classpathentry kind="lib" path="lib/axis2/rampart/opensaml-1.1.jar"/>
    <classpathentry kind="lib" path="lib/axis2/rampart/rampart-core-1.4.jar"/>
    <classpathentry kind="lib" path="lib/axis2/rampart/rampart-policy-1.4.jar"/>
    <classpathentry kind="lib" path="lib/axis2/rampart/rampart-trust-1.4.jar"/>
    <classpathentry kind="lib" path="lib/axis2/rampart/wss4j-1.5.4.jar"/>
    <classpathentry kind="lib" path="lib/axis2/rampart/xmlsec-1.4.1.jar"/>
    <classpathentry kind="lib" path="lib/backports/backport-util-concurrent.jar"/>
    <classpathentry kind="lib" path="lib/openuddi/openuddi-client-1.4.jar"/>
    <classpathentry kind="lib" path="lib/axis2/core/jaxb-xjc-2.1.7.jar"/>
    <classpathentry kind="lib" path="lib/axis2/core/jaxen-1.1.1.jar"/>
    <classpathentry kind="lib" path="lib/axis2/core/jettison-1.0-RC2.jar"/>
    <classpathentry kind="lib" path="lib/axis2/core/jibx-bind-1.2.1.jar"/>
    <classpathentry kind="lib" path="lib/axis2/core/jibx-run-1.2.1.jar"/>
    <classpathentry kind="lib" path="lib/axis2/core/log4j-1.2.15.jar"/>
    <classpathentry kind="lib" path="lib/axis2/core/mail-1.4.jar"/>
    <classpathentry kind="lib" path="lib/axis2/core/mex-1.5.1.jar"/>
    <classpathentry kind="lib" path="lib/axis2/core/neethi-2.0.4.jar"/>
    <classpathentry kind="lib" path="lib/axis2/core/smack-3.0.4.jar"/>
    <classpathentry kind="lib" path="lib/axis2/core/smackx-3.0.4.jar"/>
    <classpathentry kind="lib" path="lib/axis2/core/soapmonitor-1.5.1.jar"/>
    <classpathentry kind="lib" path="lib/axis2/core/woden-api-1.0M8.jar"/>
    <classpathentry kind="lib" path="lib/axis2/core/woden-impl-dom-1.0M8.jar"/>
    <classpathentry kind="lib" path="lib/axis2/core/wsdl4j-1.6.2.jar"/>
    <classpathentry kind="lib" path="lib/axis2/core/wstx-asl-3.2.4.jar"/>
    <classpathentry kind="lib" path="lib/axis2/core/xalan-2.7.0.jar"/>
    <classpathentry kind="lib" path="lib/axis2/core/xercesImpl-2.6.2.jar"/>
    <classpathentry kind="lib" path="lib/axis2/core/xml-apis-1.3.02.jar"/>
    <classpathentry kind="lib" path="lib/axis2/core/xmlbeans-2.3.0.jar"/>
    <classpathentry kind="lib" path="lib/axis2/core/xml-resolver-1.2.jar"/>
    <classpathentry kind="lib" path="lib/bouncycastle/bcpkix-jdk15on-147.jar"/>
    <classpathentry kind="lib" path="lib/bouncycastle/bcprov-jdk15on-147.jar"/>
    <classpathentry kind="lib" path="lib/nemhandel/dk.gov.oiosi.library-2.1.0.21718.jar"/>
    <classpathentry kind="output" path="bin"/>
</classpath>

A: You can't do it the way you want. You can't add a .classpath file (generated by eclipse I guess) directly in the command line. You need to use an external tool like ant, maven or gradle for doing the job. Or you can add by hand all the listed dependencies inside the MANIFEST file of your main jar.
Edit : Solution with Ant
1-Open your build.xml file
2-Add Path element :
<path id="dep.runtime">
    <fileset dir="paht/to/external/dependency/dir"    includes="**/*.jar"/>
</path>

A path element is an abstraction use to describe librairies needed for your project. So, it must reflect dependencies kind="lib" of your .classpath file. In your case I give you the beginning of your path and hope that It will help you to understand how it works. If not google is your friend.
<path id="dep.runtime">
        <fileset dir="lib/axis2/core"  includes="**/*.jar"/>
        <fileset dir="lib/axis2/rampart"  includes="**/*.jar"/>
        <fileset dir="lib/axis2/transport"  includes="**/*.jar"/>
        <fileset dir="lib/apache_commons"  includes="**/*.jar"/>
        <fileset dir="lib/axis2/mercury" includes="**/*.jar"/>
        <!--you need to complete this list by inspiring you of those examples -->
</path>

3-Add a Jar element inside a target call "jar" which depends on target responsible to compile your java files.
<target name="jar" depends="compile">

<!-- This element will write inside the manifest file all your dependencies needed to execute your project.-->
    <manifestclasspath property="manifest_cp" jarfile="myProject.jar" maxParentLevels="10">

<!-- This is the reference to your classpath description inside element path -->
        <classpath refid="dep.runtime" />
    </manifestclasspath>

    <jar jarfile="myProject.jar" basedir="./src">
        <manifest>
            <attribute name="Main-Class" value="dk.firma.klient.webservice.OiosiRaspClient"/>
            <attribute name="Class-Path" value="${manifest_cp}"/>
        </manifest>

    </jar>
</target>

4-Launch your build.xml with ant (make sure that ant use the target named "jar"). Normally, if all goes well it has generated a jar called myProject.jar. If you open it with a zip tool, you will see a META-INF/MANIFEST.MF file. Inside it, there is a Class-path line where all your dependencies are listed.
5-Type the command line java -jar myProject.jar
If all goes well, it will launch your program.


text:
Q: Java not providing expected result for a expression I'm trying to implement the following expression s=ut+½at² but it does not give an expected result for u = 2, a = 2, t = 1 => s = 3.00 m
I've tried moving around the parentheses/brackets but it does not fix the problem...
import java.util.Scanner;
public class Exercise4 {
    public static void main(String args[]) {
        float speed, time, acceleration, distance;
        Scanner input = new Scanner(System.in);
        System.out.print("Please enter the initial speed: ");
        speed = input.nextFloat();
        System.out.print("Please enter the acceleration: ");
        time = input.nextFloat();
        System.out.print("Please enter the time spent traveling: ");
        acceleration = input.nextFloat();
        distance = (speed * time) + (((0.5 f * acceleration) * time) * time);
        System.out.println("The object traveled a distance of " + String.format("%.2f", distance) + " metres");
    }
}

Other expected results that do work are :
u = 0, a = 0, t = 0 => s0 .00 m
u = 0, a = 1, t = 1 => s0 .50 m
u = 1, a = 1, t = 1 => s1 .50 m

A: You have messed up the order of your inputs.
You are asking for the value of acceleration, but assigning that input to time variable.
System.out.print("Please enter the acceleration: ");
        time = input.nextFloat();

Just change the order and it would work just fine.
import java.util.Scanner;

public class Exercise4 {
    public static void main(String args[]) {
        float speed, time, acceleration, distance;
        Scanner input = new Scanner(System.in);
        System.out.print("Please enter the initial speed: ");
        speed = input.nextFloat();
        System.out.print("Please enter the acceleration: ");
        acceleration = input.nextFloat();
        System.out.print("Please enter the time spent traveling: ");
        time = input.nextFloat();
        distance = (speed * time) + (((0.5f * acceleration) * time) * time);
        System.out.println("The object traveled a distance of " + String.format("%.2f", distance) + " metres");
    }
}


text:
Q: Saving request data in CakePHP between two actions in controller I have two actions which are like pages in my controller. I two buttons: next and previous too. How can I save my $this->request->data between two action in the same controller ? When i'm pressing previous, i need to have all the data on the previous page, which the user entered not to disappear.

A: If you dont have lots of fields and fields are named uniquely, you could add correspondig values to session when handling form in controller.
$this->Session->write('Form1.field1', $value);

After that, you could fetch saved values from session every time you visit that form page again and use them as default values in form.
$this->set('Form1.field1', $this->Session->read('Form1.field1'));

I must admit, that this is not very handy way doing it, and by my self, I would definetly go with JavaScript instead.


text:
Q: Function satisfying $F(a)-F(1)=F(1)-F(\frac{1}{a})$ What continuous monotone increasing function has the property:
$$F(a)-F(1)=F(1)-F(\frac{1}{a}) \space\space\space\space\space\space \forall a>1 $$
The context for this is that I'm looking for a continuous probability distribution on $(0,\infty)$ satisfying:
$$P\left(1\le x\le a\right) = P\left(\frac{1}{a} \le x \le 1\right)$$

A: Any odd and monotonic increasing function $g(x)$ that has a limit of $\frac12$ when $x\to+\infty$ could work. You define $f(x)=g(\log(x))+\frac12$.
You have the following properties:
$$f(1)=\frac12$$
$$f(1/x) + f(x) = 1$$
$$\lim_{x\to0}f(x)=0$$
$$\lim_{x\to+\infty}f(x)=1$$

A: $$F(a)=\log(a)+C$$
Satisfies for any real $C$.
Using the fundamental theorem of calculus, your equation becomes (I'm assuming a differentiable solution)
$$\int_1^a F'(x)dx=\int_{1/a}^1 F'(x)dx$$
Moving everything to the left and differentiating leads to
$$F'(a)-F'(1/a)1/a^2=0$$
We are then left with the functional equation
$$aF'(a)=F'(1/a)\frac{1}{a}$$
Assume $F'(a)=a^n$ for some $n$. By plugin this into the previous equation we have $n=-1$. So
$$F'(a)=1/a$$
Is a candidate. Integration leads to
$$F(a)=\log(a)+C.$$
Showing that this is an actual solution is simple.


text:
Q: Hibernate image getting truncated while saving I am working on a Spring-MVC application. In this, I am trying to upload an image and save it in database. During that process, I tried to convert the binary data of the image to a String, and I noticed that the images binary data is truncated. Generally, if you take a image of 20-30kb, then in String one can see atleast 500-600 characters, I can only see 6-8. I am showing how I have implemented the image save and display. Kindly let me know what I am doing wrong..
Entity :
@Entity
@Table(name = "product")
public class ProductBasic {

@Column(name = "productimage")
    byte[] productimage;

 public byte[] getProductimage() {
        return productimage;
    }

    public void setProductimage(byte[] productimage) {
        this.productimage = productimage;
    }
}

Product service while saving. :
@Transactional
@Service
public class ProductBasicServiceImpl implements ProductBasicService{
    private ProductBasicDAO productBasicDAO;

    public void setProductBasicDAO(ProductBasicDAO productBasicDAO) { this.productBasicDAO = productBasicDAO; }

    @Override
    @Transactional
    public void addProduct(User user, ProductBasic p){
       p.setProductimage(org.apache.commons.codec.binary.Base64.encodeBase64(p.getProductimage()));
        this.productBasicDAO.addProduct(user, p);
    }
}

Controller for sending image as bytearray :
@RequestMapping(value = "/product/{id}/image")
    public byte[] retrieveimage(@PathVariable("id")Integer id){
        ProductBasic productBasic1 = productBasicService.getProductById(id);
        if(productBasic1.getProductimage()==null){
            System.out.println("product by id image is null");
            return null;
        }else {
            System.out.println("Product by id image is not null");
            byte[] data = org.apache.commons.codec.binary.Base64.decodeBase64(productBasic1.getProductimage());
// When I convert above byte[] to String using String builder and append data:image/png;bas64, I get String as "data:image/png;base64,B[jak23424=="
            return data;
    }
}

JSP :

                <form:label path="productimage">
                    <spring:message text="productimage"/>
                </form:label>

                <form:input type="file" path="productimage" />

Product List

<c:if test="${!empty listProducts}">

            Product ID
            Product image
            Product name
            Product description
            Product condition
            Product age
            Product EAN
            Product ISBN
            Product ordernumber
            Product owners id

            Edit
            Delete

        <c:forEach items="${listProducts}" var="product">

                ${product.productid}
                ${product.productimage}
                ${product.productname}
                ${product.productdescription}
                ${product.productcondition}
                ${product.productage}
                ${product.productean}
                ${product.productisbn}
                ${product.ordernumber}
                ${product.user1id}
                <%----%>

                <a href="<c:url value='/editproduct/${product.productid}' />" >Edit Product
                <a href="<c:url value='/removeproduct/${product.productid}' />" >Delete Product

            <%----%>
        </c:forEach>

</c:if>

Also, when I use the below function in ServiceImpl, the saved image is just 10bytes instead of 80Kb, which is the actual image size.
 @Override
    @Transactional
    public void addProduct(User user, ProductBasic p){

        try {

            FileOutputStream imageoutfile = new FileOutputStream("/home/akshay/check.png");
            imageoutfile.write(p.getProductimage());
            imageoutfile.close();
            File file = new File("/home/akshay/check.png");
            FileInputStream fileInputStream = new FileInputStream(file);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
      p.setProductimage(org.apache.commons.codec.binary.Base64.encodeBase64(p.getProductimage()));
        this.productBasicDAO.addProduct(user, p);
    }

Any pointers would be nice. i am using PostgreSQL 9.3, and in database i am saving it as bytea.


text:
Q: PL/SQL Trigger: Facing bad bind variable error I have tried everything but nothing can solve this.PLS-00049: bad bind variable 'NEW.BLOODBANKID' keep appearing. Please help me.
CREATE OR REPLACE TRIGGER count_stock
AFTER INSERT OR UPDATE ON blood
FOR EACH ROW
DECLARE
  v_countblood NUMBER;
BEGIN
  SELECT COUNT(bloodid) INTO v_countblood
  FROM blood
  WHERE bloodbankid = :NEW.bloodbankid
  AND bloodtype = :NEW.bloodtype;

  IF v_countblood < 0 THEN
    RAISE_APPLICATION_ERROR(-20201,'There is no blood');
  END IF;
END;

A: The error indicates that there is no column "BLOODBANKID" in the table "BLOOD".
Either it doesn't exist at all in the table or you used double quotes on the column in your CREATE TABLE statement, thus making the column case sensitive.
If for instance your CREATE TABLE statement looks like this:
create table blood("bloodbankid" number(18), ...);

Then there is a column "bloodbankid" in the table, but no column "BLOODBANKID".
When we access a row without quotes as in
select BLOODBANKID from blood where BloodBankId = 123;

then Oracle converts this internally into "BLOODBANKID". As the same applies to CREATE TABLE, the column names usually match. If you used quotes in the CREATE TABLE statement, however, then you must use the same upper/lower case with quotes in every statement:
select "bloodbankid" from blood where "bloodbankid" = 123;

So, if this is the case, I'd recommend you re-create the table with case insensitive columns.
(Apart from this your trigger doesn't make sense anyway, as has already been mentioned in the request comments.)


text:
Q: IPhone - Not getting Interface Orientation I'm trying to set another position for a UIButton when I change the orientation of my IPhone and I had the idea to implement it inside BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation.
Is this the right way to implement or is there any error on my code? It's not printing these logs.
Code:
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {

if ((interfaceOrientation == UIDeviceOrientationLandscapeLeft) ||
    (interfaceOrientation == UIDeviceOrientationLandscapeRight))
{
    NSLog(@"Csantos shouldAutorotateToInterfaceOrientation: left or right");
    [adButton setFrame:CGRectMake(100, 700, 768, 90)];
}
if ((interfaceOrientation == UIDeviceOrientationPortrait) ||
    (interfaceOrientation == UIDeviceOrientationPortraitUpsideDown))
{
    NSLog(@"Csantos shouldAutorotateToInterfaceOrientation: Portrait or UpsideDown portrait");
    [adButton setFrame:CGRectMake(0, 0, 768, 90)];
}
return YES;

}
Regards!

A: shouldAutorotateToInterfaceOrientation simply specifies what rotations are supported by a UIViewController - nothing more.
You may consider modifying willRotateToInterfaceOrientation which is called just before a rotation is about to begin - to hide background views or other objects, for example.
Then, override didRotateFromInterfaceOrientation which is called after a rotation has just finished - I think this one will be the most important for your setFrame: code.

A: Your code too should work but try putting following code. Change is from UIDeviceOrientation to UIInterfaceOrientation
-(BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    if ((interfaceOrientation == UIInterfaceOrientationLandscapeLeft) || (interfaceOrientation == UIInterfaceOrientationLandscapeRight))
    {
        NSLog(@"Csantos shouldAutorotateToInterfaceOrientation: left or right");
        [adButton setFrame:CGRectMake(100, 700, 768, 90)];
    }
    if ((interfaceOrientation == UIInterfaceOrientationPortrait) || (interfaceOrientation == UIInterfaceOrientationPortraitUpsideDown))
    {
        NSLog(@"Csantos shouldAutorotateToInterfaceOrientation: Portrait or UpsideDown portrait");
        [adButton setFrame:CGRectMake(0, 0, 768, 90)];
    }
    return YES;
}

A: I don't undestand, the adButton setFrame works correctly or not and this viewcontroller is root or you have another one. Can't it be that root controller shouldAutorotateToInterfaceOrientation return NO for any orientation?


text:
Q: column names per row top 3 dataframe R Let us say we have the following data frame in R:
DF <- as.data.frame.matrix(matrix(sample(1:15,15),ncol=5,nrow=3))

   V1  V2 V3 V4 V5
1  15   8  3 14  4
2  11   2  5 13  6
3   9   7 10 12  1

I'm trying to retrieve the column name of the top three values per row. I would like to get a new data frame with the following information:
1 V1 V4 V2
2 V4 V1 V5
3 V4 V3 V1

I tried by using apply and dapply but it is not working. I designed a function to use in apply but it is not working as expected. Could you give me any hint to tackle this. I think this should be of help.

A: We can loop through the rows  (apply with MARGIN=1), get the numeric index of the elements in the row decreasingly with order, use that to order the column names, get the first 3 elements with head, transpose the output and convert to data.frame.
 as.data.frame(t(apply(DF, 1, function(x)
   head(names(DF)[order(-x)],3))), stringsAsFactors=FALSE)
#  V1 V2 V3
#1 V1 V4 V2
#2 V4 V1 V5
#3 V4 V3 V1


text:
Q: Laravel - kill session and cookie from console command? Is there any way, within a Laravel console command, to clear the session and/or the remember me cookie?
The console command is designed to deactivate users, and so if a user is deactivated while they are logged in, I want them to automatically be logged out.
But I'm not sure this is possible.  Ideas?

A: Instead of that why don't you try this approach? https://laracasts.com/discuss/channels/laravel/middleware-where-user-status-is-not-active?page=1
basicly, have a middleware that checks if the current user is active, in case it is not, redirect him to login

A: Following process may help you. You can create command of following process.
You need to delete session files from "sessions" folder.
Normally Laravel stores sessions in "storage\framework\sessions" folder.
If you delete all files from session folder , all active user will automatically logged out.
You can find out session file using id from session folder and delete those files who are deactivated.
==========================================================
I had worked to prepare the solution
update config/filesystems.php file as following.
 'disks' => [
        'local' => [
            'driver' => 'local',
            'root' => storage_path('app'),
        ],
        'adminfile' => [
            'driver' => 'local',
            'root' => storage_path('framework'),
        ],

Then you can use following code to delete the session file for particular user.
In my case , session element stored in "login_web_59ba36addc2b2f9401580f014c7f58ea4e30989d" , so I have used "if(preg_match('/login_web_(.)/i',$key))*" in below code
    $files = Storage::disk('adminfile')->allFiles("sessions");
    $users = user::where('is_deactivate',true);
    foreach($users as $user){
    foreach($files as $file){
      if($file!="sessions/.gitignore" and          Storage::disk('adminfile')->exists($file)){
        $contents = unserialize(Storage::disk('adminfile')->get($file));
        foreach($contents as $key=>$value){
         if(!is_array($value) and !is_object($value)){
           if(preg_match('/login\_web\_(.*)/i',$key))
            {
             if($value==$user->id){
                Storage::disk('adminfile')->delete($file);
             }
            }
          }
        }
     }
    }
}


text:
Q: Creating functions in sqlplus I am creating a function in oracle sql plus, that take empno as argument and returns its salary. But its not being created, where am I going wrong?
Here is my function:
CREATE FUNCTION GETEMPSALARY (EMPNUMBER IN INTEGER) RETURN INTEGER
IS
EMPSALARY INTEGER;
BEGIN
SELECT SAL INTO EMPSALARY FROM EMP WHERE EMP.EMPNO = EMPNUMBER;
RETURN EMPSALARY;
END GETEMPSALARY;

Here is the error:
Error at line 1: PLS-00103: Encountered the symbol "(" when expecting one of the following:

   . @ % ; is authid as cluster order using external character
   deterministic parallel_enable pipelined aggregate
   result_cache

1. CREATE FUNCTION GETNAMES1 (EMPID IN INTEGER) RETURN VARCHAR(20)
2. IS
3. EMPNAME VARCHAR(50);

A: your missing the / at the end.
CREATE FUNCTION GETEMPSALARY (EMPNUMBER IN INTEGER) RETURN INTEGER
IS
DECLARE
EMPSALARY INTEGER;
BEGIN
SELECT SAL INTO EMPSALARY FROM EMP WHERE EMP.EMPNO = EMPNUMBER;
RETURN EMPSALARY;
END GETEMPSALARY;
/

edit:
due to your new error which is on a totally different function!
CREATE FUNCTION GETNAMES1 (EMPID IN INTEGER) RETURN VARCHAR(20)

you shouldnt specifiy a precision on returns, so put
 RETURN VARCHAR2

also dont use VARCHAR, only VARCHAR2
and for statement ignored;
SQL> CREATE FUNCTION GETEMPSALARY (EMPNUMBER IN INTEGER) RETURN INTEGER
  2  IS
  3  EMPSALARY INTEGER;
  4  BEGIN
  5  SELECT SAL INTO EMPSALARY FROM EMP WHERE EMP.EMPNO = EMPNUMBER;
  6  RETURN EMPSALARY;
  7  END GETEMPSALARY;
  8  /

Warning: Function created with compilation errors.

SQL> show errors
Errors for FUNCTION GETEMPSALARY:

LINE/COL ERROR
-------- -----------------------------------------------------------------
5/1      PL/SQL: SQL Statement ignored
5/32     PL/SQL: ORA-00942: table or view does not exist
SQL>

what is the subsequent error you see, as this error should be followed by a real error


text:
Q: how to load a folder given just a ServerRelativeUrl using Microsoft.SharePoint.Client In my application I have a url of a folder as retrieved by folder.ServerRelativeUrl() eg. /consulting/TeamSiteTemplate/Documents/
Now I want to get a list of folders inside this folder. I use this code:
using (ClientContext clientContext = new ClientContext(siteUrl))
{
   folder = clientContext.Web.GetFolderByServerRelativeUrl(folder.ServerRelativeUrl);
   clientContext.Load(folder);
   clientContext.Load(folder.Folders);
   clientContext.ExecuteQuery();

   foreach (Folder childFolder in folder.Folders)
   {
      // process folder
   }
}

This only seems to work when siteUrl contains the site eg. http://sharepoint/consulting/TeamSiteTemplate - but what if I don't know the site name of the given url? Or don't know if it has a subsite, etc.
So simply:
How can I get a site/subsite part from a relative url - or just the site if no subsite?
or: Is there another way to do this?

A: Assuming you wait for SP.js to load (which seems safe since your using CSOM), you should have a global variable named "L_Menu_BaseUrl" which will be the absolute url to the current site.
Between this, the folder's server relative url, and a little logic, you should be able to get what you need.


text:
Q: Let $X,Y$ independent random variables such that $X\sim\text{Poisson}(\lambda)$, and $Y\sim\text{Poisson}(\mu)$. Let $X,Y$ independent random variables such that $X\sim\operatorname{Poisson}(\lambda)$, and
$Y\sim \operatorname{Poisson}(\mu)$. Let $Z=X+Y$ find the probability function of $X$ and $Z$.
Using the idea of the user @Surb. i have:
$\mathbb P\{X=k,Z=m\}=\mathbb P\{X=k, X+Y=m\}=\mathbb P\{X=k, Y=m-k\}=P(X=k)P(Y=m-k)=e^{-\lambda}\frac{\lambda^k}{k!}e^{-\mu}\frac{\mu^{m-k}}{(m-k)!}=e^{-(\lambda +\mu)}\frac{\lambda^k \mu^{m-k}}{k!(m-k)!}$
Then the probability function of $Z$ is
$p(m,k)=\begin{cases}
e^{-(\lambda +\mu)}\frac{\lambda^k \mu^{m-k}}{k!(m-k)!} && \text{if}& m\leq k \\
0 && \text{if} & m>k
\end{cases}$

A: Hint
Let $m,k\in\mathbb N$ s.t. $m\geq k$. Then
$$\mathbb P\{X=k,Z=m\}=\mathbb P\{X=k, X+Y=m\}=\mathbb P\{X=k, Y=m-k\}=...$$
I let you conclude when $m<k$.

A: Since the approach using $P(Z=n)=\sum_{k=0}^n P(X=k)P(Y=n-k)$ has already been covered, I'll discuss a different one that requires less combinatorics. Define $$G_X(t):=\mathbb{E}t^X=\sum_{k\ge 0}e^{-\lambda}\frac{(\lambda t)^k}{k!}=e^{\lambda (t-1)}.$$This power series has $t^k$ coefficient $P(X=k)$, so is called a probability generating function. Clearly, $G_Z=\mathbb{E}t^X t^Y=G_X G_Y=e^{(\lambda+\mu)(t-1)}$, i.e. $Z$ is Poisson-distributed with parameter $\lambda+\mu$.


text:
Q: Migrating from external source to AD I'm not even sure where to start so any info would be helpful.
My organization uses AD for authentication... and that's about it. All users are stored in a single OU and then under a group OU when appropriate and all under one domain. We don't use AD to track/store phone numbers, ext., dept., directors, etc. However, we have started using OTRS as our ticketing system and if you're familiar with it, it integrates nicely with AD to provide the ticket requester's info such as phone, ext., email, etc. Well, we keep all of that information in a third party system. Specifically, a product called inteli-desk.
I'm a dba guy not an AD guy (just enough to cause damage) so my question is: Is there a way/tool or something to migrate the information from the SQL Server db that inteli-desk uses and populate it in AD?

A: Powershell "speaks" CSV, the hardest part will be mapping the data from the SQL to the appropriate attributes in Active Directory. Check out this link Make sure you read the comments, the script listed there has a typo.
Depending on the version of AD & your powershell version some of this may already be done for you.


text:
Q: How to convert userscript to Firefox add-on I'm trying to convert usescript to Firefox addon but it's not working (It works with all modern browsers except Firefox). I tried https://arantius.com/misc/greasemonkey/script-compiler.php it converts userscript and its working but add-on fails at validation and I can't submit it at Firefox add-on catalog.
Here is my code http://pastebin.com/mxnBqDxS
Is there easy way to create Firefox add-on whit this script that won't fail at validation?

A: According to your comment the extension wasn't rejected by the automatic validation (that always produces many warnings that have no real implications) but rather by the human reviewer. The reviewer considered the following line in your script to be unsafe:
button.innerHTML = wrapper.text;

The reviewer is wrong however and you should reply to the mail (your reply will be sent to amo-editors mailing list) pointing out that:

*

*wrapper.text isn't some text that is provided by the web page or the user. It is rather something that is hardcoded in your extension, its possible values are known in advance and sanitization is unnecessary.

*Even if wrapper.text were some text that you got from the web page - button is being inserted as an element of that very web page. This means that any JavaScript code that executes because of improper sanitization executes with the privileges of the web page. The web page doesn't get any more privileges than it already has.
So while innerHTML is a common source of security issues, in this case it isn't.


text:
Q: Compress image in android (b4a) I'm using this java code to compress an image in basic4android! However, nothing works!
#if java
import android.graphics.Bitmap;
import java.io.*;
import android.os.Environment;
public void Resize(Bitmap mPhoto)
{
    try
    {
        ByteArrayOutputStream bytes = new ByteArrayOutputStream();
        mPhoto.compress(Bitmap.CompressFormat.PNG, 50, bytes);

        File file = new File(Environment.getExternalStorageDirectory()+"/"+"11111.jpg");
        file.createNewFile();
        FileOutputStream fo = new FileOutputStream(file);
        fo.write(bytes.toByteArray());
        fo.close();
    }
    catch (Exception e) {}
}
#end if

No file is shown under ExternalStorageDirectory.

A: Try first to create a directory in the root directory and then write the file in it like this for example:
File sdcard = Environment.getExternalStorageDirectory();
File dir = new File(sdcard.getAbsolutePath() + "/your-dir-name/");
dir.mkdir();
File file = new File(dir, "11111.jpg");
FileOutputStream os = outStream = new FileOutputStream(file);
os.write(bytes.toByteArray());
os.close();

And please do not forget to add this permission to your AndroidManifest-file
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />


text:
Q: Write unit test for object.GetType().InvokeMember I have method with uses object.GetType().InvokeMember():
private void InvokeComObject(object callback, object parameter)
        {
            callback.GetType().InvokeMember(
                                name: "[DispID=0]",
                                invokeAttr: BindingFlags.Instance | BindingFlags.InvokeMethod,
                                binder: null,
                                target: callback,
                                args: new Object[] { parameter == null ? "" : parameter });
        }

and a unit test for it:
[Test]
public void should_execute_action()
{
    var executor = CreateExecutor();

    Action<int> callback = Substitute.For<Action<int>>();

    executor.ExecuteAction("name", "value", callback);

    callback.Received(1).GetType().InvokeMember(Arg.Is<string>(r => r == "[DispID=0]"),
        Arg.Is<BindingFlags>(r => r.HasFlag(BindingFlags.Instance) && r.HasFlag(BindingFlags.InvokeMethod)),
        Arg.Is<Binder>(r => r == null), Arg.Is<object>(r => ReferenceEquals(r, callback)),
        Arg.Is<Object[]>(r => r == new Object[] { 2 }));
}

executor.ExecuteAction inside executes InvokeComObject with "callback" which I passed to this method. This methods fails with exception on "callback.Received(1).GetType().InvokeMember":
"System.ArgumentException: Must specify binding flags describing the invoke operation required (BindingFlags.InvokeMethod CreateInstance GetField SetField GetProperty SetProperty)."
How can I make this test work?


text:
Q: What is the best graph editor to use in your articles? Here is the criteria for a "perfect" graph editor:

*

*it should be able to perform an automated, but controllable layout

*one is able to make "manual" enforcements to nodes and edges locations when you need it (or at least such fine automated layout so you don't need "manual" enforcements)

*one could add some math symbols and formulae on a graph

Common vector graphics editors could do the trick, but there is a lot of overhead efforts to draw every node, every edge, every label.
Graphviz is good enough, but sometimes you cannot get needed layout (even if you use several tricks like additional invisible nodes etc) and you should use ladot or dot2tex for math formulae
yEd has nice layouts, but there is a problem with a math text.
This is probably not a math question, but it is common to draw graphs in articles i think.
Result graph
(Update: 27.12.2010)
Here is another candidate for the best editor in TeX - Asymptote (asymptote.sf.net).
The very powerful tool at first glance.
(Update: 28.04.2014)
The very tasty semiautomated tool to use with PGF/TiKZ is TiKZEdt. You can extend its palette with your own tools and make the process of diagram creation very simple!

A: Graphviz is extremely powerful and I'd be surprised to discover that it doesn't do what you need.  It only generates the positions of nodes that aren't already specified so if you need fine tuning then you can run it to get a basic graph, then fine tune it, and then it'll respect your fine tuning.  Also, it comes with an interactive program called dotty which can be used to alter the graphs visually.
One should also distinguish between generating graphs and rendering them.  I use graphviz to generate graphs, but don't use it for rendering.  For that, if PGF/TikZ can't do it then I'm not interested!  PGF/TikZ is absolutely fantastic and has consigned xy.sty, xfig, and all the other stuff that I used to use to the rubbish bin [trash can].  Even for commutative diagrams in category theory!

A: For adding math symbols I use lpic --- this way you use LaTeX to  write over picture,so you can add ALL math symbols NOT just some. BONUS: if you change notation, you do not have to redo picture.
For drawing I often use some geogebra or kig. This soft is mostly designed for compass and straightedge constructions, but I use it as an advanced vector-graphic editor --- it is flexible enough to make virtually any math drawing.

A: I personnally mostly use xfig, and start moving to inkscape. However I guess that they are not what you want. A friend of mine, working on graphs, uses metapost with great results. Last, for 3D images, I use povray which is very efficient with geometric forms. It renders natively in .png, so the best is to compile with pdflatex. You can find mathematical picture rendered with povray on my web page: http://www-fourier.ujf-grenoble.fr/~bkloeckn/images.html

A: I already had about 30 pages of graphs typeset with xymatrix for my thesis before discovering tikz; but was so impressed by it that I was happy to rewrite them all. As well as (imho) looking better, it gave me cross-platform compatibility - xypic seems to need pstricks, so on the mac with TeXshop (which uses pdflatex, I assume) the old graphs couldn't even be rendered.
Its ability to construct graphs iteratively can also be a massive timesaver- for instance, I wanted a bunch of otherwise identical rectangles at various positions, so with tikz could just loop over a list of their first coordinate rather than having to tediously cut,paste and modify an appropriate number of copies of the command for a rectangle. Particularly handy when I then decided they all needed to be slightly wider!
There's a gallery of tikz examples here, to give you some idea of what it's capable of (and with the relevant source code- I did find the manual a bit hard to understand and learnt mostly by examples or trial and error).
The vector graphics package inkscape (which I used to use for drawing more complicated graphs for inclusion as eps images) also apparently has a plugin to export as tikz, although I haven't tried that out.

A: For something quick (and not necessarily dirty) you can use XFig — TeX symbols are allowed, and there's quite a lot you can do (it's quite impressive how powerful this 'oldie' can be ;-).
For something more elaborate, i'd say PGF and TikZ — this is a very powerful tool, and you can virtually do whatever you want with it.
For some sort of "middle ground" approach, you can maybe try Xy-pic — this is not as old as XFig and not as new as PGF/TikZ; and used to be the standard way to go for graphs. ;-)
Hope this helps.


text:
Q: How can one decide between structure or coincidence regarding the fine structure constant? This question originates the following observations about the fine structure constant, $\alpha$.
Measurements of $\alpha^{-1}$ yield values slightly smaller than $137.036$, and a good rational fit for all of them is $\frac{34259}{250}$. The choice of $250$ does not seem to be decimally biased, because one can multiply any value close to $137.035999$ for all integers up to say $300$ and $250$ emerges as a proper denominator more clearly than $113$ for $\pi$.
One of the alternative approximate expressions for $\alpha^{-1}$ is $$5^3+\frac{5^2}{2}-\frac{1}{2}+5^{-2}-\frac{5^{-3}}{2}$$ After some easy manipulation, this can be written as $$\frac{1}{2^3}(10^3+2^3·3(1+\frac{3}{10^3}))$$
I would like to learn how to decide between structure or coincidence, based on data. For instance, how should one compare the complexities of the approximate value of the constant ($137.036$) and the above expression that suggests some internal structure?
An equivalent way to see $137$ (only the integer part of $\alpha^{-1}$) is the following image, corresponding to the polynomial $(4n+1)^3+3(2n)^2$ at $n=1$, or $(2n+1)^3+3n^2$ at $n=2$.

I would classify this as a figurate number, as it is the sum of related (by $n$) figurate numbers (even squares and related cubes). But how can the structureness of this representation be evaluated?

Working with spheres instead of cubes, the correction $.036$ may be obtained from the normalized volume of a sphere of radius $5$ with $24·5^6$ spheres of radius $\frac{1}{25}$ centered on its surface, according to the following volume integral
$$\frac{4}{3}\alpha^{-1} \approx  \frac{4}{3}\times137.036 = \int_{-10}^{0} (5^2 - (x + 5)^2) dx $$
$$+ 24·5^6 \left( \int_{-\frac{1}{10·25^2}}^{\frac{1}{25}} \left(\frac{1}{25^2} - x^2\right) dx - \int_{-\frac{1}{10·25^2}}^{0} \left(5^2 - (x + 5)^2\right) dx\right)$$


text:
Q: Creating a NSTextView programmatically? I'm can't seem to build a working NSTextView programmatically. Starting from a new project template I have this code (mostly coming from Apple's "Text System User Interface Layer Programming Guide"):
- (void)applicationDidFinishLaunching:(NSNotification *)aNotification {
    NSString *string = @"Here's to the ones who see things different.";
    NSTextStorage *textStorage = [[NSTextStorage alloc] initWithString:string];
    NSLayoutManager *layoutManager = [[NSLayoutManager alloc] init];
    [textStorage addLayoutManager:layoutManager];

    NSTextContainer *textContainer = [[NSTextContainer alloc] initWithContainerSize:NSMakeSize(300, 300)];
    [layoutManager addTextContainer:textContainer];

    NSTextView *textView = [[NSTextView alloc] initWithFrame:NSMakeRect(50, 50, 300, 300)
                                               textContainer:textContainer];

    [textContainer setWidthTracksTextView:YES];
    [textView setVerticallyResizable:YES];
    [textView setHorizontallyResizable:NO];
    [textView setAutoresizingMask:NSViewWidthSizable];

    [[self.window contentView] addSubview:textView];
}

Running the app, a window opens with a white square in it that's supposed to be the NSTextView, but there's no text, and there's no way to interact with the text view. Moreover, I tried adding text to the text view in code after the view is created using [textView setString:@"Some string."], but that doesn't work either. (Incidentally, I've also tried putting it in a NSScrollView first, in case that somehow was the issue, but that didn't help.)
I can't for the life of me figure out what the problem is. What am I missing?

A: This should work, although I tried it out myself and was unable to edit too. It could possibly be a bug now, but I'm not 100% sure. If you need to use the containers and layout managers just use the one that comes from the initWithFrame: method (without the text container).
NSTextView *textView = [[NSTextView alloc] initWithFrame:NSMakeRect(50, 50, 300, 300)];
NSLayoutManager *layoutManager = textView.layoutManager;
NSTextContainer *textContainer = textView.textContainer;
NSTextStorage *textStorage = textView.textStorage;

//Do your edits here

A: To expand on TheAmateurProgrammer's answer:

If you need to use the containers and layout managers just use the one that comes from the initWithFrame: method (without the text container)

With iOS, needed to create the text storage, layout manager, and text container for UITextView to work as intended. For NSTextView to function, needed to not create those. Had same results as OP until this change--the view was located accurately, but didn't display text or show insertion point or invoke delegate methods--and then the text view worked properly.


text:
Q: An unhandled exception was thrown by the application I've created my new site using DjANGO
AT FIRST Everything is okay startapp,syncdb......Etc
but the problems its this massage
Unhandled Exception
An unhandled exception was thrown by the application.
you can see
http://www.daqiqten.com/
this is my index.fsgi and .htacces
index.fcgi
#!/usr/bin/python
import sys, os

# Add a custom Python path. (optional)
sys.path.insert(0, "/home/daq")

# Switch to the directory of your project.
os.chdir("/home/daq/newproject")

# Set the DJANGO_SETTINGS_MODULE environment variable.
os.environ['DJANGO_SETTINGS_MODULE'] = "newproject.settings"

from django.core.servers.fastcgi import runfastcgi
runfastcgi(method="threaded", daemonize="false")

___________

.htacces
AddHandler fcgid-script .fcgi
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(.*)$ index.fcgi/$1 [QSA,L]

A: Do you have 'DEBUG' turned on in your app's settings? Maybe you will get some more information about the Exception that was raised.


text:
Q: Change Textview's Text Upon Change of ComboBoxText Selection - Gtk+ 3.0 in C I am building a GUI program that allows users to choose between a few software profiles for them to get written to their USB drive. I have chosen GTK+ 3.0 in C, and my supervisor is aware of my chosen method, so I am not changing it.
What I am trying to do is really quite simple but I'm still having trouble finding a comprehensive answer.
I want to be able to allow the user to select a (text) entry in the combo box and have the corresponding description show up in the frame/textview. The description in the textview should change properly to be the description for that combo box entry (the one selected).
My UI is mostly contained within a Glade file. Currently, the UI is functional but changing between combo box entries does nothing to the textview.
EDIT: I removed the posting of my code because it's too long and maybe it was throwing people off. Apologies. I can post things at request. Thanks.


text:
Q: How to use strange characters in a query string I am using silverlight / ASP .NET and C#. What if I want to do this from silverlight for instance,
// I have left out the quotes to show you literally what the characters
// are that I want to use
string password = vtakyoj#"5
string encodedPassword = HttpUtility.UrlEncode(encryptedPassword, Encoding.UTF8);
// encoded password now = vtakyoj%23%225

URI uri = new URI("http://www.url.com/page.aspx@password=vtakyoj%23%225");

HttpPage.Window.Navigate(uri);

If I debug and look at the value of uri it shows up as this (we are still inside the silverlight app),
http://www.url.com?password=vtakyoj%23"5
So the %22 has become a quote for some reason.
If I then debug inside the page.aspx code (which of course is ASP .NET) the value of Request["password"] is actually this,
vtakyoj#"5
Which is the original value. How does that work? I would have thought that I would have to go,
HttpUtility.UrlDecode(Request["password"], Encoding.UTF8)

To get the original value.
Hope this makes sense?
Thanks.

A: First lets start with the UTF8 business.  Esentially in this case there isn't any.  When a string contains characters with in the standard ASCII character range (as your password does) a UTF8 encoding of that string is identical to a single byte ASCII string.
You start with this:-

vtakyoj#"5

The HttpUtility.UrlEncode somewhat aggressively encodes it to:-

vtakyoj%23%225

Its encoded the # and " however only # has special meaning in a URL. Hence when you view string value of the Uri object in Silverlight you see:-

vtakyoj%23"5

Edit (answering supplementary questions)

How does it know to decode it?

All data in a url must be properly encoded thats part of its being valid Url.  Hence the webserver can rightly assume that all data in the query string has been appropriately encoded.

What if I had a real string which had %23 in it?

The correct encoding for "%23" would be "%3723" where %37 is %

Is that a documented feature of Request["Password"] that it decodes it?

Well I dunno, you'd have check the documentation I guess.  BTW use Request.QueryString["Password"] the presence of this same indexer directly on Request was for the convenience of porting classic ASP to .NET.  It doesn't make any real difference but its better for clarity since its easier to make the distinction between QueryString values and Form values.

if I don't use UFT8 the characters are being filtered out.

Aare you sure that non-ASCII characters may be present in the password?  Can you provide an example you current example does not need encoding with UTF-8?

A: If Request["password"] is to work, you need "http://url.com?password=" + HttpUtility.UrlEncode("abc%$^#@"). I.e. you need ? to separate the hostname.
Also the @ syntax is username:password@hostname, but it has been disabled in IE7 and above IIRC.


text:
Q: How to enable live reload on webpack only for some type of files I have been struggling for over two days to come up with the perfect setup for webpack when using express and EJS.
This is where I am at at the moment:
https://github.com/ZeldOcarina/webpack-express-ejs-setup
Right now I have HMR enabled for SCSS and front-end JS changes.
The last thing I need to add is live reload on views/ejs changes. It works if I change liveReload to true on webpack.dev.js but then HMR breaks as everything reloads.
I can't find a way to reload only for EJS file changes.
Does anyone have any suggestions?
Thank you!

A: I've made it guys!
The way is to use chokidar directly in the before devServer hook:
    devServer: {
        contentBase: "./src/",
        before(app, server) {
          chokidar.watch("./views").on(
            "all",
            debounce(function () {
              console.log("THIS IS HAPPENING!!!!!!");
              server.sockWrite(server.sockets, "content-changed");
            })
          );
        },
[...rest of devServer configuration]

debounce is a lodash function. To check the full configuration please refer to the GitHub repo in the question, I'll leave that open! :)


text:
Q: Custom price calculation in Woocommerce product page I want to do a simple calculation based-on the price of each product and show it on Woocommerce product page. I need to add a code as snippet or directly in the product page template. But I am not a programmer.
How can I get the products price and do a very simple calculation like divide by 12 + 200 and then show it under the price as a finance option.
The new price is just an information and no need to have the option to be added the cart. I want to make it simple.
Your help is much appreciated.


text:
Q: Run Windows Explorer on remote system from its cygwin shell through SSH Please consider my problem :)
1) I Have a Windows 7 - x64 system with cygwin installed and SSHD running.
2) From another Windows machine , from futty, SSH to the above machine.
3) Command "TaskKill /IM explorer.exe /F" to kill explorer. Success!
4) Command "/cygdrive/c/Windows/sysnative/cmd.exe /c start /B explorer.exe" to start explorer. Failed!!
From task manager I can see that the explorer process is running, but no visible "proof" for it. No icons , No task bar.
5) (optional) Command "ps -W | grep explorer | cut -c 31-36 | paste -s -d," to see running explorer process Id from cygwin shell itself.
After searching google and StackOverFlow, the command mentioned in step 4 worked manually on direct cygwin shell on target system.
Primary:: My question here is, is there any command to replace in Step 4, so that we have a "neat" Windows Explorer process up and running ?!
Secondary:: My aim is to remotely kill and start windows explorer properly, Any methods for doing it ?! (Ofcourse, through cygwin - direct (most preferred), power shell or cmd commands )
Advanced Thanks!
- Rx3 -

A: no.  There is no way to run remote windows applications over ssh. There is no protocol that would support that (unlike on Linux, where is still the ancient X11). If you want to play with Windows windows, use RDP or how is that thing called.
Even if you are not interested in the actual window, the cygwin is running in different session (I hope windows has also such concept) to the actual desktop so running applications across the sessions is also not a good idea.
I would just kill it and rely that it will get started automatically again.


text:
Q: On other pc java.sql.SQLException: No suitable driver found for jdbc:sqlserver I wrote an app and it works fine by me. But on other pc-s it throws an exception.

java.sql.SQLException: No suitable driver found for jdbc:sqlserver

I give it (only the app.jar file) to my college, and he gets this error. I give him a jdbcdriver.jar file and, nothing changed.
However I use jre7, I added a line to the code:
    Class.forName("com.mysql.jdbc.Driver");

And than he gets another exception:

Error: java.lang.ClassNotFoundException: com.mysql.jdbc.Driver

What can I do to run this app properly on other pc-s?

A: Put the jar file, containing the MySql Driver on the classpath when starting your application.
The switch is called -cp or -classpath like this:
java -cp ".;mysql.jar" my.package.Main

assuming you start your application from the root directory which is named my.package.Main. The classpath separator is the one for Windows. For unix based OSs you need to use : i guess.


text:
Q: Serial block doesn't work with simulink coder I receive some data signals from Serial Port using Serial Receive block (and Serial Configuration block of course). I use it to move a marker in a video. It works during simulation but when I generate .exe file using Simulink Coder marker doesn't move during execution. It would seem that it does not receive data from serial.
*EDIT:*The original data is an int16 but the "source" is built on Arduino Mega2560 using Target Support Package and so using an Arduino serial send block it generates the source on USB COM port with a baud rate of 9600. Because Arduino serial block wants only uint8 I used a byte pack block before Arduino Serial block. The parameters of byte pack block are:
1)Input port data types = {'int16'}
2)Byte Alignment = 2
In model that receives I use Serial Receive block from instrument control toolbox with:
(Serial Configuration Block:)
Baud Rate = 9600;
Data Bits = 8;
Stop Bits = 1;
Byte Order  = LittleEndian;
Flow Control = none;
Time Out = 10;
Header = none;
Terminator = none;
Data size = [2 1];
Data Type = uint8;
Enable blocking mode = flag;
Action when data is unavailable = output last received value;
Block sample time = (same sample time setted in the model built on Arduino)
I have connected this Serial Receive Block to a Byte Unpack block with:
Output dimensions = {[1]};
Output Port Data types = {'int16'} (data type of original signal)

Suggestions?


text:
Q: Laplace transform of $u(x,t)\sin{x}$ I am trying to work out what the Laplace transform of $u(x,t)\sin{x}$ is.
I have worked it out as $L(u(x,t)\sin{x})=U(x,s)\sin{x}$, where $L(u(x,t))=U(x,s)$, using definition:
$$\int_0^{\infty} e^{-st}f(x)dt$$
In one of the comments on Solving $u_{t}+u_{xxx} = u\sin{x}$ using Laplace transforms , in a comment it is indicated that the Laplace transform of $u(x)\sin{x}$ is not $U(s)\sin{x}$.


text:
Q: my ajax is not working in codeigniter I am getting error in Ajax by using the method post and getting the total attendance between two dates of the selected person.
    <script type="text/javascript">
                $(document).ready(function(){
                    $("#submit").click(function(event){
                        event.preventDefault();
                        var fromdate = $("#fromDate").val();
                        var todate = $("#toDate").val();
                        var dep = $("#dep").val();
                        $.ajax(
                        {
                            type: "POST",
                            url: "<?php echo base_url(); ?>" +"index.php/Ajaxcontroller/getAttendence",
                            dataType: 'json',
                            data: {from: fromdate, to: todate,dep:dep},
                            cache:false,
                            success: function(result) {
                                $("#row2").html(result);

                            },
                            error: function() {
                                alert("error");
                            }
                        });
                    });
                });
            </script>

Please help me to resolve this error.

A: **this is my controller..**

    public function getAttendence()
    {
        if($this->input->post() && $this->input->is_ajax_request()){
            $credentials=array(
                'from' => $this->input->post('from'),
                'to' = $this->input->post('to'),
                'dep' => $this->input->post('dep')
            );
            $this->load->model('Ajaxmodel');
            if($this->Ajaxmodel->selectAttendence($credentials)){
                $data['result']=$this->Ajaxmodel->selectAttendence($credentials);
                echo json_encode($data);
            }
        }
        else{
             $this->load->view('Salarycontrol');
        }
    }

A: Edit your code as
data: {'from': fromdate, 'to': todate, 'dep':dep}
If still getting error please elaborate the error exactly you are getting


text:
Q: Calling coroutine from coroutine in python I came across this issue today and I'm not quite certain why it works like this:
def outside():
    print 'before'
    inside()
    print 'after'
    yield 'World'

def inside():
    print 'inside'
    yield 'Hello'

for n in outside():
    print n

(Naive) expectation of output:
before
inside
Hello
after
World

Actual output:
before
after
World

Is it not possible to call a coroutine from inside a coroutine? The articles I read on coroutines and yield didn't elaborate on this issue and I'm quite lost here. Could anyone shed some light on this behaviour please? Thanks in advance!

A: It is totally possible. when you call inside() it creates a coroutine. In order to yield the result, you need to initialize the coroutine and yield from it as follows:
def outside():
     print 'before'
     for i in inside():
         yield i
     print 'after'
     yield 'World'

and the result would be as expected:
before
inside
Hello
after
World


text:
Q: using IEnumerable over List in C# What's the advantages to use IEnumerable over List? For example I have a Employee class and a collection of employee objects, if I want to iterate each employee, I can either use:
List<Employee> employees = new List<Employee>() { new Employee(...),...}
foreach (Employee emp in employees)
{
   Console.WriteLine(emp.Name);
}

or I can use Ienumerable as :
IEnumerable<Employee> employees = new List<Employee>() { new Employee(...),...}

then use foreach loop.
Both of them achieve same goal, so why we sometimes prefer to use IEnumerable over List?

A: List is a more complex structure that enables accessing values by index and supports the methods insert, add, remove and other methods. IEnumerable is a very basic interface that the List class implements as well(though it can be tricky to implement the first few times). That said, IEnumerable is used when you do not need the extras that a List provides. Otherwise, because a List has an "is a" relationship with IEnumerable you can use it the same due to the rules of contravariance that c# provides for. Here is some documentation on that:
https://msdn.microsoft.com/en-us/library/dd799517.aspx
Also on the implementation of an IEnumerable:
https://msdn.microsoft.com/en-us/library/system.collections.ienumerable(v=vs.110).aspx
In conclusion, if all you need to do is use a simple iterator such as a foreach loop to cycle through the resultant IEnumerable, or use LINQ, than an IEnumerable type is great and lightweight. If you need more functionality, than the list builds upon the features that IEnumerable requires because it is an IEnumerable and then some.


text:
Q: How to make magrittr's pipe operator (%>%) work when nesting base-R functions? Why does this code produce an error ?
library(magrittr)

c('a', 'b', 'c', 'b') %>%
  seq_len(length(.))

# Error in seq_len(., length(.)) :
#   2 arguments passed to 'seq_len' which requires 1

A: Another way could be to wrap in braces:
c('a', 'b', 'c', 'b') %>%
  {seq_len(length(.))}

See: https://magrittr.tidyverse.org/reference/pipe.html

Often, some attribute or property of lhs is desired in the rhs call in addition to the value of lhs itself, e.g. the number of rows or columns. It is perfectly valid to use the dot placeholder several times in the rhs call, but by design the behavior is slightly different when using it inside nested function calls. In particular, if the placeholder is only used in a nested function call, lhs will also be placed as the first argument! The reason for this is that in most use-cases this produces the most readable code. For example, iris %>% subset(1:nrow(.) %% 2 == 0) is equivalent to iris %>% subset(., 1:nrow(.) %% 2 == 0) but slightly more compact. It is possible to overrule this behavior by enclosing the rhs in braces. For example, 1:10 %>% {c(min(.), max(.))} is equivalent to c(min(1:10), max(1:10)).

A: Pipe operator tries to insert left-hand-side argument as an argument to the function call on the right-hand-side. If you are not using any . at the rhs function call as a parameter, it inserts it as a first argument by default. In your situation, since you are not using . directly as an argument to seq_len, it transforms the call into:
seq_len(., length(.))

and I think there is no way around it with nesting.
There is no point in nesting here, however. The main idea behind pipe operator is to avoid nesting, so code more in line with this philosophy would be:
c('a', 'b', 'c', 'b') %>%
  length() %>%
  seq_len()

EDIT:
I feel like I need to add: you can nest . inside some other call here, but you need to pass . as a direct parameter to function on rhs at least once. Here is an example that would work:
1:5 %>%
  purrr::map2(., exp(.), ~ .x + .y) # first parameter is passes as a direct ., second is . nested within a call -- no implicit adding of . as first parameter

A: Here is a solution that uses an anonymous function
library(magrittr)

c('a', 'b', 'c', 'b') %>%
  (\(.) seq_len(length(.)))


text:
Q: SQL issue that I should be able to answer but I cannot Here's the tiny bit of data I am to query:
name       continent    area      population    gdp
Afghani    Asia         652230    25500100      20343000000
Albania    Europe       28748     2831741       12960000000
Algeria    Africa       2381741   37100000      188681000000
Andorra    Europe       468       78115         3712000000
Angola     Africa       1246700   20609294      100990000000

Given the above data, the request was to select two columns with France, Germany, Italy and their populations.
Here was my thought:
Select name, population
where name = 'France','Germany','Italy'

Where was any screw-up, if you would be so kind.

A: The = operator doesn't take multiple arguments. You're looking for the in operator. Additionally, you're missing a from clause:
SELECT name, population
FROM   populations
WHERE  name IN ('France', 'Germany', 'Italy')


text:
Q: Why Does 'import { RouterModule } from '@angular/router;' Syntax Work? Basically, what the title says. Why can I just provide the @angular/whatever as a route instead of providing a legitimate route like I would for custom components? ( for example: import {FooModule} from ../../somefolder/some-exported-es6-module )
An example of this can be seen in the start-up app:
http://plnkr.co/edit/tpl:AvJOMERrnz94ekVua0u5?p=catalogue
e.g.
//our root app component
import {Component, NgModule} from '@angular/core'
import {BrowserModule} from '@angular/platform-browser'

Does this only work with angular packages or is this some global syntax that I am not aware of?

A: The module loader is SystemJS which gets configured in config.ts to map "@angular/whatever" to some URL.


text:
Q: VisualStudio 2012 crashes on opening web-based project - Windows 7 - Windows error message Everything had beed working great, but suddenly something happened and every time I try to open any web-based project (either MVC or just 'Open Web Site', any others are just fine), Visual Studio 2012 crashes with Windows environment message:

MyProject - Microsoft Visual Studio (Administrator): devenv.exe - System error
Exception Processing Message 0xc0000005 Parameters 0x000007FEFD4A718C 0x000007FEFD4A718C 0x000007FEFD4A718C 0x000007FEFD4A718C
ОК
I did not notice exact moment when it stopped working. And obviously I have different extensions etc. But I believe, I did not install any big soft these days.
I've installed Windows 8 though, but separatly - on separate volume to try it. Theoretically, it might affect my situation, but I don't know how is that possible - at least I don't know any explanations.
I've tried to refresh Visual Studio 2012 installation, even removed and installed it again.
However, at the same time, I have Visual Studio 2010 previously installed, and it opens web-based projects without any problems.
Mentioned error message above is, as I understand, some generic error message - googling did not help on its recognizing, so don't know what to do - don't really want to reinstall Windows because of that.
Does anyone have any thoughts? Thanks!

A: I really don't know what was the cause of the problem, but after all other tries I've applied all pending updates of Windows Update service and everything works well after that.


text:
Q: MS Access: Use VBA to Change Query using Multi-Select List Box I am trying to do a query that changes based on the selection of a multi-select list box.
My code works fine for 1 item, but if you try to select multiple items it does not work properly.
Private Sub Toggle7_Click()

Dim strSQL As String
Dim db As DAO.Database
Dim qdf As DAO.QueryDef
Set db = Application.CurrentDb
Set qdf = db.QueryDefs("SSSBasic")
Dim Criteria1 As String

Dim strList As String
Dim FstrList As String
Dim varSelected As Variant

'Criteria1 = Me.List_Group

Dim ctl As Control

Set ctl = Me!List_Group
  If ctl.ItemsSelected.Count = 0 Then
    MsgBox "You haven't selected anything"
  Else
    For Each varSelected In ctl.ItemsSelected
      strList = strList & ctl.ItemData(varSelected) & " Or "
    Next varSelected
    FstrList = Left$(strList, Len(strList) - 4)
    'MsgBox "You selected the following items:" & vbCrLf & FstrList
  End If

strSQL = "SELECT * FROM SSSTable WHERE (SSSTable.Group = """ & FstrList & """)"

qdf.SQL = strSQL

DoCmd.OpenQuery "SSSBasic"

End Sub

When I select Proc and Non-Proc from list box, the code will run, but I get zero records. This is what the SQL looks like:
SELECT *
FROM SSSTable
WHERE (((SSSTable.Group)="Proc Or Non-Proc"));

I cannot figure out how to get it to work...
Thank you for your help!


text:
Q: Best Way to update Array with SharedObject As3 I just made a irc client with as3, but the problem is that i don't have too much experience with SharedObject. I need a best way to update an array when a user join other channels.
For example, if i have this array:
var channels:Array = [];

I also have a function where i can get vars if a user join other channels and when the use do that, array must be updated, without removing vars thats already exist in array, but i fails everytime in this. What's the best way to update array for one item such like for "Channels", it must be looks: "'#channel1', '#channel2', '#channel3'". Sorry for my bad english, i am from the netherlands.
To make a bit more clear:, this is one of in switch() for user commands:
case "JOIN":
    if(sCmd.split(" ")[1] == "")
    {
        sendNoticeToServerAndChatroom("Geef een kanaal op.");
    } else {
        var getJoinChannel = sCmd.split(" ")[1];
        sendCommand("JOIN", [getJoinChannel]);
                     // Here must be a code that sends every channels to a array <- (channels:array = [];)
        goToRoom();
    }
break;

Thanks!


text:
Q: how to compute vertex similarity to neighbors in graphx Suppose to have a simple graph like:
val users = sc.parallelize(Array(
                 (1L, Seq("M", 2014, 40376, null, "N", 1, "Rajastan")),
                 (2L, Seq("M", 2009, 20231, null, "N", 1, "Rajastan")),
                 (3L, Seq("F", 2016, 40376, null, "N", 1, "Rajastan"))
            ))
val edges = sc.parallelize(Array(
                 Edge(1L, 2L, ""),
                 Edge(1L, 3L, ""),
                 Edge(2L, 3L, "")))
val graph = Graph(users, edges)

I'd like to compute how much each vertex is similar to its neighbors on each attribute.
The ideal output (an RDD or DataFrame) would hold these results:
1L: 0.5, 0.5, 0.5, 1.0, 1.0, 1.0, 1.0
2L: 0.5, 0.0, 0.0, 1.0, 1.0, 1.0, 1.0
3L: 0.0, 0.5, 0.5, 1.0, 1.0, 1.0, 1.0

For instance, the first value for 1L means that on 2 neighbors, just 1 share the same value...
I am playing with aggregateMessage just to count how many neighbors have a similar attribute value but with no avail so far:
val result = graph.aggregateMessages[(Int, Seq[Any])](
    // build the message
    sendMsg = {
        // map function
        triplet =>
        // send message to destination vertex
        triplet.sendToDst(1, triplet.srcAttr)
        // send message to source vertex
        triplet.sendToSrc(1, triplet.dstAttr)
    }, // trying to count neighbors with similar property
    { case ((cnt1, sender), (cnt2, receiver)) =>
        val prop1 = if(sender(0) == receiver(0)) 1d else 0d
        val prop2 = if(Math.abs(sender(1).asInstanceOf[Int] - receiver(1).asInstanceOf[Int])<3) 1d else 0d
        val prop3 = if(sender(2) == receiver(2)) 1d else 0d
        val prop4 = if(sender(3) == receiver(3)) 1d else 0d
        val prop5 = if(sender(4) == receiver(4)) 1d else 0d
        val prop6 = if(sender(5) == receiver(5)) 1d else 0d
        val prop7 = if(sender(6) == receiver(6)) 1d else 0d
        (cnt1 + cnt2, Seq(prop1, prop2, prop3, prop4, prop5, prop6, prop7))
    }
)

this gives me the correct neighborhood size for each vertex but is not summing up the values right:
//> (1,(2,List(0.0, 0.0, 0.0, 1.0, 1.0, 1.0, 1.0)))
//| (2,(2,List(0.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0)))
//| (3,(2,List(1.0, 0.0, 0.0, 1.0, 1.0, 1.0, 1.0)))

A: It doesn't sum values because there is no sum in your code. Moreover your logic is wrong. mergeMsg receives messages not (message, current) pairs. Try something like this:
import breeze.linalg.DenseVector

def compareAttrs(xs: Seq[Any], ys: Seq[Any]) =
  DenseVector(xs.zip(ys).map{ case (x, y) => if (x == y) 1L else 0L}.toArray)

val result = graph.aggregateMessages[(Long, DenseVector[Long])](
  triplet => {
    val comparedAttrs = compareAttrs(triplet.dstAttr, triplet.srcAttr)
    triplet.sendToDst(1L, comparedAttrs)
    triplet.sendToSrc(1L, comparedAttrs)
  },
  { case ((cnt1, v1), (cnt2, v2)) => (cnt1 + cnt2, v1 + v2) }
)

result.mapValues(kv => (kv._2.map(_.toDouble) / kv._1.toDouble)).collect
// Array(
//   (1,DenseVector(0.5, 0.0, 0.5, 1.0, 1.0, 1.0, 1.0)),
//   (2,DenseVector(0.5, 0.0, 0.0, 1.0, 1.0, 1.0, 1.0)),
//   (3,DenseVector(0.0, 0.0, 0.5, 1.0, 1.0, 1.0, 1.0)))


text:
Q: MongoDB - aggregation to append a document to an existing array within an array in a collection I currently have a master collection which looks like this:
{
"col1": "a",
"col2": "b",
"array1": [{
    "col3": "xyz",
    "member": [{
        "memberName": "JohnSmith",
        "memberId": "999ABC888",
        "contact": [{
                "type": "phone",
                "value": "999-000-1234"
            },
            {
                "type": "email",
                "value": "foo_bar@outlook.com"
            }
        ]
    }]
}]

}
Then I have another staging collection which has lets say 2 documents:
{
"memberName": "JohnSmith",
"memberId": "999ABC888",
"age": 35,
"status": "single",
"hobbie1": "playing guitar",
"hobbie2": "sketching"
},
{
"memberName": "WillBeems",
"memberId": "8SW8YGS72",
"age": 42,
"status": "married",
"hobbie1": "travel",
"hobbie2": "writing"
}

I want to see if the combination of memberName and memberId matches between the staging and master collection (in this case the record for JohnSmith and 999ABC888 exists in both collections) then I want to add an additional array ("additionalInfo") to my master collection within the member array.
Expected Output:
{
"col1": "a",
"col2": "b",
"array1": [{
    "col3": "xyz",
    "member": [{
        "memberName": "JohnSmith",
        "memberId": "999ABC888",
        "contact": [{
                "type": "phone",
                "value": "999-000-1234"
            },
            {
                "type": "email",
                "value": "foo_bar@outlook.com"
            }
        ],
        "additionalInfo": [{
            "age": 35,
            "status": "single",
            "hobbie1": "playing guitar",
            "hobbie2": "sketching"
        }]
    }]
}]
}

Let me know your thoughts on resolving this. I tried using unwind > lookup > group > out, but the problem was - if there's no match on either one of the columns it still overwrite the whole "additionalInfo" array. Any suggestions?


text:
Q: Keyboard shortcut to "Show Applications" I want a keyboard shortcut that is equivalent to pressing the dotted "Show Applications" button on the Ubuntu dock. The closest thing in Settings > Devices > Keyboard is Show all applications (Super+A), but this shows not only all applications, but all activities as well (maybe a bug?). For example, here is a sequence of actions:

*

*I press Super+A to get up the applications dash.

*The
applications dash pops up as expected.

*Now I want to close the
applications dash, I hit Super+A OR Escape.

*It goes away,
but now the activities dash is there instead of the desktop or
whatever I had before Step 1).

A: What you're describing is a standard behaviour.

*

*Pressing Super brings up the "Activities" overview (same as clicking "Activities" in the top-left). Pressing Super again brings you back to the desktop.

*Pressing Super+A brings up the applications list (same as clicking "Show Applications" icon in the Ubuntu dock).
But pressing Super+A again or pressing Escape won't take you back to the desktop, it takes you to the Activities overview instead (standard behaviour from GNOME shell). Press only Super when you have the applications list open to get back to your desktop.

A: I actually created a lightweight deb installer to do this, check out my repo here https://github.com/milan102/Ubuntu-Launchpad
The installation instructions are in the github README. The program is a simple shell script that invokes the keyboard shortcut for showing applications (Super+A)
It's not a direct keyboard shortcut like you were asking, but it's pretty close.

A: use dash to panel extension. It has the the setting to work with escape
I didn't actually found the setting. But escape started working once I installed it.
It also has {click empty space to close overview} and lot more.
It may help you


text:
Q: BIDS 2008 expand fonts available I added new fonts in Windows. When preparing a new report in Business Intelligence Development Studio, the new fonts are not available in combobox for FontFamily in Properties of a report element.
I can use some of the new fonts in report by building an expression ="New Font". The fonts available in combobox are presented as "Constants" in Expression Builder. Is there some way to expand the list of constants for FontFamily and therefore to make new fonts easily accessed for usage?


text:
Q: How to import neo4j dump into the current database I can get a dump of the current database as following:
neo4j-shell -c dump > dump.sql

Now how do I import that dump file into another database (using the shell)

A: neo4j-shell -file dump.sql

The shell will exit after executing the file. See http://neo4j.com/docs/2.2.2/re02.html


text:
Q: Way to run .NET application on Win7 without installing anything? We have a few special computers that are for security reasons offline and use W7 with some tweaks. I cannot install anything on these machines, all I can do is run a portable program.
I would need to run my .NET application, is there any way I could run it without having to install .NET framework; something like pre-compiling it with linked all the libraries and then run it as a stand-alone app, like .NET native does for W10?

A: According to the article
What version of the .NET Framework is included in what version of the OS,
Windows 7 includes the .NET Framework 3.5.1 as an OS component.
This means you will have available the .NET Framework 2.0 SP2, 3.0 SP2
and 3.5 SP1 plus a few post 3.5 SP1 bug fixes.
You will not see it in Programs and Features because it is built-in.
So all you have to do is to downgrade your app to .NET 3 and it will run.
If you are using Visual Studio 2017, it might be possible to package the
.Net Framework with the application. See the Microsoft blog:
Package a .NET desktop application using the Desktop Bridge and Visual Studio Preview.