text:
Q: A faster way of doing objectToArray Ive got this snippet of code below which works perfectly fine. I have been profiling it and the bit of code gets used alot of times, so I want to try figure out how to write it in a way that will perform better than the current way its written.
Is there a more efficient way to write this?
function objectToArray($d) {
    if (is_object($d)) {
        // Gets the properties of the given object
        // with get_object_vars function
        $d = get_object_vars($d);
    }

    if (is_array($d)) {
        // Return array converted to object Using __FUNCTION__ (Magic constant) for recursive call
        return array_map(__FUNCTION__, $d);
    }
    else {
        // Return array
        return $d;
    }
}

A: You could implement a toArray() method to the class that needs to be converted:
e.g.
class foo
{
  protected $property1;
  protected $property2;

  public function __toArray()
  {
    return array(
      'property1' => $this->property1,
      'property2' => $this->property2
    );
  }
 }

Having access to the protected properties and having the whole conversion encapsulated in the class is in my opinion the best way.
Update
One thing to note is that the get_object_vars() function will only return the publically accessible properties - Probably not what you are after.
If the above is too manual of a task the accurate way from outside the class would be to use PHP (SPL) built in ReflectionClass:
$values = array();
$reflectionClass = new \ReflectionClass($object);
foreach($reflectionClass->getProperties() as $property) {
  $values[$property->getName()] = $property->getValue($object);
}
var_dump($values);

A: depends what kind of object it is, many standard php objects have methods built in to convert them
for example MySQLi results can be converted like this
$resultArray = $result->fetch_array(MYSQLI_ASSOC);

if its a custom class object you might consider implementing a method in that class for that purpose as AlexP sugested

A: Ended up going with:
function objectToArray($d) {
$d = (object) $d;
return $d;
}
function arrayToObject($d) {
$d = (array) $d;
return $d;
}

A: As AlexP said you can implement a method __toArray(). Alternatively to ReflexionClass (which is complex and expensive), making use of object iteration properties, you can iterate $this as follow
class Foo
{
  protected $var1;
  protected $var2;

  public function __toArray()
  {
    $result = array();
    foreach ($this as $key => $value) {
      $result[$key] = $value;
    }
    return $result;
  }
}

This will also iterate object attributes not defined in the class: E.g.
$foo = new Foo;
$foo->var3 = 'asdf';
var_dump($foo->__toArray());)

See example http://3v4l.org/OnVkf

A: This is the fastest way I have found to convert object to array. Works with Capsule as well.
     function objectToArray ($object) {
        return json_decode(json_encode($object, JSON_FORCE_OBJECT), true);
    }


text:
Q: Key error when printing columns in dataframe after read_csv() I'm trying to read in a CSV file into a pandas dataframe and select a column, but keep getting a key error.
This is a snippet of the input file I am working with. I want to skip the first 5 lines, use the sitxh line with model_number,star_age, etc. as the headers, and collected the columns of data:
                           1                            2                            3                            4                            5
              version_number                 initial_mass                    initial_z                    burn_min1                    burn_min2
                       10398      8.1000000000000005E-001      1.0000000000000000E-003      5.0000000000000000E+001      1.0000000000000000E+003

                                       1                                        2                                        3                                        4                                        5                                        6                                        7                                        8                                        9                                       10                                       11                                       12                                       13                                       14                                       15                                       16                                       17                                       18                                       19                                       20                                       21                                       22                                       23                                       24                                       25                                       26                                       27                                       28                                       29                                       30                                       31                                       32                                       33                                       34                                       35                                       36                                       37                                       38                                       39                                       40                                       41                                       42                                       43                                       44                                       45                                       46                                       47                                       48                                       49                                       50                                       51                                       52                                       53                                       54                                       55                                       56                                       57                                       58                                       59                                       60                                       61                                       62                                       63                                       64                                       65                                       66                                       67                                       68                                       69                                       70                                       71                                       72                                       73                                       74                                       75                                       76                                       77                                       78                                       79                                       80                                       81                                       82                                       83                                       84                                       85                                       86                                       87                                       88
                            model_number                                 star_age                                star_mass                           mass_conv_core                             he_core_mass                           he_core_radius                             conv_mx1_top                             conv_mx1_bot                             conv_mx2_top                             conv_mx2_bot                           conv_mx1_top_r                           conv_mx1_bot_r                           conv_mx2_top_r                           conv_mx2_bot_r                            cz_bot_radius                                   log_LH                                  log_LHe                                 log_Teff                               luminosity                                    log_L                                    log_R                                    log_g                          log_surf_cell_z                             log_center_T                           log_center_Rho                             log_center_P                                center_mu                        center_degeneracy                                center_h1                                center_h2                               center_he3                               center_he4                               center_li7                               center_be7                                center_b8                               center_c12                               center_c13                               center_n13                               center_n14                               center_n15                               center_o14                               center_o15                               center_o16                               center_o17                               center_o18                               center_f17                               center_f18                               center_f19                              center_ne18                              center_ne19                              center_ne20                              center_ne22                              center_mg22                              center_mg24                               surface_h1                               surface_h2                              surface_he3                              surface_he4                              surface_li7                              surface_be7                               surface_b8                              surface_c12                              surface_c13                              surface_n13                              surface_n14                              surface_n15                              surface_o14                              surface_o15                              surface_o16                              surface_o17                              surface_o18                              surface_f17                              surface_f18                              surface_f19                             surface_ne18                             surface_ne19                             surface_ne20                             surface_ne22                             surface_mg22                             surface_mg24                                   nu_max                                 delta_nu                                 delta_Pg                          acoustic_cutoff                          acoustic_radius                               d_log_L_dT                          h_exh_core_mass                        h_exh_core_radius
                                     590                  7.4832653674979620E+003                  8.0999231594859322E-001                  9.3013103578994949E-002                  0.0000000000000000E+000                  0.0000000000000000E+000                  1.1367933255238216E-001                  7.8129078318056600E-008                  1.0000000000000000E+000                  9.9318920202569283E-001                  1.1581183159043519E-001                  9.6384235196922451E-004                  6.9887906688924084E-001                  5.6970970716172920E-001                  0.0000000000000000E+000                 -1.9971124824757927E-001                 -4.8201179092980333E+001                  3.7897634917269190E+000                  6.3290767033577267E-001                 -1.9865964099109620E-001                 -1.5559796749675942E-001                  4.6575661873384373E+000                 -3.0000000000000475E+000                  7.1159454763339030E+000                  1.9980751452335390E+000                  1.7261783473862238E+001                  5.9749025137280032E-001                 -1.3921254545517694E+000                  7.4862988071983971E-001                  6.4224755686599933E-018                  1.1040796520256433E-004                  2.5025816673994183E-001                  3.6245810211769934E-016                  7.0974332935137005E-013                  4.6287532383736027E-023                  1.6090485487993254E-004                  1.9156053663187585E-006                  3.4877009372383987E-016                  6.0985269793407524E-005                  2.2754513772045929E-007                  2.9195681915663947E-031                  8.7420459328129831E-020                  4.6667973725421542E-004                  2.0414721029513937E-007                  1.1381709511386918E-006                  2.2860196785405309E-021                  9.1671666641570419E-023                  2.0874159744382837E-008                  3.7083264706195407E-042                  3.9279368604326808E-040                  1.0269030813449696E-004                  6.7091975862944943E-006                  4.2398886865254202E-017                  2.0006886383171565E-004                  7.4899999942868345E-001                  2.7200701027954921E-017                  2.6605602791999035E-005                  2.4997339496852472E-001                  1.6905661394980510E-037                  1.7567453744563094E-040                  1.0000000000000274E-099                  1.7017919585850694E-004                  1.9011704267928175E-006                  7.2620283197083900E-094                  5.0179160420602355E-005                  2.2876560599578056E-007                  1.0000000000000006E-099                  1.0000000000000006E-099                  4.6668013273267953E-004                  2.0414644161309358E-007                  1.1381848144163238E-006                  1.0000000000000006E-099                  8.4411414882972268E-074                  2.0874146844472571E-008                  1.0000000000000006E-099                  1.0000000000000006E-099                  1.0269030813453584E-004                  6.7091975862945028E-006                  1.1399939856108351E-057                  2.0006886383171633E-004                  4.9774621436997058E+003                  2.1457444791057421E+002                  0.0000000000000000E+000                  4.5146723037873518E+004                  2.3301935755574186E+003                  1.0590627364747510E+001                  0.0000000000000000E+000                  0.0000000000000000E+000
                                     591                  1.6463183808495516E+004                  8.0999231496783064E-001                  9.2873327284872409E-002                  0.0000000000000000E+000                  0.0000000000000000E+000                  1.1367933269002861E-001                  7.8129078429078902E-008                  1.0000000000000000E+000                  9.9318494262289947E-001                  1.1581293977069999E-001                  9.6385193654037807E-004                  6.9879898141115959E-001                  5.6967302923999130E-001                  0.0000000000000000E+000                 -1.9978213060522462E-001                 -4.8201281132346992E+001                  3.7897483582980382E+000                  6.3267443633058140E-001                 -1.9881971316983504E-001                 -1.5564773672836699E-001                  4.6576657252757956E+000                 -3.0000000000000475E+000                  7.1159439547711134E+000                  1.9980621893502508E+000                  1.7261768696422475E+001                  5.9749042822746268E-001                 -1.3921513883392005E+000                  7.4862947570235450E-001                  6.4224852088404529E-018                  1.1037767369519526E-004                  2.5025860081630319E-001                  3.6293040823707671E-016                  7.1091046311060774E-013                  4.6359908361904593E-023                  1.6088811945050166E-004                  1.9343478788613242E-006                  3.4876029004368768E-016                  6.0986182006780295E-005                  2.2587329315472058E-007                  2.9193215138718783E-031                  8.7416768418526394E-020                  4.6667973812484934E-004                  2.0414813320371832E-007                  1.1381543204624337E-006                  2.2858303888862015E-021                  9.1791850761956234E-023                  2.0874175222493570E-008                  3.7075984662615788E-042                  3.9325993844270721E-040                  1.0269030813445076E-004                  6.7091975862944951E-006                  9.3271194401577135E-017                  2.0006886383171565E-004                  7.4899999942868334E-001                  3.4436613497022586E-017                  2.6605602792180270E-005                  2.4997339496852464E-001                  3.7109055189055696E-037                  1.7477951709463041E-040                  1.0000000000000597E-099                  1.7017919585850675E-004                  1.9011704267928160E-006                  7.2698748944159613E-094                  5.0179160420602321E-005                  2.2876560599578056E-007                  1.0000000000000004E-099                  1.0000000000000004E-099                  4.6668013273267904E-004                  2.0414644161309340E-007                  1.1381848144163240E-006                  1.0000000000000004E-099                  8.4443007282823002E-074                  2.0874146844472544E-008                  1.0000000000000004E-099                  1.0000000000000004E-099                  1.0269030813453577E-004                  6.7091975862945011E-006                  2.4972413232265062E-057                  2.0006886383171628E-004                  4.9786898247189956E+003                  2.1461143575428008E+002                  0.0000000000000000E+000                  4.5157989697983539E+004                  2.3297919714421755E+003                  1.0577389962355879E+001                  0.0000000000000000E+000                  0.0000000000000000E+000
                                     592                  2.7239085937692584E+004                  8.0999231379148418E-001                  9.2768956348480064E-002                  0.0000000000000000E+000                  0.0000000000000000E+000                  1.1367933285512455E-001                  7.8129078429078902E-008                  1.0000000000000000E+000                  9.9317986516242851E-001                  1.1581426267158637E-001                  9.6386337090931164E-004                  6.9870341901610078E-001                  5.6962931836955688E-001                  0.0000000000000000E+000                 -1.9986631841832908E-001                 -4.8201405210184461E+001                  3.7897302509749204E+000                  6.3239593236503233E-001                 -1.9901093215713114E-001                 -1.5570713157577978E-001                  4.6577845143398982E+000                 -3.0000000000000475E+000                  7.1159420949650363E+000                  1.9980467324434472E+000                  1.7261751021496853E+001                  5.9749064052195178E-001                 -1.3921821623723432E+000                  7.4862898953216450E-001                  6.4224972602860048E-018                  1.1034185970759304E-004                  2.5025912131718681E-001                  3.6281941590277494E-016                  7.1065810408343176E-013                  4.6338906148233168E-023                  1.6086802751266569E-004                  1.9568213315500052E-006                  3.4867545924503404E-016                  6.0987289529204137E-005                  2.2388535189517994E-007                  2.9182327486870975E-031                  8.7407027840248354E-020                  4.6667973915111283E-004                  2.0414924054833912E-007                  1.1381343663647126E-006                  2.2855131115230559E-021                  9.1781576961675115E-023                  2.0874193793734392E-008                  3.7065645159884602E-042                  3.9314864173782023E-040                  1.0269030813439529E-004                  6.7091975862944926E-006                  1.5430912131334866E-016                  2.0006886383171560E-004                  7.4899999942868323E-001                  3.6108155599347527E-017                  2.6605602792408040E-005                  2.4997339496852472E-001                  6.1203516138300124E-037                  1.7349513354145605E-040                  1.0000000000000993E-099                  1.7017919585850678E-004                  1.9011704267928163E-006                  7.2796725886830642E-094                  5.0179160420602334E-005                  2.2876560599578053E-007                  1.0000000000000006E-099                  1.0000000000000006E-099                  4.6668013273267893E-004                  2.0414644161309337E-007                  1.1381848144163238E-006                  1.0000000000000006E-099                  8.4421321164489613E-074                  2.0874146844472544E-008                  1.0000000000000006E-099                  1.0000000000000006E-099                  1.0269030813453577E-004                  6.7091975862945019E-006                  4.1106152142620843E-057                  2.0006886383171622E-004                  4.9801556111713053E+003                  2.1465559040371008E+002                  0.0000000000000000E+000                  4.5171441672397355E+004                  2.3293127332935192E+003                  1.0560312314089561E+001                  0.0000000000000000E+000                  0.0000000000000000E+000
                                     593                  4.0170168492729063E+004                  8.0999231238068270E-001                  9.2657535069124067E-002                  0.0000000000000000E+000                  0.0000000000000000E+000                  1.1367933305312516E-001                  7.8129078651123507E-008                  1.0000000000000000E+000                  9.9317381688473827E-001                  1.1581583973990918E-001                  9.6387699231684568E-004                  6.9858951468809860E-001                  5.6957730101692139E-001                  0.0000000000000000E+000                 -1.9996575097436850E-001                 -4.8201556735701352E+001                  3.7897085953642202E+000                  6.3206367855156909E-001                 -1.9923916562517330E-001                 -1.5577793708840007E-001                  4.6579261246087080E+000                 -3.0000000000000475E+000                  7.1159398087311061E+000                  1.9980283205803717E+000                  1.7261729896286983E+001                  5.9749089537331979E-001                 -1.3922185550828545E+000                  7.4862840591704072E-001                  6.4225121615288567E-018                  1.1029964301003699E-004                  2.5025974536316059E-001                  3.6268773618728560E-016                  7.1035719815415304E-013                  4.6313771343818876E-023                  1.6084390390354043E-004                  1.9837641461756074E-006                  3.4857298043539306E-016                  6.0988637058530873E-005                  2.2152584991130176E-007                  2.9169145056016640E-031                  8.7395177948976034E-020                  4.6667974035628692E-004                  2.0415056914861469E-007                  1.1381104254089161E-006                  2.2851269496277786E-021                  9.1769014090128329E-023                  2.0874216075586247E-008                  3.7053063551717499E-042                  3.9301281231132292E-040                  1.0269030813432880E-004                  6.7091975862944951E-006                  2.2754168226061389E-016                  2.0006886383171563E-004                  7.4899999942868323E-001                  3.6446705264203970E-017                  2.6605602792683519E-005                  2.4997339496852472E-001                  8.9903274053503869E-037                  1.7196986704942170E-040                  1.0000000000001490E-099                  1.7017919585850689E-004                  1.9011704267928175E-006                  7.2888696099299523E-094                  5.0179160420602334E-005                  2.2876560599578053E-007                  1.0000000000000004E-099                  1.0000000000000004E-099                  4.6668013273267893E-004                  2.0414644161309345E-007                  1.1381848144163238E-006                  1.0000000000000004E-099                  8.4345403543658127E-074                  2.0874146844472561E-008                  1.0000000000000004E-099                  1.0000000000000004E-099                  1.0269030813453578E-004                  6.7091975862945019E-006                  6.0248713184901274E-057                  2.0006886383171625E-004                  4.9819039607629957E+003                  2.1470824703177900E+002                  0.0000000000000000E+000                  4.5187487085895678E+004                  2.3287414755242025E+003                  1.0539230280853543E+001                  0.0000000000000000E+000                  0.0000000000000000E+000

And here is what my code looks like:
import matplotlib.pyplot as plt
import mesa_reader as mr
import pandas as pd

# load and plot data
#h = mr.MesaData('history.data')
h = pd.read_csv('history.data', header=4)
#plt.plot(10**h.log_Teff, h.luminosity)
#plt.plot(10**h["log_Teff"], h["luminosity"])
#print("The column headers :")
#print(list(h.columns.values))
print(h['model_number'])

As well as the error:
Traceback (most recent call last):
  File "/home/nick/.local/lib/python3.6/site-packages/pandas/core/indexes/base.py", line 2898, in get_loc
    return self._engine.get_loc(casted_key)
  File "pandas/_libs/index.pyx", line 70, in pandas._libs.index.IndexEngine.get_loc
  File "pandas/_libs/index.pyx", line 101, in pandas._libs.index.IndexEngine.get_loc
  File "pandas/_libs/hashtable_class_helper.pxi", line 1675, in pandas._libs.hashtable.PyObjectHashTable.get_item
  File "pandas/_libs/hashtable_class_helper.pxi", line 1683, in pandas._libs.hashtable.PyObjectHashTable.get_item
KeyError: 'model_number'

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "HR_plotter.py", line 12, in <module>
    print(h['model_number'])
  File "/home/nick/.local/lib/python3.6/site-packages/pandas/core/frame.py", line 2906, in __getitem__
    indexer = self.columns.get_loc(key)
  File "/home/nick/.local/lib/python3.6/site-packages/pandas/core/indexes/base.py", line 2900, in get_loc
    raise KeyError(key) from err
KeyError: 'model_number'

A: This data is in fixed-width format, so use read_fwf with skiprows:
h = pd.read_fwf('history.data', skiprows=5)

redpajama_set_name: RedPajamaStackExchange


text:
Q: Are there any concrete examples when using the Any type is a good solution? We all know that swift has a strong type system, and as such I lean towards using this system to my advantage :)
Here's what Apple has to say about using the Any type:

Type Casting for Any and AnyObject
Swift provides two special type aliases for working with non-specific
  types:
AnyObject can represent an instance of any class type. Any can
  represent an instance of any type at all, including function types.
  NOTE
Use Any and AnyObject only when you explicitly need the behavior and
  capabilities they provide. It is always better to be specific about
  the types you expect to work with in your code.

I don't know if it's me, but I kind of think the code starts to smell when using these (This maybe my lack of experience using them) - I know AnyObject is required/useful for interacting with Objective-C so I get that there is a practical nature to AnyObject's use.
So I wanted to know what concrete examples represent a good use of the Any type.
For example is it could be used to pass unknown content to a POST request constructor method where the method could safely use optional chaining to examine the unknown content.
Apple's example from the Swift Programming Language (Swift 2.2)

Any
Here's an example of using Any to work with a mix of different types,
  including function types and non-class types. The example creates an
  array called things, which can store values of type Any:

var things = [Any]()

things.append(0)
things.append(0.0)
things.append(42)
things.append(3.14159)
things.append("hello")
things.append((3.0, 5.0))
things.append(Movie(name: "Ghostbusters", director: "Ivan Reitman"))
things.append({ (name: String) -> String in "Hello, \(name)" })

A: If you are using pure Swift (without the legacy Objective-C stuff) and you want an array where you can put Int(s), Bool(s) and String(s) then you need an array of Any.
let values: [Any] = [1, true, "I'm not a pointer!"]

But, wait I can also use an array of AnyObject right?
Nope. Infact Int, Bool and String in Swift are struct(s).
They why does this code compile?

The code above compile because the import Foundation does enable the bridge to Objective-C. This mean the Swift Int, Bool and String are allowed to be seen as objects by the compiler in order to preserve compatibility  with Objective-C.
But as soon as you remove the import Foundation the code stop compiling.

A: When should I use [Any]?
Any is an abstract type that all other types implicitly conform to. Because it could be anything – it must be guaranteed to do nothing.
For that very reason, typing a variable as Any is nonsensical. If I define this:
let itCouldBeAnything : Any = "Actually it's a string"

It now can't do anything (without type casting):

You should always use the most descriptive type available when defining something, and because of Any's abstract nature, there will always be a more descriptive type available – in this case, String should've been used.
Now let's think about arrays. As you say, Apple demonstrates that you can use an array of Any to mix together different types.
var things = [Any]()

things.append(0)
things.append(0.0)
things.append(42)
things.append(3.14159)
things.append("hello")
things.append(Movie(name: "Ghostbusters", director: "Ivan Reitman"))

Great. But what does this array actually represent? It's just a collection of junk – the programming equivalent of the backseat of my car.
If we try and do something with one of the elements...

We can't. It could be anything – so we can't do anything with it. Sure, we can type cast the elements with a switch or if statement to handle the different possibilities – but all we'll succeed in doing there is splitting our array back into distinct types. So what was the point in using [Any] to begin with?
An array should always represent a collection of related data. There's no point of an array if the elements share nothing in common. If the different types that the array can store have common functionality, then you should define a protocol with this common functionality:
protocol ACommonProtocol {
    // define common functionality
}

We can then conform the types that the array can store to it:
extension Int : ACommonProtocol {}
extension Double : ACommonProtocol {}
extension String : ACommonProtocol {}
extension Movie : ACommonProtocol {}

Now our array can be of type [ACommonProtocol]. This is a significant improvement from Any, we've narrowed the concrete types that the elements could be down to 4 – and we can now use any common functionality that we define in the protocol on the elements without type-casting. Our elements also are now explicitly related, which actually gives the array some meaning (assuming the protocol represents a meaningful concept).
If the different types that the array can store don't have any common functionality, or cannot conform to protocols (such as tuples and functions), but are still related in some meaningful way – then another way of expressing this relationship is through using an enum with associated values:
// obviously this enum (and possibly its cases) should have a far better names
enum IntDoubleStringOrMovie {
    case int(Int)
    case double(Double)
    case string(String)
    case movie(Movie)
}

Now our array can be of type [IntDoubleStringOrMovie] – which has the added benefit of allowing us to use an exhaustive switch in order to determine the element type:
for element in array {
    switch element {
    case let .int(int):
        print(int)
    case let .double(double):
        print(double)
    case let .string(string):
        print(string)
    case let .movie(movie):
        print(movie)
    }
}

So for this reason, you should never ever have to use [Any] in Swift. If you ever find yourself in a situation of using [Any], you should be re-considering your data structure. Whether that involves splitting the array up into sub-arrays, conforming the elements to a common protocol (if they have common functionality), using an enum with associated values (if they have no common functionality) or using a different collection type altogether, is entirely up to you.
But what about interfacing with Objective-C?
Any is sometimes necessary for bridging with Objective-C's inferior type system – and therefore you may well find yourself using [Any] with Objective-C APIs, which is acceptable (although with the bridging of Objective-C's lightweight generics to Swift, it should be uncommon).
The only thing I would say about this is once you're back in your Swift logic, you should always convert an [Any] back to a meaningful array type through type casting, or unpacking it into a more appropriate data structure. You shouldn't sacrifice type safety in Swift just because Objective-C lacks in that regard.
But what about [AnyObject]?
AnyObject is pretty much as vague as Any in pure Swift. The only thing it guarantees is that it's a class. However, as of Swift 3, anything can be bridged to Objective-C by being boxed in a _SwiftValue. For this reason, [AnyObject] is just as (if not more) questionable as [Any].


text:
Q: error in update with composer in ezlatform 5.4 i'm using ezplatform 5.4  , and when i run composer update/install , it show me this error :
[ErrorException]
 Declaration of
 eZ\Bundle\EzPublishLegacyBundle\Composer\ScriptHandler::installAssets()
should be compatible with
Sensio\Bundle\DistributionBundle\Composer\ScriptHandler::installAssets
(Composer\Script\Event $event)

i don't find any response to get out from this error , and i hope some solution for that .
thank you in advance .

A: The distribution bundle required in the root composer.json must be updated. On the 5.4.x update instructions page for eZ Platform, you will see for version 5.4.2 that it must be bumped to ~3.0.
Running the composer require command from this chapter may therefore fix your error, but it is hard to be 100% sure. Let me know.


text:
Q: android display string I am trying to pass a string from one activity to another. I retrieved the information like this:
Intent openReadMail = getIntent();
String readfrom = openReadMail.getStringExtra("from");

Now I want to display this string on screen. I this xml TextView element:
 <TextView
        android:id="@+id/from"
        android:layout_width="match_parent"/>

but I can't convert the string to a textview, is there a better way of doing this? thanks for your help guys!

A: You have to create a variable for your TextView and then set the text.
TextView fromtxt = (TextView) findViewById(R.Id.from);

Fromtxt.setText(readfrom);

A: You need to set the text of the TextView with the String you read in.
TextView tv = (TextView)findViewById(R.id.from);
tv.setText(readFrom);


text:
Q: Java Regex vs. PHP, Dangling meta character '?' I'm tagging this with PHP even though it's a Java question.  The regex is copied from a PHP source so I'm hoping some PHPers can help with the question.
I decided to build a simple spam filter, just for fun, and I copied the spam blocklist from MediaWiki: https://meta.wikimedia.org/wiki/Spam_blacklist
Mostly this seems to work, but a few of the patterns fail with a syntax error.  I don't know if this is a typo or if PHP uses a different syntax than Java.  Can anyone help me fixing these regex so that they compile?
Here's the problems:
java.util.regex.PatternSyntaxException: Dangling meta character '?' near index 17
\bfacebo(?:o[ob]|?o)k\.com\b
                 ^
java.util.regex.PatternSyntaxException: Dangling meta character '?' near index 5
\b????\.tk\b
     ^
java.util.regex.PatternSyntaxException: Dangling meta character '?' near index 0
??\.xsl\.pt\b
^
java.util.regex.PatternSyntaxException: Dangling meta character '?' near index 4
\b????\.shop\b
    ^
java.util.regex.PatternSyntaxException: Dangling meta character '?' near index 4
\b???\.??\b
    ^

Here's the code that compiles them, in case you're interested.  I don't think it makes a difference though.
   private static synchronized void init() throws IOException {

      if( blackListPatterns.get() != null ) return;
      InputStream blacklistfile = SpamBlackList.class.getResourceAsStream( "blacklist.txt" );
      BufferedReader buf = new BufferedReader( new InputStreamReader( blacklistfile, "UTF-8" ) );
      ArrayList<String> blacklist = new ArrayList<>( 12000 );
      for( String line; (line = buf.readLine()) != null; )
         if( !line.isBlank() && line.trim().charAt(0) != '#' )
            blacklist.add( line );
      ArrayList<Pattern> tempPatterns = new ArrayList<>( blacklist.size() );
      for( String pat : blacklist )
         try {
            tempPatterns.add( Pattern.compile( pat ) );
         } catch ( java.util.regex.PatternSyntaxException ex ) {
            System.err.println( ex );  // should log this, low level like FINER
         }
      blackListPatterns = new WeakReference<>( tempPatterns );
   }

   private static volatile WeakReference<List<Pattern>>
           blackListPatterns = new WeakReference( null );

A: Your downloaded copy of https://meta.wikimedia.org/wiki/Spam_blacklist (blacklist.txt) is corrupt. The dangling question marks are non-ASCII characters, e.g. \bfacebo(?:o[ob]|?o)k\.com\b is actually \bfacebo(?:o[ob]|ıo)k\.com\b. Note the dotless "ı".
Download https://meta.wikimedia.org/wiki/Spam_blacklist?action=raw and take into account that it is UTF-8.
And you may want to pass Unicode flag to the regular expressions. Also take into account that:

What is referred to here as regular expressions are not proper regular expressions, but rather subpatterns that are inserted into a hard-coded regular expression. i.e. the subpattern Foo from above would create a regular expression like /^Foo$/usi.

(see https://www.mediawiki.org/wiki/Extension:TitleBlacklist#Block_list).


text:
Q: Is there an advantage in declaring "this" on every reference to itself in a script in C#? I'm looking at code from another programmer and style differences aside, they do something I don't.
On every single reference to the class' own variables and methods, they precede it with this. (ie. this.Init() x Init() )
On my side, I've mostly used this to pass a reference to the instance to other classes, or, on occasion, when I needed to differentiate from base.
Is there any particular advantage in explicitly referring to this every time?

A: No functional difference.  Perhaps the project coding style guidelines require it, in which case you should use it.


text:
Q: C# Interface Problem For some reason, I am having issues with Interfaces. I know a 100 examples have been posted but apparently I'm not smart enough to figure it out...
I have the following interface:
namespace DocStore.Interfaces
{
  public interface IResetCategoryControl
  {
    string CategoryToAdd { set; }
  }
}

I want to set CategoryToAdd to a value.
Here is my class that I want to set it in and what I have so far:
  public partial class AddDocumentsDialog : IResetCategoryControl

    public string CategoryToAdd
    {
      set
      {
        IResetCategoryControl() ireset = new IResetCategoryControl();
        ireset.CategoryToAdd = value;
      }
    }
  }

What am I doing wrong in the AddDocumentDialog class? I can't get that part to work.
Thank you!
Eroc

A: Following line is the problematic one:
IResetCategoryControl() ireset = new IResetCategoryControl();

First, you need to get rid of first parenthesis:
IResetCategoryControl ireset = new IResetCategoryControl();

Next, you cannot instantiate an interface. Interface is only a signature which has to be implemented by a concrete class.
If you are looking at some other people's code, right click on IResetCategoryControl and select "Find all references" to search if this interface has already been implemented in some class.
For example, you may find:
class SomeResetCatControl : IResetCategoryControl
{

}

On the other hand, it looks like you only need to set an internal private field in your setter method. You should do it like this in that case:
public partial class AddDocumentsDialog : IResetCategoryControl
{
   private string _categoryToAdd = "";
   public string CategoryToAdd
   {
     set
     {
        _categoryToAdd = value;
     }
   }
}

But as others have already pointed out, using a write-only property is very unusual, and indicates wrong design.

A: You can't instantiate an interface:
IResetCategoryControl() ireset = new IResetCategoryControl();

After the new keyword you must use an object that implements that interface.

A: I'm not sure what you're trying to do in your setter...but the following line is causing you problems:
IResetCategoryControl() ireset = new IResetCategoryControl();

First of all, you don't use parenthesis when declaring the type of a variable. Second of all, you can't directly instantiate an instance of an Interface. To make that statement valid it would have to be something along the lines of:
IResetCategoryControl iReset = new SomeConcreteResetCategoryControl();

There is a bigger issue though:
Theoretically, your class is implementing the interface and the interface specifies that you need a property called CategoryToAdd with a public setter. That property should be setting the value on your class...not a new instance of another class.
I would expect the code to look something like:
public partial class AddDocumentsDialog : IResetCategoryControl
{
    private string categoryToAdd;

    public string CategoryToAdd
    {
        set
        {
            // do some logic to validate the value
            categoryToAdd = value;
        }
    }
}

You might also want to re-think your interface design as set only properties are typically discouraged (in favor of using a method, since a set only property indicates some amount of logic being executed and the value being only used internally by the class rather than accessed by the consumer again).

A: You can't instantiate an interface; it is merely a contract and not an object itself.  You need to figure out what the contract means and have AddDocumentsDialog implement that contract, doing whatever it is supposed to do when CategoryToAdd is set.
On a side note, set-only properties are discouraged.  It's better to use a method.

A: This isn't valid C# -- remove the first pair of ():
IResetCategoryControl() ireset = new IResetCategoryControl();

Edit: It's still not valid C#. You can't instantiate an interface, only classes.

A: ireset is only defined locally, within the set. You won't be able to access it anywhere else

A: You can't instantiate an interface.  new IResetCategoryControl is never going to work.  AddDocumentsCatalog implements IResetCAtegoryControl with the string property CategoryToAdd.  Whatever computation you do to return CategoryToAdd is up to you.

A: From the looks of it, ireset is going out of scope as soon as you've set one of its properties.  I'm guessing that should probably be a member variable...
I'm making the assumption the 'IResetCategoryControl()' type declaration is a typo, but if not, that's also an issue.


text:
Q: Are scala.util.automata, scala.util.regexp, and scala.util.grammar really needed? These package exist for a long time as far as I know.  However, I have not ever seen their realistic usage.  And it seems that these packages are immature and no longer maintained.  If yes, why these packages exist now ?

A: The package automata is used by scala.xml.dtd, and regexp is used by automata. As for grammar, I couldn't find any use of it and, perhaps, it could be removed.


text:
Q: Problem with C nested structure. error: invalid use of incomplete typedef For the sake of simplicity I'm going to recreate the actual situation with dummy structures. I have this structure (not my code, I can't edit it):
// private_header_a.h
struct A_s{
 int a1;
};
// header_a.h
typedef struct A_s A_t;

Then in one of my headers I extended it this way:
// my_header.h
typedef struct B_s{
 A_t* a_f;
 int b1;
} B_t;

Now, in my function, I have:
B_t* b;
// Initialization and some other code
b->b1 = 4; // Just an example and compiler does not give any error
// Some other code
b->a_f->a1;

This last line of code makes the compiler throw this error:
error: invalid use of incomplete typedef 'A_t' {aka 'struct A_s'}

Where is the error?
EDIT: the piece of code that triggers the compiler has header_a.h and my_header.h included. private_header_a.h cannot be included directly as not installed (I should copy-paste it, but frankly I would like to avoid to do that)

A: Here's two fundamental rules:

*

*Each c file is compiled separately

*When you #include a file, think of it as directly replacing the #include line with the contents of the file being included.

Therefore, you are compiling a piece of source code that looks like this:
struct A_s {
 int a1;
};

typedef struct B_s {
 A_t* a_f;
 int b1;
} B_t;

void foo() {
  B_t* b;
}

This code doesn't know what A_t is. You've never defined that in the code that's visible to the compiler.
A trivial way to fix this is to replace A_t with struct A_s.

A: The compiler error is probably intentional - the library's designers don't want you using A_t directly in that sort of way.
When a struct is only declared in a library's public header file, and only defined in the library's private implementation files, that means you're not supposed to know or care about its members or even size. So looking up that the struct has a member named a1 and writing b->af->a1 is not the intended use. This arrangement is called an "opaque handle". A few of its benefits are that the library keeps your application code from initializing or changing members in ways that don't make sense, and a future version of the library can change the names, numbers, and meanings of the members without breaking your application code.
(Also, how did you get a valid pointer for b->af without doing malloc(sizeof(A_t)) or similar? That sizeof would also cause a compiler error about the incomplete struct type.)
When a library uses an opaque handle, since you can't create any such objects yourself, it will typically provide functions that create the objects for you. Look for public functions in the library with names including init, create, open, etc. which return an A_t* pointer, and read their documentation. Usually there will also be a corresponding destroy, cleanup, close, etc. function which the program should call later when the library object is no longer needed. (In the case of some very simple handles, the function which creates the object might say instead you should just pass the pointer to free. But only do this if the documentation says to!)


text:
Q: Filling char array with snprintf() I am trying to fill a char array with values under conditions. The problem is I can not use snprintf() not properly.
    char staedte[MAX_LAENGE_ARR][MAX_LAENGE_STR];
    char laender[MAX_LAENGE_ARR][MAX_LAENGE_STR];
    int bewohner[MAX_LAENGE_ARR];

    char *p = (char*) malloc(len);
    if (p == NULL){
        perror("malloc failed while allocating an array of chars.");
        exit(1);
    }

    for (int i = 0; i < MAX_LAENGE_ARR; i++) {
        if(strcmp(bundesland,laender[i]) == 0 && bewohner[i] >= anzahl){
            snprintf(p,MAX_LAENGE_STR,"Die Stadt %s hat %d Einwohner. \n", staedte[i],bewohner[i]);
            snprintf(&p[i],MAX_LAENGE_STR,"Die Stadt %s hat %d Einwohner. \n", staedte[i],bewohner[i]);
        }
    }
    free(p);
}

A: regarding:
    if( strcmp( bundesland,laender[i] ) == 0 && bewohner[i] >= anzahl)
    {
            snprintf(p,MAX_LAENGE_STR,"Die Stadt %s hat %d Einwohner. \n", staedte[i],bewohner[i]);
            snprintf(&p[i],MAX_LAENGE_STR,"Die Stadt %s hat %d Einwohner. \n", staedte[i],bewohner[i]);

            printf("%s : %d\n",staedte[i] , bewohner[i]);
    }

the first call to snprintf() keeps overlaying the first entry in the p[] array
suggest:
    char buffer[MAX_LAENGE_STR+1];
    p[0] = '\0';

then in the loop
    if( strcmp( bundesland,laender[i] ) == 0 && bewohner[i] >= anzahl)
    {
            snprintf( buffer, MAX_LAENGE_STR, "Die Stadt %s hat %d Einwohner. \n", staedte[i],bewohner[i]);
            strcat( p, buffer );

            printf("%s : %d\n",staedte[i] , bewohner[i]);
    }

I'll leave it to you to add the checking that the buffer p[] is not overflowed.

A: snprintf() returns the number of bytes that it wrote to the string. You can use this to increment the position where you write the next line.
int offset = 0;
for (int i = 0; i < MAX_LAENGE_ARR; i++) {
    if(strcmp(bundesland,laender[i]) == 0 && bewohner[i] >= anzahl){
        int written = snprintf(p + offset, len - offset, Die Stadt %s hat %d Einwohner. \n", staedte[i], bewohner[i]);
        printf("%s : %d\n",staedte[i] , bewohner[i]);
        offset += written;
    }
}

I'm not sure why you're calling snprintf() twice. I removed the one that just writes to p.
Since the length of the p string is len bytes, you should use that when specifying the maximum amount to write in snprintf(), not MAX_LANGE_STR. You have to subtract offset from it, since each write is further in the string and there's less room left after it.


text:
Q: Remove border around JavaFX ScrollPane scroll bar when *not* focused I have a strange issue. I've styled the scroll-bar of my ScrollPane in JavaFX using CSS, but now every time the ScrollPane is in focus, the border disappears. However, if I click a button outside of the pane, it comes back.
Here are the images:
Unfocused

Focused

Here is the CSS:

.scroll-bar:horizontal .track,
.scroll-bar:vertical .track{
    -fx-background-color :transparent;
    -fx-border-color :transparent;
    -fx-background-radius : 2.0em;
}

.scroll-bar:horizontal .increment-button ,
.scroll-bar:horizontal .decrement-button {
    -fx-background-color :transparent;
    -fx-background-radius : 0.0em;
    -fx-padding :0.0 0.0 10.0 0.0;

}

.scroll-bar:vertical .track-background,
.scroll-bar:horizontal .track-background {
   -fx-background-color: transparent;
   -fx-background-insets: 0;
   -fx-background-radius: 2em;
}

.scroll-bar:vertical .increment-button ,
.scroll-bar:vertical .decrement-button {
    -fx-background-color :transparent;
    -fx-background-radius : 0.0em;
    -fx-padding :0.0 10.0 0.0 0.0;

}

.scroll-bar .increment-arrow,
.scroll-bar .decrement-arrow{
    -fx-shape : " ";
    -fx-padding :0.15em 0.0;
}

.scroll-bar:vertical .increment-arrow,
.scroll-bar:vertical .decrement-arrow{
    -fx-shape : " ";
    -fx-padding :0.0 0.15em;
}

.scroll-bar:horizontal .thumb,
.scroll-bar:vertical .thumb {
    -fx-background-color : #dddddd;
    -fx-background-insets : 2.0, 0.0, 0.0;
    -fx-background-radius : 2.0em;
}

.scroll-bar:horizontal .thumb:hover,
.scroll-bar:vertical .thumb:hover {
    -fx-background-color : #9e9e9e;
    -fx-background-insets : 2.0, 0.0, 0.0;
    -fx-background-radius : 2.0em;
}

.scroll-bar{
   -fx-background-color: transparent;
   -fx-background-radius: 2em;
   -fx-focus-color: transparent;
   -fx-faint-focus-color: transparent;
}

.scroll-bar:vertical:focused {
   -fx-background-color: transparent;
}

A: Try setting the -fx-focus-color and playing around with insets in the .scroll-bar class (the regular one, not the :focused pseudo-class):
.scroll-bar {
    -fx-focus-color: transparent;
    -fx-background-insets: -1.4, 0, 1, 2;
}


text:
Q: Getting the type of an array member from another type? (I'm having difficulty formulating the question correctly, I haven't found an answer elsewhere)
See below example:
export interface MasterProps {
  objects?: Array<{chart: ChartOpts} | {image: ImageOpts}>
}

I cannot touch the above definitions.
Now, I know I can get the type of the objects property by doing this:
   let obj: MasterProps['objects']

This will type obj as Array<{chart: IChartOpts} | {image: ImageProps}>
But how can I assign obj the type {chart: IChartOpts} | {image: ImageProps}?

A: separate the object type on its own and then you can make like this:
type obj = {
 chart: IChartOpts
} | {
 image: ImageProps
}

and then you can extract it easily like this:
export interface MasterProps {
  objects?: Array<obj>
}
let obj:obj


text:
Q: Knockout binding using object in data-bind i was trying to figure a way to bind some values as object to an element
It works if i do binding like this
var viewModel = {
    someObj: ko.observable(),
    textBox: {
        value: ko.observable('val'),
        attr: { title: 'Test', placeholder: 'Test' },
        style: { width: '100px' }
    }
}

<input type="text" data-bind="value: textBox.value, attr: textBox.attr, style: textBox.style />

But is there any way to bind like this
<input type="text" data-bind="bindFrom: textBox" />

I tried to create a customBinding "bindFrom" using ko.bindingHandlers
but dont know how to trigger these individual bindings manually.
Looking for some help!.
Thanks in advance.

A: after reading knockout.debug.js
i have created this custom binding
ko.bindingHandlers.bindFrom = {
    init: function (element, valueAccessor, allBindings) {
        var value = ko.utils.unwrapObservable(valueAccessor()) || {};
        ko.utils.objectForEach(value, function (bindName, bindValue) {
            bindObj = ko.bindingHandlers[bindName];
            ko.utils.objectForEach(bindObj, function (type, fn) {
                if (typeof fn == 'function')
                    fn(element, function () { return bindValue }, allBindings);
            });
        });
    }
};

which is working fine like expected.
check it out at JSFiddle


text:
Q: How to remove specific tags from with a DIV? Have found a mixed bag of solutions that don't seem to work.  I'm loading the HTML of a particular page, and want to extract the HTML from within an identified DIV - this works fine, but trying to remove an unidentified H3 tag from within the remaining HTML (and retain the following UL/LIs) seems to be impossible: I've tried everything Google has to offer, and can get either no results, or only the contents of the H3 tag.  I'm trying to get the HTML of the UL list, including the UL tags.
/* variable html is the result of an AJAX load of the web page of interest*/
/* I know the first line below is not correct */
/* but it demonstrates the chain of events that I'm trying to accomplish*/

var theStuffIWant = $(html).find("#tab-2").remove("h3").html();

Heading to get rid of

The list I want to keep

List item to keep

List item to keep

List item to keep

A: Since you're only concerned with the ul, skip the h3 and extract what only you want:
$('
').append($('#tab-2').find('ul')).html();

or
$('#tab-2').find('ul'); //to return them as a jQuery object.

A: See http://jsfiddle.net/ewjBp/
The remove() can't be used in chaining, because it returns the elements that were removed.
So you need to split: first remove the elements, then check the html() of the div, which was ridden of all h3.

Edit
http://jsfiddle.net/ewjBp/5/
So, first you create a new Jquery object by wrapping the html you want (e.g. $(html)).
As @pete stated, this won't be inserted into DOM. DOM is the in-memory representation of the page, accessible to Javascript, meaning that $(html) won't be added to the page structure representation.
Then just find the headers (with children()), and replace with nothing.
I suggest you read about replaceWith(), and the fact that it returns the old object instead. That's why I discard return value. It's not necessary, html will be changed anyway in the above code.
Also, html.html() discards the outer HTML element in html, which is the DIV container in this example.

A: Get an array of all H3s within that item, then loop through and remove them.
var eles = $("#tab-2").getElementsByTagName("h3");
for(var i in eles)
    $("#tab-2").removeChild(eles[i]);

A: I can't figure out how to comment on the previous but I'd suggest fully using JQuery's selectors:
$('#tab-2 h3').each(function(idx) {
    $(this).remove();
}

Code untested but you get the gist of it, I hope.


text:
Q: How can I force Netbeans to always open XML files in the text view? My work pc is the slowest machine on the planet.  It consistently takes SIX MINUTES to open a 13 line XML file (the persistence.xml).  I think it's because it's opening it in the XML editor mode and all I want to see is the text.
Is there a way to enforce this?
Thanks.

A: This question can be closed or deleted but I thought I would mention my solution.  Turns out, the corporate virus scanning is so strict around here that once I disabled real-time scanning, it went from 6 minutes to 5 seconds.  Yeah FSecure.


text:
Q: Cannot access class variable outside class - kivy Anytime i try to run my app i get error.
Error: AttributeError: 'NoneType' object has no attribute 'text'
See code snippet below
class Login(Screen):

    email_obj = ObjectProperty()
    password_obj = ObjectProperty()
    conn = lite.connect("database/nairamanager.db")
    cursor = conn.cursor()

    def init(self, **kwargs):
        super().__init__(**kwargs)

    # Display an alert on login validation
    def login_alert(self):
        p = LoginAlert()
        p.open()

    # Get user from database
    def login_nm_user(self):
        self.cursor.execute("SELECT * FROM user_tb WHERE email_db = ? AND password_db = ?;", (self.email_obj.text, self.password_obj.text))
        if self.cursor.fetchall():
            self.manager.current = "news_feed_screen"
        else:
            return self.login_alert()
            self.conn.commit()
            # self.conn.close

    # Get user email
    def get_user_email(self):
        self.cursor.execute("SELECT * FROM user_tb WHERE email_db = ?;", (self.email_obj.text))
        self.user_email = self.cursor.fetchone()[0]
        self.conn.commit()
        print(self.user_email)

login = Login()
login.get_user_email()
print(login.user_email)

.kv code
Below is the Login class in the kivy lang file
<Login>:

email_obj: email_text
password_obj: password_text

GridLayout:
    size: root.size
    rows: 2
    rows_minimum: {0:0,1:root.height*.7}
    spacing: 50
    GridLayout:
        rows: 2
        row_default_minimum: True
        rows_minimum: {0:root.height*.1,1:root.height*.01}
        BoxLayout:
            orientation: "horizontal"
            BackButton:
                text: "L"
                size_hint: (.1,1)
                halign: "center"
                markup: True
                on_press:
                    root.manager.current = "login_signup_screen"
                    root.manager.transition.direction = "left"
            TopLabel:
                text: "[b]Lets get you logged in...[/b]"
                size_hint: (.9,1)
        BorderLabel:

    # Login form
    BoxLayout:
        orientation: "vertical"
        spacing: 20
        UniTextInput:
            id: email_text
            hint_text: "Email"
            size_hint: (.6,1)
            pos_hint: {"center_x":.5}
        UniTextInput:
            id: password_text
            hint_text: "Password"
            password: True
            size_hint: (.6,1)
            pos_hint: {"center_x":.5}
        GreenButton
            id: main_login_button
            text: "Login"
            size_hint: (.6,1)
            pos_hint: {"center_x":.5}
            on_press:
                root.login_nm_user()
                root.get_user_email()

        # Fake widget for spacing
        Widget:
        Widget:
        Widget:

Please, how do i fix this?

A: To share a variable to all screens, you can make it an attribute of the screenmanager.
Like this:
from kivy.app import App
from kivy.uix.screenmanager import Screen, ScreenManager
from kivy.lang import Builder
from kivy.properties import StringProperty

class MyScreenManager(ScreenManager):
    user_email = StringProperty()

class Login(Screen):

    def login(self, user, pw):
        # login
        # if pass
        self.manager.user_email = user
        self.manager.current = "screen2"

root = Builder.load_string('''

MyScreenManager:

    Login:
        name: "login"
        id: login
        BoxLayout:

            orientation: 'vertical'

            TextInput:
                id: email_input
            TextInput:
                id: password_input
            Button:
                text: "Login"
                on_release: login.login(email_input.text, password_input.text)

    Screen:
        name: "screen2"
        BoxLayout:
            orientation: "vertical"
            Label:
                text: "Wellcome {}!".format(root.user_email)
            Button:
                text: "Go to screen 3"
                on_release: root.current = "screen3"

    Screen:
        name: "screen3"
        BoxLayout:
            orientation: "vertical"
            Label:
                text: "Wellcome {}!".format(root.user_email)
            Button:
                text: "Go back to screen 2"
                on_release: root.current = "screen2"

''')

class MyApp(App):

    def build(self):
       return root

MyApp().run()

That said, I see you define a init method. If you really want to overite the __init__, remember the underscores.
In this particular example, you dont really do anything in the init. super().__init__() gets executed anyways when you create a new Screen


text:
Q: Form in HTTP POST: Curl to pyCurl I am trying to transform following Curl fragment:
-F "model={
name: 'myapp',
targets: [ { identity: [ 'servers', 'server_name' ] } ]
}" \
-F "sourcePath=@/deployments/MyApp/app/MyApp.ear"

Into pyCurl:
targets_list = list()
targets_list.append(json.dumps({ 'identity': ['servers', 'server_name'] }, ensure_ascii=False))
model = json.dumps({"name": 'myapp', \
                            "targets": targets_list } )
sourcePath = "/deployments/MyApp/app/MyApp.ear"
send = [("model", model), ('sourcePath', \
                (pycurl.FORM_FILE, sourcePath)),]
curl_agent.setopt(pycurl.HTTPPOST, send)

But I am getting 500 HTTP Error:
{
    "detail": "JSONArray[0] is not a JSONObject.",
    "status": 500
}

The problem is definitely with the 'targets' list... Any ideas?
EDIT: Here's the full Python script:
import pycurl, json

url = "http://localhost:7001/some_context"
agent = pycurl.Curl()
agent.setopt(pycurl.POST, 1)
targets_list = list()
targets_list.append(json.dumps({ 'identity': ['servers', 'server_name'] }, ensure_ascii=False))
model = json.dumps({"name": 'myapp', \
                        "targets": targets_list } )
sourcePath = "/deployments/MyApp/app/MyApp.earr"
send = [("model", model), ('sourcePath', \
            (pycurl.FORM_FILE, sourcePath)),]
agent.setopt(pycurl.HTTPPOST, send)
agent.setopt(pycurl.URL, url)
agent.setopt(pycurl.HTTPHEADER, ['Accept: application/json',
                         'X-Requested-By:MyClient',
                         'Content-Type:multipart/form-data',
                         'Content-Length:'])
agent.setopt(pycurl.VERBOSE, 1)
agent.setopt(pycurl.USERPWD, "user:XXXXXX")
agent.perform()

A: Allright.
It should be:
targets_list.append({ 'identity': ['servers', 'server_name'] })

Instead of:
targets_list.append(json.dumps({ 'identity': ['servers', 'server_name'] }, ensure_ascii=False))

Now it works :)


text:
Q: Dictionary.ContainsKey() in C# is not finding a key in the Dictionary I am trying to write a class for privileges/permissions.
I am trying to use the Binary base permission System in C#.
I got it where I believe it should work. However, it is not working as expected.
After, I stepped thru my code I can see one issue in the method called _mapPermissions the line if (dic.ContainsKey(vv)) returns false every time.
the key is an instance of a class which have 2 values (ie. secionName, KeyIndex)
This is my entire class
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using MySql.Data.MySqlClient;

namespace POS
{
    class Roles
    {

        private Dictionary<PermissionsKey, int> systemPermissions = new Dictionary<PermissionsKey, int>();
        private Dictionary<PermissionsKey, int> userPermissions = new Dictionary<PermissionsKey, int>();

        public Roles()
        {
            this._getSystemPrivleges();
            this._getUserPrivleges();

            this._display(systemPermissions);
            this._display(userPermissions);

        }

        public bool hasAccess(string sectionName, string[] keys)
        {

            if (    this.systemPermissions.Count == 0
                 || this.userPermissions.Count == 0
                 || keys.Count() == 0
                 || String.IsNullOrEmpty(sectionName)
             )
            {
                return false;
            }

            int systemReq = this._mapPermissions(sectionName, keys, systemPermissions); ;
            int userPerm = this._mapPermissions(sectionName, keys, userPermissions);

            int check =  systemReq & userPerm;

            Common.Alert("System Value" + systemReq + Environment.NewLine +"User Value " + userPerm + Environment.NewLine + "AND Results " + check);

            if (check == 0)
            {
                return false;
            }

            return true;

        }

        private int _mapPermissions(string secName, string[] keys, Dictionary<PermissionsKey, int> dic)
        {

            int newKey = 0;
            var vv = new PermissionsKey();

            foreach (string k in keys)
            {
                vv.sectionName = secName;
                vv.KeyIndex = k;

                if (dic.ContainsKey(vv))
                {
                    newKey |= dic[vv] ;
                }
            }

            return newKey;
        }

        private void _getSystemPrivleges()
        {
            var db = new dbConnetion();

            string sql =   " SELECT SQL_CACHE "
                         + " KeyIndex, Value, sectionName "
                         + " FROM role_keys "
                         + " WHERE status = 'active' ";

            foreach (var i in db.getData(sql, null, r => new SystemPermissions()
                                                           {
                                                                 pIndex = r["KeyIndex"].ToString()
                                                               , pSec = r["sectionName"].ToString()
                                                               , pValue = r["Value"].ToString()
                                                           }
                                           )
                    )
            {

                var vv = new PermissionsKey();
                vv.sectionName = i.pSec;
                vv.KeyIndex = i.pIndex;
                systemPermissions.Add(vv, Convert.ToInt32(i.pValue));

            }
        }

        private void _getUserPrivleges()
        {
            var db = new dbConnetion();

            string sql = " SELECT SQL_CACHE k.sectionName, k.KeyIndex, k.value "
                        +" FROM users AS su "
                        +" INNER JOIN role_relation AS r ON r.roleID = su.roleID "
                        +" INNER JOIN role_keys AS k ON k.KeyID = r.KeyID "
                        +" WHERE su.status = 'active' AND su.userID = @userid ";

            var parms = new List<MySqlParameter>();
            parms.Add(new MySqlParameter("@userid", UserInfo.UserID));

            foreach (var i in db.getData(sql, parms , r => new SystemPermissions()
                                                            {
                                                                  pIndex = r["KeyIndex"].ToString()
                                                                , pSec = r["sectionName"].ToString()
                                                                , pValue = r["Value"].ToString()
                                                            }
                                           )
                    )
            {
                var vv = new PermissionsKey();
                vv.sectionName = i.pSec;
                vv.KeyIndex = i.pIndex;

                userPermissions.Add(vv, Convert.ToInt32(i.pValue));
            }
        }

        private void _display(Dictionary<PermissionsKey, int> dic)
        {
            string str = "";
            foreach (KeyValuePair<PermissionsKey, int> d in dic)
            {
                var vv = new PermissionsKey();
                var c = d.Key;

                str += c.sectionName + "_" + c.KeyIndex + "  =>  " + d.Value.ToString() + Environment.NewLine;

            }

            Common.Alert(str);
        }

        private int _BinToInt(string str)
        {
            Regex binary = new Regex("^[01]{1,32}$", RegexOptions.Compiled);
            int val = -1;

            if (binary.IsMatch(str))
            {
                val = Convert.ToInt32(str, 2);
            }

            return val;
        }

        private string _IntToBin(int number)
        {
            return Convert.ToString(number, 2);
        }

    }

    class SystemPermissions{
        public string pIndex;
        public string pSec;
        public string pValue;
    }

    class PermissionsKey
    {
        public string sectionName;
        public string KeyIndex;
    }
}

And I use this class like so
    var role = new Roles();
    string[] aa = { "view", "use" };

    if (role.hasAccess("system", aa))
    {
        Common.Alert("Welcome");
    }
    else
    {
        Common.Alert("NOP!");
    }

Note that the method Common.Alert() it simply display a Message (ie. MessageBox)
The above code displays the following when it runs
1) the content of the systemPermissions dictionary in the following order PermissionsKey.sectionName_PermissionsKey.KeyIndex => the value (ie. 1 , 2, 4, 8, 16, 32, 64 .....)
    system_do = > 1
    system_use => 2
    system_view => 4
    test_use => 1
    test_view => 2
2) The content of the usePermissions dictionary
system_do = > 1
test_use => 1

The issue is that the 2 variables systemReq  and userPerm return 0 every time. I am not sure why
 int systemReq = this._mapPermissions(sectionName, keys, systemPermissions); ;
 int userPerm = this._mapPermissions(sectionName, keys, userPermissions);

A: In order to use something as a dictionary key and expect it to follow you expectations of what is considered equals, you actually need to define what is considered the same.
In your PermissionsKey class, you do not override Equals, which means that the default Equals method is still in play (which is the object reference, and is unique for each specific object).
To fix, you need to actually tell the dictionary how to evaluate equality.  And anytime you override Equals, you also should also override GetHashCode:
class PermissionsKey
{
    private string sectionName;
    private string keyIndex;

    public string SectionName { get { return sectionName; } }
    public string KeyIndex { get { return keyIndex; } }

    public PermissionsKey(string sectionName, string keyIndex)
    {
        this.sectionName = sectionName;
        this.keyIndex = keyIndex;
    }

    public override bool Equals(object obj)
    {
        var key = obj as PermissionsKey;

        if (key == null)
            return false;

        return sectionName.Equals(key.sectionName) &&
               keyIndex.Equals(key.keyIndex);
    }

    //Credit to Jon Skeet from https://stackoverflow.com/questions/263400/what-is-the-best-algorithm-for-an-overridden-system-object-gethashcode
    //  for inspiration for this method
    public override int GetHashCode()
    {
        unchecked // Overflow is fine, just wrap
        {
            int hash = (int) 2166136261;
            // Suitable nullity checks etc, of course :)
            hash = hash * 16777619 ^ sectionName.GetHashCode();
            hash = hash * 16777619 ^ keyIndex.GetHashCode();
            return hash;
        }
    }
}

You are overriding Equals to actually define the equality comparison.  Anytime you try to compare 2 objects (specifically in the Dictionary object, but any other time you do it by calling .Equals), you should define your own comparison.  If you don't, then you are just using the default equality comparison, which is a pure objection comparison and 2 objects unless created from the same exact object will never be equals.
Similarly, when you override Equals, you are strongly advised to also override GetHashCode.  The HashCode defines which "bucket" the object falls into.  A good hashcode that follows the Equals implementation will help speed up comparisons by placing only objects with the same hash code into the same buckets.  The standard recommendation is 2 objects that are Equals will always have the same hashcode, but it is possible for 2 objects that are not equals to have the same hashcode.  Effectively it is a quick way for the framework to check for inequality.  If you get 2 different hashcodes, the framework knows the objects aren't equal, but if the hashcodes are the same, then it goes and checks equality.
If you can't or don't want to override Equals and GetHashCode, then you also have the option of definining an IEqualityComparer<T> in the constructor of the dictionary,
You just have to pass an object that implements IEqualityComparer<T> and within that object you can define the equality comparisons you want.
In addition, anything you plan to use as a dictionary key should never be mutable, specifically the fields that are used to calculate equality and calculate the hashcode, otherwise your keys can get lost as the hash code for the object does not match what was originally put into the dictionary.  I have modified your original example to change your fields in PermissionsKey to immutable properties and added a constructor to allow you to set them once when initially created.


text:
Q: keras with tensorflow : a CUDA runtime call was likely performed without using a StreamExecutor context I am using kears with tensorflow backend, and following is the problem. Is there any can solve this problem, thanks!

A: The error is caused by a illegal value of CNMEM. According to theano doc, CNMEM can only be assigned as a float.

0: not enabled.
0 < N <= 1: use this fraction of the total GPU memory (clipped to .95 for driver memory).
1: use this number in megabytes (MB) of memory.

You can also refer to here.
The warning is due to a change in Theano (Kera's backend). It will change from CUDA to GpuArray. You can refer to here for a solution.
Actually if you fix the warning, the error will disappear as well according to:

This value allocates GPU memory ONLY when using (CUDA backend) and has no effect when the GPU backend is (GpuArray Backend). For the new backend, please see config.gpuarray.preallocate


text:
Q: I would like only one application to run I have some Mining software called MinerGate and I would like it to use as much CPU as possible. So I would like to completely close out of all programs, apps, etc... that aren't required to run Ubuntu, to speed it up. How could I do this? I want as much possible to stop running. Also MinerGate is a GUI so can't cut that out.

A: Actually, it seems like MinerGate does have a command line interface:
https://es.minergate.com/faq/how-minergate-console
This way you won't even need a Desktop Environment. To avoid automatically starting the graphical interface, disable lightdm, it may vary from an Ubuntu version to another, but for 16.04 (and higher) sudo systemctl disable lightdm.service should do it.
If you are not satisfied, use ps -u $(whoami) to list your processes and use kill on any unnecessary process. Still not satisfied? ps -e will list all processes, just be extra cautious when killing processes owned by root. Daemons may need to be killed with systemctl.
Add in Shreyash S Sarnayak's suggestion to set a low nice value and you will get the most out of it.


text:
Q: issue when running cmder.exe from a java application I'm trying to run cmder.exe from a java application. I'm using the java ProcessBuilder class and it works great with cmd.exe, but never with cmder.exe.
This is my code:
    command =    "cd C:\\Users\\fxxx\\Documents\\plt 3.0\\git\\xxx-estatic";
    ProcessBuilder builder = new ProcessBuilder("C:\\PLT 3.0\\abc\\cmder_mini\\cmder.exe", "/start", command);

I want to open the cmder command prompt and run a "cd" command. Cmder.exe is actually launched, but I get the "file name, directory name or volume label syntax is incorrect" error message and my command (cd...) is never executed.
Again, things work perfectly if I use cmd.exe.
Does someone know how to effectively run cmder.exe from a java application?
Thanks a lot.

A: RTFM!
Assuming that you use that cmder.exe, the doc states:

Cmder.exe  Command Line Arguments

Argument                Description
/C [user_root_path]     Individual user Cmder root folder. Example: %userprofile%\cmder_config
/SINGLE                 Start Cmder is single mode.
/START [start_path]     Folder path to start in.
/TASK [task_name]       Task to start after launch.

That means that your code should be:
path =    "cd C:\\Users\\fxxx\\Documents\\plt 3.0\\git\\xxx-estatic";
ProcessBuilder builder = new ProcessBuilder("C:\\PLT 3.0\\abc\\cmder_mini\\cmder.exe", "/start", path);


text:
Q: Java card returns 0x6F00 on the calling point of a shared method I used this question's programs to test Shareable interface on my Java Card.
Just like the question I wrote an applet named Master with AID = 010203040101 and another one named Slave with AID =010203040202. These are the files:
MyShareableInterface.java :
package master;

import javacard.framework.Shareable;

public interface MyShareableInterface extends Shareable {
    public void ShareMethod();

}

Master.java :
package master;

import javacard.framework.APDU;
import javacard.framework.Applet;
import javacard.framework.ISOException;

public class Master extends Applet implements MyShareableInterface {

    private Master() {
    }

    public static void install(byte bArray[], short bOffset, byte bLength)
            throws ISOException {
        new Master().register();
    }

    public void process(APDU arg0) throws ISOException {

        if (selectingApplet()){
            ISOException.throwIt((short)0x9100);
        }
        ISOException.throwIt((short)0x9200);
    }

    public void ShareMethod() {
        ISOException.throwIt((short) 0x6103);
    }

}

Slave.java :
package slave;

import master.MyShareableInterface;
import javacard.framework.AID;
import javacard.framework.APDU;
import javacard.framework.Applet;
import javacard.framework.ISOException;
import javacard.framework.JCSystem;

public class Slave extends Applet {
    byte[] masterAppletAID={(byte)0x01,(byte)0x02,(byte)0x03,(byte)0x04,(byte)0x01,(byte)0x01};
     AID aid = JCSystem.lookupAID(masterAppletAID, (short)0, (byte)masterAppletAID.length);
     MyShareableInterface MasterShareableInterfaceInstance = (MyShareableInterface)JCSystem.getAppletShareableInterfaceObject(aid, (byte)0);

     private Slave() {
    }

    public static void install(byte bArray[], short bOffset, byte bLength)
            throws ISOException {
        new Slave().register();
    }

    public void process(APDU arg0) throws ISOException {
        if (selectingApplet()){
            ISOException.throwIt((short)0x9400);
            return;
        }
        MasterShareableInterfaceInstance.ShareMethod();

    }

}

Finally I convert these two applets to .cap files and upload them on my card successfully. I expect the card to have the below behavior:

*

*Return 0x9100 on reception of Master applet selection

*Return 0x9200 on reception of any other commands while Master is selected

*Return 0x9400 on reception of Slave applet selection

*Return 0x6103 on reception of any other commands while Slave is selected

But this is what I receive in above conditions:
OpenSC: OSC -s 00a4040006010203040101 -s 00000000 -s 00a4040006010203040202 -s 00000
000
Using reader with a card: ACS CCID USB Reader 0
Sending: 00 A4 04 00 06 01 02 03 04 01 01
Received (SW1=0x91, SW2=0x00)
Sending: 00 00 00 00
Received (SW1=0x92, SW2=0x00)
Sending: 00 A4 04 00 06 01 02 03 04 02 02
Received (SW1=0x94, SW2=0x00)
Sending: 00 00 00 00
Received (SW1=0x6F, SW2=0x00)

As you see above, the first three commands return the correct response, but the latter (calling SharedMethod) throws an 0x6F00 exception. Why?
Note that I tested the above .cap files with two different JavaCards (2.2.1 and 3.0.1) and both act similar.

A: Change status word 0x6103 to any other status word from the interval dedicated by ISO7816 (or ETSI if you write an applet for SIM card). Try using 0x9003 instead, for example.
http://www.cardwerk.com/smartcards/smartcard_standard_iso7816-4_5_basic_organizations.aspx
SW1 = 0x61 means there are still some response bytes available. SW2 indicates the number of these bytes. Some readers (and libraries) handle this status word by themselves and that can cause your troubles (you say there are 3 bytes available, although there is not a single one).

A: You receive the status word 0x6F00 because you get an unhandled null pointer exception at
MasterShareableInterfaceInstance.ShareMethod();

The reason for this null pointer exception is that MasterShareableInterfaceInstance is null.
You try to get an instance of the sharable interface through
(MyShareableInterface)JCSystem.getAppletShareableInterfaceObject(aid, (byte)0);

upon instantiating your applet object. Your approach does not work for multiple reasons. You have to make sure the following:

*

*the slave applet must already be registered when you invoke getAppletShareableInterfaceObject. You currently invoke this method in your applet constructor and hence call it before you call Applet.register(). So you have to make sure to use getAppletShareableInterfaceObject only after you called the register() method. So it may be a good idea to call this method directly from your process() method.

*the master applet is already registered when you call getAppletShareableInterfaceObject

*the master applet has to override the getShareableInterfaceObject method and return the shareable interface object (the default implementation will return null):
public Shareable getShareableInterfaceObject(AID clientAID, byte parameter)

This method allows the master applet to decide if it will allow the client applet to use the shareable interface. As your master applet does not implement this method, sharing is denied by default.


text:
Q: Is there a way to update the same variable inside a loop in Mongo Db Is there a way to update the same variable inside a loop in Mongo Db
{
    $project : {
        "taxedData":{
                 $map:
                  {
                     input: "$rateTaxLevel",
                     as: "taxIds",
                     in: {
                                $map:
                                {
                                input: "$taxValidity",
                                as: "levels",
                                in: {

                                    chargeAmount:
                                    {
                                        $cond: [ { $eq: [ "$$taxIds.taxid", "$$levels.taxid" ] },
                                        { $divide: [ "$chargeAmount",{ $add: [ 1, "$$levels.tax_validityval" ]} ] }
                                        , "$$REMOVE" ]
                                    }
                                    }
                                }

                          }
                  }
         }
    }
}

How can I carry forward the $chargeAmount variable to the next iteration of the loop


text:
Q: How To perform calculations on array and show it in tabular form I have an assignment regarding multiplication of array and show it in tabular form, my teacher just give me the data that is in the array form and said to display it in tabular form and also multiply the items **Quantity and price ** and show it in table ....i already have display the array in tabular form but i'm unable to product the QTY and price? anybody help ?

<!doctype html>

    <meta charset="utf-8">
<title>Untitled Document</title>

<?php
$ProductsTest = array("1001" => array("Name" => "LCD","Desc" => "Sony","Qty" =>10,"Price" => 2000),
"1002" => array("Name" => "Mouse","Desc" => "Dell","Qty" =>3,"Price" => 300),
"1003" => array("Name" =>"Mouse","Desc" =>"a4Tech","Qty" =>3,"Price" =>300),
"1004" => array("Name" =>"USB","Desc" =>"Kingstton","Qty" =>15,"Price" =>700),
"1005" => array("Name" =>"HeadPhone","Desc" =>"a4Tech","Qty" =>7,"Price" =>3000));
$no_of_ele = count($ProductsTest);
echo '

';
echo '

 Name
    Brand
     QTY
    price
    totalamount

';
foreach( $ProductsTest as $values)
{
    echo '
';
    foreach( $values as $key )
    {
        echo ''.$key.'	';
  }
    echo '
';
}

echo '
';
?>

this is my output till now

A: <?php
$ProductsTest = array("1001" => array("Name" => "LCD","Desc" => "Sony","Qty" =>10,"Price" => 2000),
"1002" => array("Name" => "Mouse","Desc" => "Dell","Qty" =>3,"Price" => 300),
"1003" => array("Name" =>"Mouse","Desc" =>"a4Tech","Qty" =>3,"Price" =>300),
"1004" => array("Name" =>"USB","Desc" =>"Kingstton","Qty" =>15,"Price" =>700),
"1005" => array("Name" =>"HeadPhone","Desc" =>"a4Tech","Qty" =>7,"Price" =>3000));
$no_of_ele = count($ProductsTest);
?>

 Name
    Brand
     QTY
    price
    totalamount

<?php
foreach( $ProductsTest as $key => $value)
{
    echo '
';
    echo ''.$value['Name'].'	';
    echo ''.$value['Desc'].'	';
    echo ''.$value['Qty'].'	';
    echo ''.$value['Price'].'	';
    echo ''.$value['Qty']*$value['Price'].'	';
    echo '
';
}
?>

A:     <!doctype html>

    <meta charset="utf-8">
    <title>Untitled Document</title>

    <?php
    $ProductsTest = array(
    "1001" => array("Name" => "LCD", "Desc" => "Sony", "Qty" =>10, "Price" => 2000),
    "1002" => array("Name" => "Mouse","Desc" => "Dell","Qty" =>3,"Price" => 300),
    "1003" => array("Name" =>"Mouse","Desc" =>"a4Tech","Qty" =>3,"Price" =>300),
    "1004" => array("Name" =>"USB","Desc" =>"Kingstton","Qty" =>15,"Price" =>700),
    "1005" => array("Name" =>"HeadPhone","Desc" =>"a4Tech","Qty" =>7,"Price" =>3000)
    );

    $no_of_ele = count($ProductsTest);

    echo '

';

    if( $no_of_ele > 0 )
    {
    echo '

    Name
    Brand
    QTY
    price
    totalamount

';

    foreach( $ProductsTest as $key_ProductsTest => $value_ProductsTest)
    {
    echo '
';
    echo ''.$value_ProductsTest["Name"].'	';
    echo ''.$value_ProductsTest["Desc"].'	';
    echo ''.$value_ProductsTest["Qty"].'	';
    echo ''.$value_ProductsTest["Price"].'	';
    echo ''. ($value_ProductsTest["Qty"] * $value_ProductsTest["Price"]) .'	';
    echo '
';
    }

    echo '
';
    }
    else
    {
    echo "Sorry, no data found.";
    }

    ?>

A: This is a good soluction for this problem using functional programming you can map the array to return other array with the totalamount
    <!doctype html>

        <meta charset="utf-8">
    <title>Untitled Document</title>

    <?php
    $lists = array("1001" => array("Name" => "LCD","Desc" => "Sony","Qty" =>10,"Price" => 2000),
    "1002" => array("Name" => "Mouse","Desc" => "Dell","Qty" =>3,"Price" => 300),
    "1003" => array("Name" =>"Mouse","Desc" =>"a4Tech","Qty" =>3,"Price" =>300),
    "1004" => array("Name" =>"USB","Desc" =>"Kingstton","Qty" =>15,"Price" =>700),
    "1005" => array("Name" =>"HeadPhone","Desc" =>"a4Tech","Qty" =>7,"Price" =>3000));

    $ProductsTest  = array_map(function($item){
        $item['totalamount'] = $item['Qty'] * $item['Price'];
        return $item;
    },$lists);
$no_of_ele = count($ProductsTest);
    echo '

';
    echo '

     Name
        Brand
         QTY
        price
        totalamount

';
    foreach( $ProductsTest as $values)
    {
        echo '
';
        foreach( $values as $key )
        {
            echo ''.$key.'	';
        }
        echo '
';
    }

    echo '
';
    ?>


text:
Q: Cannot place ajax call within jQuery Dialog button function. Returns null I need to confirm the user wants to really submit a form via a jQuery dialog button. I tried to place my ajax function inside my "Confirm" function, but it returned NULL.
How can I call the ajax function only if they click "Confirm"?
Here I have my dialog div:
echo "

Are you sure you wanna do that?

All records will be removed!

";

Here I initialize my dialog
//Confirmation dialog
    $('#dialog_confirm').dialog({
        autoOpen: false,
        modal: true,
        draggable: false,
        resizable: false,
        show: {
            effect: "blind",
            duration: 500
        },
        hide: {
            effect: "fade",
            duration: 500
        },
        buttons: {
            "Confirm": function () { //Tried to place my ajax function
                                     //here but it returned null
                $(this).dialog('close');
                $('#remove_domain_form')[0].reset();
            },
            "Cancel": function () {
                $(this).dialog('close');
            }
        }
    });

My form submit function:
 $('#remove_domain_form').submit(function (e) {
    e.preventDefault();
    var isEmpty = false;
    $(':input:not(button)').each(function () {
        if ($(this).val() === "") {
            var error_text = $('#dialog p').text("All fields are required");
            $('#dialog').html(error_text);
            $('#dialog').dialog('option', 'title', 'Error').dialog('open');
            isEmpty = true;
        }
        else {
            $('#dialog_confirm').dialog('open');
        }
    });
    if (!isEmpty) {
        // <------ I NEED TO HAVE THE CONFIRMATION DIALOG HERE
        console.log("Not Empty");
        $.ajax({
            url: "check-domain-remove.php",
            type: "post",
            dataType: 'json',
            data: $('#remove_domain_form').serialize(),
            success: function (response) {
                if (response === "Success") {
                    //DO OTHER STUFF
                    var success_div = '
Domain Successfully Removed

';
                    $('body').append(success_div);
                }
            }

        });
    }
});

Edit: I also tried to place it in a function that fires on the close/Confirm event, still to no avail. If I click "Confirm," it returns null. If I click "Cancel," I get the correct results! This is so strange, and I don't know why it is happening.
$('#dialog_confirm').bind('dialogclose', function(event, ui) {
        if($(event.target).text() != 'Cancel') {
            console.log("Clicked Confirm");
            $.ajax({
                url: "check-domain-remove.php",
                type: "post",
                dataType: 'json',
                data: $('#remove_domain_form').serialize(),
                success: function (response) {
                    if (response === "Success") {
                        //DO OTHER STUFF
                        var success_div = '
Domain Successfully Removed

';
                        $('body').append(success_div);
                    }
                }

            });
        }
    });

A: This might have something to do with the element not being present when jQuery is loaded. Try changing your code to this:
$(document).on('submit', '#remove_domain_form', function (e) {...})

A: OK so do this:
$('#yourFirstButton').on('click', function (e) {
    e.preventDefault();
    $(':input:not(button)').each(function () {
        if ($(this).val() === "") {
            var error_text = $('#dialog p').text("All fields are required");
            $('#dialog').html(error_text);
            $('#dialog').dialog('option', 'title', 'Error').dialog('open');
            return false;
        }
        else {
            $('#dialog_confirm').dialog('open');
        }
    });
});

$('#yourConfirmButton').on('click', function(){
    $('#remove_domain_form').submit(
        // <------ I NEED TO HAVE THE CONFIRMATION DIALOG HERE
        console.log("Not Empty");
        $.ajax({
            url: "check-domain-remove.php",
            type: "post",
            dataType: 'json',
            data: $('#remove_domain_form').serialize(),
            success: function (response) {
                if (response === "Success") {
                    //DO OTHER STUFF
                    var success_div = '
Domain Successfully Removed

';
                    $('body').append(success_div);
                }
            }
        });
    )
});

So the validation breaks at return false and then proceeds with the ajax call afterwards if it passes.

A: Ok, I figured it out. I needed (for some reason I don't yet know) to add empty click functions in my dialog initialization. I am now able to submit the form and get the dialog. If I click Cancel, it closes. If I click Confirm, the ajax returns what I need.
Keith, your suggestion to create the click function was almost what I needed. I just needed to add the click functions.
$('#dialog_confirm').dialog({
        autoOpen: false,
        modal: true,
        draggable: false,
        resizable: false,
        show: {
            effect: "blind",
            duration: 500
        },
        hide: {
            effect: "fade",
            duration: 500
        },
        buttons: {
            'Confirm' : {
                text:'Confirm',
                id:'confirm_button',
                click:function() {
                    $(this).dialog('close');
                }
            },
            'Cancel' : {
                text:'Cancel',
                id:'cancel_button',
                click:function() {
                    $(this).dialog('close');
                }
            }
        }
    });

$('#remove_domain_form').submit(function (e) {
    e.preventDefault();
    //var isEmpty = false;
    $(':input:not(button)').each(function () {
        if ($(this).val() === "") {
            var error_text = $('#dialog p').text("All fields are required");
            $('#dialog').html(error_text);
            $('#dialog').dialog('option', 'title', 'Error').dialog('open');
            return false;
        }
        else {
            $('#dialog_confirm').dialog('open');
        }
    });

    $('#confirm_button').click(function() {
        console.log("Not Empty");
        $.ajax({
            url: "check-domain-remove.php",
            type: "post",
            dataType: 'json',
            data: $('#remove_domain_form').serialize(),
            success: function (response) {
                if (response === "Success") {
                    //DO OTHER STUFF
                    var success_div = '
Domain Successfully Removed

';
                    $('body').append(success_div);
                }
            }

        });
    });
});


text:
Q: Queuing installations via Process.Start I need to queue approximately 20 installations that are fully unattended (Using a C# winform application). Each installation has its own INI file (that is manually created) that contains the proper information on what arguments each installer requires for this procedure (read in before that program is executed).   I'm running into issues with many application that when the setup.exe is executed the process closes immediately and launches its MSI (if applicable), causing my procedure to carry out with the next installation assuming that the first is complete. I have read similar problems snooping around the web, but no real solution on the issue... (some workarounds included using a batch file with the /Wait option which should have kept the setup.exe in memory until its MSI has completed). The setup.exe must be launched due to the fact that they contain bootstrappers.
What options do i have to resolve this dilemma?
Here is some sample code that demonstrates the procedure:
            foreach (ListViewItem itm in this.lstSoftwares.Items)
            {
                try
                {
                    if (itm.Checked)
                    {
                        lblStatus.Text = "Status: Installing " + current.ToString() + " of " + count.ToString();

                        string InstallPath = Path.Combine(Application.StartupPath, "Software",
                        itm.Text, itm.Tag.ToString());

                        string CommandLine = itm.SubItems[1].Text;

                        Process process = new Process();
                        process.StartInfo.FileName = InstallPath;
                        process.StartInfo.Arguments = CommandLine;

                        process.StartInfo.WindowStyle = ProcessWindowStyle.Normal;
                        process.Start();
                        process.WaitForExit();
                        this.lstSoftwares.Items[i].SubItems[2].Text = "Complete";
                        current++;
                    }

Update
right after waitforexit() i'm using a loop that checks if the msiexec is running:
    private bool MSIRunning()
    {
        try
        {
            using (var mutex = Mutex.OpenExisting(@"Global\_MSIExecute"))
            {
                return true;
            }

        }
        catch (Exception)
        {
            return false;
        }
    }

this is a hack in my opionion, but doing the trick so far...

A: Querying the MSI Mutex after process.start in a loop (check if Mutex is running every 3 seconds, if not return and proceed with next install) seemed to solve the problem (Noted above).

A: Already answered, but I have a slightly more robust implementation of the MSI mutex check:
public bool IsMsiExecFree(TimeSpan maxWaitTime)
{
    _logger.Info(@"Waiting up to {0}s for Global\_MSIExecute mutex to become free...", maxWaitTime.TotalSeconds);

    // The _MSIExecute mutex is used by the MSI installer service to serialize installations
    // and prevent multiple MSI based installations happening at the same time.
    // For more info: http://msdn.microsoft.com/en-us/library/aa372909(VS.85).aspx

    const string installerServiceMutexName = "Global\\_MSIExecute";
    Mutex msiExecuteMutex = null;
    var isMsiExecFree = false;

    try
    {
        msiExecuteMutex = Mutex.OpenExisting(installerServiceMutexName,
            MutexRights.Synchronize);
        isMsiExecFree = msiExecuteMutex.WaitOne(maxWaitTime, false);
    }
    catch (WaitHandleCannotBeOpenedException)
    {
        // Mutex doesn't exist, do nothing
        isMsiExecFree = true;
    }
    catch (ObjectDisposedException)
    {
        // Mutex was disposed between opening it and attempting to wait on it, do nothing
        isMsiExecFree = true;
    }
    finally
    {
        if (msiExecuteMutex != null && isMsiExecFree)
            msiExecuteMutex.ReleaseMutex();
    }

    _logger.Info(@"Global\_MSIExecute mutex is free, or {0}s has elapsed.", maxWaitTime.TotalSeconds);

    return isMsiExecFree;
}