text:
Q: json sent to view but not able to take id from it jade template Please help me solve this. I'm new to node as well as json.
Something must have gone terribly wrong.
extends layout

block content
  h3 Trips selection #{trips}  //shows following json in the view
  form.form-horizontal(id="Findtrips", accept-charset="UTF-8",
  action="#", method="post" enctype="multipart/form-data")
    each trip in trips
      p #{trip.tripId} //doesnt pusblish anything

#{trips} gives following:
{
  "onwardTrips": [{
    "tripId": "1285170",
    "fromCity": "Singapore",
    "toCity": "Malacca",
    "operatorCode": "SA",
    "operatorName": "Starmart Express",
    "departTime": "2014-01-20 20:00:00.0",
    "busType": "Executive",
    "pickupPointDetails": [{
      "pickupPointId": "78",
      "departureTime": "2014-01-20 20:00:00.0",
      "pickupPointName": "Golden Mile Tower, Beach Road"
    }],
    "dropoffPointDetails": [{
      "dropOffPointName": "Melaka Sentral",
      "dropOffPointId": "1285170"
    }],
    "fareDetails": {
      "adultFare": "65.0"
    }
  },
  {
    "tripId": "1285254",
    "fromCity": "Singapore",
    "toCity": "Malacca",
    "operatorCode": "SA",
    "operatorName": "Starmart Express",
    "departTime": "2014-01-20 23:00:00.0",
    "busType": "Executive",
    "pickupPointDetails": [{
      "pickupPointId": "78",
      "departureTime": "2014-01-20 23:00:00.0",
      "pickupPointName": "Golden Mile Tower, Beach Road"
    }],
    "dropoffPointDetails": [{
      "dropOffPointName": "Melaka Sentral",
      "dropOffPointId": "1285254"
    }],
    "fareDetails": {
      "adultFare": "65.0"
    }
  }],
  "errorCode": 0
}

server.js
getTrips: function getTrips(req, res, next){
     var url = 'CTB-WS/rest/trips?from='+ req.tripinfo.fromCityId + '&to=' + req.tripinfo.toCityId + '&depart-date=' + req.tripinfo.departDate+ '&pax=1';
     console.log(url);
     rest.get(url).on('complete', function(trips) {
      if (trips instanceof Error) {
        console.log('Error:', trips.message);
        } else {
          console.log('trips'+ JSON.stringify(trips));
          req.trips = JSON.stringify(trips);
          next();

        }
    });
  },

  sendTrips: function sendTrips(req, res, next){
    res.render('trips', {trips : req.trips});
  }

A: In your json(actually Javascript object), trips is not an array. Instead trips.onwardTrips is an array.
Please change each in jade like
if trips.onwardTrips
  each trip in trips.onwardTrips
    p #{trip.tripId}

A: solved it by following. I got trips.tripId now I want to get array inside trip i.e. dropoffPointDetails.
 getTrips: function getTrips(req, res, next){
     var url = 'CTB-WS/rest/trips?from='+ req.tripinfo.fromCityId + '&to=' + req.tripinfo.toCityId + '&depart-date=' + req.tripinfo.departDate+ '&pax=1';
     console.log(url);
     rest.get(url).on('complete', function(trips) {
      if (trips instanceof Error) {
        console.log('Error:', trips.message);
        } else {
          console.log('trips'+ JSON.stringify(trips));
          trips = trips || [];
          req.trips = trips['onwardTrips'];
          next();
        }
    });
  },

  sendTrips: function sendTrips(req, res, next){
    //res.render('trips', {trips : req.trips});
   res.render('trips', { trips: req.trips});

  }


text:
Q: Comparing two consecutive rows in the table and ignoring the results if the condition is fulfilled I have one problem with comparing values in a table in MSSQL database.
One column (let's say it's called ID) contains integer values - those values are supposed to be consecutive. The other column contains location ID info. Now there is one other column that contains info whether the product has failed quality check (binary value - 0 or 1).
Now what I am trying to do is to compare two consecutive rows, find out if values in ID column are consecutive as well and select those location IDs which haven't got consecutive values in ID columns only IF quality check column has value 0. If it is 1 I want my query to sort of jump to the next row and compare the next row with the previous one.
So to sum it up I want to select only those locationIDs from the table which do not have consecutive ID values for quality check set at 0 (if its 1 and not consecutive - ignore the result)
I was thinking about using cursor for this one but I am not quite sure, I would highly appreciate if someone could point me in the right direction (preferably with some example). Thanks!

A: You can do this using lag().  I think it is something like this:
select t.*
from (select t.*,
             lag(id) over (order by id) as prev_id,
             lag(info) over (order by id) as prev_info
      from t
     ) t
where id <> prev_id + 1 and prev_info = 0 and info = 0;

This returns the row following the gap.

A: select t.*
from (select t.*,
             lag(id) over (order by id) as prev_id
      from t
      where info = 0
     ) t
where id > prev_id + 1
order by id

redpajama_set_name: RedPajamaStackExchange


text:
Q: Stop AngularJS adjusting dates for timezone? I'm stuck in an awkward situation where I have to send date/times over the wire without timezone information - to put it simply, the timezone information isn't collected at the time of data-entry and therefore isn't accessible.
This means I have date/times that I just want to echo out exactly as they arrive over the wire, without any accounting for timezone.  I've noticed that AngularJS seems to be automatically assuming the dates are UTC, and is applying a timezone transformation to the data as it arrives, so I'm getting 9am being translated into 8pm AEDT.
Is there a way I can disable this behavour and just have the dates remain exactly as they arrive?
Specifically I'm referring to the $http.get() method. By the time I get access to the returned data it has already been transformed:
$http.get('url')
    .success(function (data) {
        console.log(data);
    });

This will log the transformed dates, so I need to somehow jump in the middle there and stop Angular from transforming the dates.

A: A simple solution would be to just treat the dates as normal strings.
Or you can create proper data objects from the partial data strings by adding your desired timezone and then printing them (or whatever you need to do with them).


text:
Q: Get non empty values of dataframe as a single column I have a sparse dataframe and would like to get all non empty values as a single column. See the image that I made up to illustrate the problem. I somehow managed to solve it using the python code below. However, I feel there migh be some better | simpler | efficient way to solve it

import pandas as pd

list1 = ["x1","x2","?","?","?","?"]
list2 = ["?","?","y1","y2","?","?"]
list3 = ["?","?","?","?","z1","z2"]

df_sparse = pd.DataFrame({"A":list1,"B":list2,"C":list3})
values_vect = []
for col in df_sparse.columns:
  values = [ i for i in list(df_sparse[col]) if i !="?"]
  values_vect.extend(values)
df_sparse["D"] = pd.DataFrame(values_vect,columns=["D"])
display(df_sparse)

A: df_sparse["D"] = df_sparse.replace("?", np.nan).ffill(axis="columns").iloc[:, -1]

*

*replace "?"s with NaNs

*forward fill the values along columns so that non-NaN values will slide to the rightmost positions

*query the rightmost column, that's where the values are

to get
>>> df_sparse

    A   B   C   D
0  x1   ?   ?  x1
1  x2   ?   ?  x2
2   ?  y1   ?  y1
3   ?  y2   ?  y2
4   ?   ?  z1  z1
5   ?   ?  z2  z2

A: Using masking, stack and groupby.last:
df_sparse['D'] = (df_sparse
 .where(df_sparse.ne('?'))
 .stack()
 .groupby(level=0).last()
 )

print(df_sparse)

Output:

    A   B   C   D
0  x1   ?   ?  x1
1  x2   ?   ?  x2
2   ?  y1   ?  y1
3   ?  y2   ?  y2
4   ?   ?  z1  z1
5   ?   ?  z2  z2


text:
Q: JWPlayer error codes list I want to use onError for accurate error handling. JWPlayer documentation gives a list of errors https://support.jwplayer.com/customer/portal/articles/1403682-troubleshooting-your-setup. But these errors don't have codes with them. Does anyone have a concise list of possible error codes generated by JWPlayer upon failure?

A: I reach out to JWPLayer regarding this concern since we struggled with the same issues not being able to handle errors correctly. The response was not really satisfying but understandable:

We don't have a formal list of errors since errors can happen on many levels (for example, errors with our SDK initialization, errors during playback due to the video file itself, errors related to retrieving the video file from your server, etc.)
  I would also like to point out that the error delegates methods that I shared with you have error parameters that are of type NSError. This means that you can localize the error and get more information that way.
  However, I would of course be happy to decipher any error that may arise.
  -Daniel

What I ended up was listening to the three delegates onError, onSetupError and onAdError. This helps debugging. If it is an option you can react appropriately there. If you want a first list you should look at apples documentation of the AVPlayer: Link. This is the underlying player.


text:
Q: wget downloads only 5 bytes file I've got the following issue - the wget command downloads only 5bytes of files on the remote server I need to access.
I know, that the files have 5MB and 1.3MB, so why after wget'ing them i receive only 5b empty files?
===EDIT===
root@app:# wget -c -v XXX.X.X.XXX:139/dbase/dispense.log
--2013-03-28 09:10:27--  http://XXX.X.X.XXX:139/dbase/dispense.log
Connecting to XXX.X.X.XXX:139... connected.
HTTP request sent, awaiting response... 200 No headers, assuming HTTP/0.9
Length: unspecified
Saving to: `dispense.log'

    [ <=>                                   ] 5           --.-K/s   in 0s

2013-03-28 09:10:27 (846 KB/s) - `dispense.log' saved [5]

A: wget only supports HTTP, HTTPS and FTP protocols. You are using port 139 which is normally not a port such a protocol is run over.
If you're trying to download a file from a Samba/Windows network share, have a look at mount.cifs.


text:
Q: How to run selenium 2.0 script in jenkins I have selenium webdriver script, and i want to run the script in jenkins. how to configure in jenkins. what steps i need to fallow? i am new to jenkins, can any one tell me the step by step procedure to fallow.

A: If you're running Jenkins on a unix machine, create a new job:
 Click on New Job, Type a name and click on Build a free-style software project
Then add a 'build' step called 'Execute shell'. (For windows you can use Windows Batch command).
Using that you can run the selenium standalone server jar to execute the your selenium script.
For example:
java -version && java -jar /Applications/SeleniumRC/selenium-server-standalone-2.12.0.jar -trustAllSSLCertificates -htmlSuite "*googlechrome" "https://user:password@www.example.com/" "examplesuite.html" "result_file.html"
Other option would be to go to Configure Jenkins -> Configure Plugins and install Hudson Seleniumhq plugin and use the build step provided by them when configuring the jenkins job.
You might also want to create a Post-build Action to show reports. If you install Selenium HTML report plugin from the aforementioned Manage Plugins page, you can then add 'Publish selenium report' Post-build step.


text:
Q: How to add a role with a Discord Bot I start creating a Discord bot with the Python API of Discord. So, I tried to make a command that give roles on a discord server. Here is my code :
client = commands.Bot(command_prefix = '/')

@client.command()
async def addrole(ctx, role: discord.Role, user: discord.Member):
    if ctx.author.guild_permissions.administrator:
        await user.add_roles(role)
        await ctx.send(f"Successfully given {role.mention} to {user.mention}.")

When I try to use the command, any error happear. I try to make like the websearch I've done but still don't work. Can someone help me ?

A: I don't believe basic things like these would require Discords intents, especially the "member intent". What I have done is I've cleaned up your code and required a member to be passed before a multiple string role, if needed.
@client.command()
@commands.has_permissions(manage_roles=True)
async def addrole(ctx, member: discord.Member = None, *, role: discord.Role = None):
        if role == None:
                await ctx.send(f'Provide a role to add')
                return

        if member == None:
                await ctx.send(f'Provide a member to add a role')
                return

        await member.add_roles(role)
        await ctx.send(f"Successfully added role, {role} to {member.name}")


text:
Q: Convert list to list of dictionaries in python I have two python lists like the following:
fruits = ["apple", "banana", "guava", "grapes"]
colour = ["red", "yellow", "green", "black"]

I wish to convert them into a dictionary of the following format:
dictionary = [{"fruit":"apple", "colour":"red"},{"fruit":"banana", "colour":"yellow"}...]

A: Zip your fruit and colour lists together using the zip() function, and build a new dictionary from each pair:
[{'fruit': f, 'colour': c} for f, c in zip(fruits, colour)]

This uses a list comprehension to create the list output from a loop.
Demo:
>>> fruits = ["apple", "banana", "guava", "grapes"]
>>> colour = ["red", "yellow", "green", "black"]
>>> [{'fruit': f, 'colour': c} for f, c in zip(fruits, colour)]
[{'colour': 'red', 'fruit': 'apple'}, {'colour': 'yellow', 'fruit': 'banana'}, {'colour': 'green', 'fruit': 'guava'}, {'colour': 'black', 'fruit': 'grapes'}]

A: A good solution I found is to use an external CSV file to manage your dictionary
for example the dict.csv is the directry of the csv file
import csv
import os

dictionary = os.getcwd() +  r'\dict.csv'
with open(dictionary, mode='r') as infile:
        reader = csv.reader(infile)
        mydict = {rows[0]:rows[1] for rows in reader}

and in the csv file can have first column as fruits second column as color. Easy to modify and manage


text:
Q: Remove model name from submitted form url (GET) Here's my form
         <?php $form=$this->beginWidget('booster.widgets.TbActiveForm',array(
                    'id'=>'listing-main-form',
                    'enableAjaxValidation'=>false,
                    'action'=>Yii::app()->createUrl('site/search'),
                    'method'=>'get',
                )); ?>

                    Type
                     <?php echo $form->dropDownListGroup(
                            $model,
                            'prp',
                            array(
                                'wrapperHtmlOptions' => array(
                                    'class' => 'col-sm-5',
                                ),
                                'widgetOptions' => array(
                                    'data' => CHtml::listData(Type::model()->findAll(), 'id', 'type'),
                                    'htmlOptions' => array('id'=>'selecttype'),
                                ),
                                'label' => ''
                            )
                        ); ?>

                    <?php echo $form->checkboxListGroup(
                        $model,
                        'rs',
                        array(
                            'widgetOptions' => array(
                                'data' =>CHtml::listData(ResourceCategory::model()->findAll(), 'id', 'res_category'),
                            ),
                           'label' => ''
                        )
                    ); ?>

............
............

When the form is submitted, I can read all the field's data fine. But the url appears with Model[field] for each fields and looks very ugly (see below). Is there any where I can remove the model name from there?
index.php?r=site/search&ItemModel[prp]=1&ItemModel[rs]=&ItemModel[rs][]=2&ItemModel[rs][]=3&ItemModel[rs][]=4&ItemModel[cm] ............

A: You can explicitly set input name.
...
'htmlOptions' => array(
    'id'=>'selecttype',
    'name' => 'fieldname'
)
...

Also you can override CHtml and CActiveForm classes.

A: In your array for each element, add
'name'=>'your_custom_name'

So...
<?php echo $form->dropDownListGroup(
                            $model,
                            'prp',
                            array(
                                'wrapperHtmlOptions' => array(
                                    'class' => 'col-sm-5',
                                ),
                                'widgetOptions' => array(
                                    'data' => CHtml::listData(Type::model()->findAll(), 'id', 'type'),
                                    'htmlOptions' => array('id'=>'selecttype'),
                                ),
                                'label' => '',
                                'name' => 'customName'
                            )
                        ); ?>


text:
Q: Ionic unfocus searchbar placeholder to align left I would like to know if it's possible to align Ionic searchbar placeholder to the left side when unfocus?

as of right now the placeholder is currently centered when unfocus
HTML
<ion-searchbar
  slot="bottom"
  mode="ios"
  autocomplete="off"
  autocorrect="off"
  spellcheck="false"
  animated="true"
  debounce="500"
  clearIcon="close"
  [placeholder]="placeholder"
  [(ngModel)]="search"
  (ionChange)="runSearch()"
></ion-searchbar>

CSS
ion-searchbar {
  height: 40px;
  padding: 0px;
  border: 1px solid rgba(0, 56, 100, 0.4);
  box-shadow: none !important;
  border-radius: 6px;
  margin: 8px 0 12px;
  --border-radius: 6px;
  --background: white;
  --placeholder-color: red;

  text-align: start !important; // not working
  text-align: left !important; // not working
  align-items: flex-start; // not working

  &::placeholder {
    text-align: left; // not working
  }
}

A: As of right now (Ionic 4) the solution I found is to add in app.scss
// Force align searchbar text left
ion-searchbar {
  .searchbar-search-icon.sc-ion-searchbar-ios.ios.hydrated{
    margin-left: 0 !important;
  }
  .searchbar-input.sc-ion-searchbar-ios {
    padding-left: 30px !important;
  }
}

this will force the placeholder & icon align to the left corner when unfocused.

A: Small Update to evans answer that works for Ionic React Apps
Place code at top of variables.css

ion-searchbar {
  --background: "black"
}

.searchbar-search-icon.sc-ion-searchbar-ios {
  margin-left: 0 !important;
}
.searchbar-input.sc-ion-searchbar-ios {
  padding-left: 30px !important;
}


text:
Q: Query a list of objects that contains any string I'm this expression to search inside a list of objects by a specific property:
var result = myObject.Where(o => o.SearchString.Contains(searchValue));

It works good for a single value. The searchValue is a string passed by the user. The user can pass a single word or many words separeted by spaces. Is there any way to filter the objects that contains any of the passed words?
I could do this with a loop, searching a new word in previous results, but it doesn't seem very elegant.

A: myObject.Where(o => words.Any(o.SearchString.Contains))


text:
Q: Error: No Firebase App '[DEFAULT]' has been created - call firebase.initializeApp() I need to use Phone authentication with firebase but every time I click on the button that sends the code to the user this error shows up, it's probably easy to solve but since my knowledge with firebase and react native is not very deep I can't find a solution.
Here is my code:
export default class VerifyCell extends Component{
    static navigationOptions = {header: null}

    constructor(props){
        super(props);
        this.state = {
            code: '',
        };
    }

    render(){

        const celular = this.props.navigation.getParam('celular');

        return (
            <ScrollView style={styles.container}>
                <HeaderIcon type='MaterialCommunityIcons' name='message-processing'/>
                    <Text style={styles.titulo}>Phone Verification</Text>
                    <Text style={styles.dica}>Insert the code that has been sent to you below</Text>

                    <FormItem onChangeText={ (code) => this.setState({code}) } texto='Code'/>

                    <View style={{marginBottom: '40%'}}></View>

                    <GradientButton texto='Send code' onPress={async () => {
                        const confirmation = await auth().signInWithPhoneNumber('+55 19995661551');
                    }}/>

                <View style={styles.formButton}>

                     <GradientButton texto='Next' onPress={async () => {
                         try {
                            await confirmation.confirm(this.state.code); // User entered code
                            // Successful login - onAuthStateChanged is triggered
                          } catch (e) {
                            console.error(e); // Invalid code
                          }
                         this.props.navigation.navigate('CadastraDados', {celular: celular} )
                         }}/>
                </View>

            </ScrollView>

        )
    }
}

I guess I need to insert this "firebase.initializeApp()" somewhere in my code. Please, how can I fix this issue?

A: The error is pretty straight forward and if you take a look at the documentation, you can see that you need to have a firebaseConfig object,
var firebaseConfig = {
      apiKey: "api-key",
      authDomain: "project-id.firebaseapp.com",
      databaseURL: "https://project-id.firebaseio.com",
      projectId: "project-id",
      storageBucket: "project-id.appspot.com",
      messagingSenderId: "sender-id",
      appId: "app-id",
      measurementId: "G-measurement-id",
    };

with all the relevant data for your application and then you need to use the command:
firebase.initializeApp(firebaseConfig);
This is usually inserted inside your App.js file


text:
Q: Why request.args returns empty ImmutableMultiDict? I am trying to obtain arguments passed from url_for() function. But it keeps returning an empty ImmutableMultiDict to me. Below is my code.
hosts.html

  Install Software

view.py
@app.route('/deploy/<service_id>', methods=['GET', 'POST'])
@app.route('/deploy/<service_id>/<host_id>/', methods=['GET', 'POST'])
@login_required
def svc_instance_deploy(service_id, host_id=0):
    print(request.args)

When click the link on hosts.html, both browser and server side make no error. Except that it prints an empty ImmutableMultiDict to me.
Why can't I get the arguments passed by url_for() function? How could I do that? Thanks in advance.

A: I solved this issue.
Turns out I use the wrong property of Request object. When we obtain arguments in view function, we should use request.view_args instead of request.args.


text:
Q: Approximation of a standard normal random variable in probability Let $Z$ be standard normal random variable and $(a_n)_{n\in\mathbb{N}}$ a real sequence with $a_n\xrightarrow{n\rightarrow\infty}\infty$. Can we obtain something like
$$P(Z>a_n)\leq \exp(- c_n)$$ where $c_n$ is another real sequence with $c_n\xrightarrow{n\rightarrow\infty}\infty$. And if there is a result like this how does $c_n$ look like?
Thanks!

A: For every $z\gt0$,
$P[Z\gt z]\leqslant C(z)$, where
$$
C(z)=\frac1{\sqrt{2\pi}}\frac1z\mathrm e^{-z^2/2}.
$$
This is asymptotically optimal since
$$
P[Z\gt z]\geqslant\frac{z^2}{z^2+1}\,C(z).
$$
In your context, one can choose
$$
c_n=\tfrac12a_n^2+\log(a_n)+\tfrac12\log(2\pi).
$$
Edit: To show the first upper bound above note that, if $z\gt0$ then $t/z\gt1$ for every $t$ in $(z,+\infty)$ hence, for every $z\gt0$,
$$
P[Z\gt z]\leqslant\frac1{\sqrt{2\pi}}\int_z^\infty\frac{t}z\mathrm e^{-t^2/2}\mathrm dt=\frac{-1}{z\sqrt{2\pi}}\cdot\left.\mathrm e^{-t^2/2}\right|_z^\infty=C(z).
$$


text:
Q: Compute dataframe columns from a string formula in variables? I use an excel file in which I determine the names of sensor, and a formula allowing me to create a new "synthetic" sensor based on real sensors. I would like to write the formula as string like for example "y1 + y2 + y3" and not "df ['y1'] + df ['y2'] + df ['y3]" but I don't see which method to use?
Excel file example:

My script must therefore create a new sensor for each line of this excel file. This new sensor will then be uploaded to my database. The number of sensors to calculate the new value is variable!
Here is my code sample :
# From excel file
sensor_cell = '008253_sercit_sercit_batg_b_flr0_g_tctl_z1_tr_prval|officielles_darksky_bierset_temp|officielles_darksky_uccle_temp|005317_esa_001_hur_piece_030110'
formula_cell = "df['y1'] + df['y2'] + df['y3'] + df['y4']"
# formula_cell = 'y1+y2+y3+y4' --> what I would like to be able to write in my  excel file cell

list = sensor_cell.split('|')

df = []
for sensor in list:
    position = list.index(sensor) + 1
    df_y = search_ES(sensor) # Function that return a df with timestamp and value from my database
    df_y = df_y.rename(columns={'value': "y"+ str(position)})
    df.append(df_y)

df = pd.concat(df, axis=1, sort=True)
# I would like to have :
# y1 = df['y1']
# y2 = df['y2']
# y3 = df['y3']
# y4 = df['y4']
df = df.dropna()
print(df)
df['value'] = eval(formula_cell) # Formula from excel file
print(df)

df before applying the formula :
                           y1    y2    y3  y4
2019-12-11 00:00:00  20.500000  5.62  6.03  29
2019-12-11 01:00:00  21.180000  5.54  6.15  30
2019-12-11 02:00:00  21.020000  5.28  6.29  30
2019-12-11 03:00:00  20.760000  4.99  6.36  29
2019-12-11 04:00:00  20.680000  4.80  6.26  30
2019-12-11 05:00:00  20.760000  4.63  6.07  30
2019-12-11 06:00:00  20.900000  4.49  5.91  30
2019-12-11 07:00:00  20.920000  4.20  6.05  30
2019-12-11 08:00:00  21.320000  4.15  5.95  30
2019-12-11 09:00:00  21.840000  4.42  5.81  30
2019-12-11 10:00:00  22.460000  4.24  5.81  30
2019-12-11 11:00:00  22.240000  4.11  5.89  31
2019-12-11 12:00:00  22.420000  4.43  6.15  32
2019-12-11 13:00:00  21.740000  4.37  6.14  32
2019-12-11 14:00:00  22.500000  4.48  6.24  31
2019-12-11 15:00:00  22.980000  4.87  6.46  32
2019-12-11 16:00:00  22.420000  4.56  6.21  32
2019-12-11 17:00:00  22.320000  4.40  5.92  32
2019-12-11 18:00:00  21.939999  4.52  6.19  32
2019-12-11 19:00:00  20.680000  4.30  5.35  32
2019-12-11 20:00:00  20.900000  4.28  4.94  32
2019-12-11 21:00:00  20.859999  4.55  5.21  32
2019-12-11 22:00:00  20.520000  4.28  4.73  32
2019-12-11 23:00:00  20.320000  4.24  4.90  32

df after applying the formula :
                          y1    y2    y3  y4      value
2019-12-11 00:00:00  20.500000  5.62  6.03  29  61.150000
2019-12-11 01:00:00  21.180000  5.54  6.15  30  62.870000
2019-12-11 02:00:00  21.020000  5.28  6.29  30  62.590000
2019-12-11 03:00:00  20.760000  4.99  6.36  29  61.110000
2019-12-11 04:00:00  20.680000  4.80  6.26  30  61.740000
2019-12-11 05:00:00  20.760000  4.63  6.07  30  61.460000
2019-12-11 06:00:00  20.900000  4.49  5.91  30  61.300000
2019-12-11 07:00:00  20.920000  4.20  6.05  30  61.170000
2019-12-11 08:00:00  21.320000  4.15  5.95  30  61.420000
2019-12-11 09:00:00  21.840000  4.42  5.81  30  62.070000
2019-12-11 10:00:00  22.460000  4.24  5.81  30  62.510000
2019-12-11 11:00:00  22.240000  4.11  5.89  31  63.240000
2019-12-11 12:00:00  22.420000  4.43  6.15  32  65.000000
2019-12-11 13:00:00  21.740000  4.37  6.14  32  64.250000
2019-12-11 14:00:00  22.500000  4.48  6.24  31  64.220000
2019-12-11 15:00:00  22.980000  4.87  6.46  32  66.310000
2019-12-11 16:00:00  22.420000  4.56  6.21  32  65.190000
2019-12-11 17:00:00  22.320000  4.40  5.92  32  64.640000
2019-12-11 18:00:00  21.939999  4.52  6.19  32  64.649999
2019-12-11 19:00:00  20.680000  4.30  5.35  32  62.330000
2019-12-11 20:00:00  20.900000  4.28  4.94  32  62.120000
2019-12-11 21:00:00  20.859999  4.55  5.21  32  62.619999
2019-12-11 22:00:00  20.520000  4.28  4.73  32  61.530000
2019-12-11 23:00:00  20.320000  4.24  4.90  32  61.460000

EDIT - SOLUTION:
The problem was solved by using df.eval:
formula_cell = 'fictive = y1+y2+y3+y4'
df.eval(formula_cell, inplace=True)

A: I think pandas.query is what you want. https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.query.html
Example:
formula_cell = "y1 + y2 + y3 + y4"
df['value'] = df.query(formula_cell)


text:
Q: how to make Powershell output file path using mapped drive path instead of true path? How can I change the path in result using mapped drive instead of true path? Now I got something like \\server\data\work\.... I would like to see it in lets say K:\work\....
I can't use mapped drive path for variable because it does not work with task scheduler....
Get-ChildItem -Recurse $source -Filter *.prt | Where{$_.LastWriteTime -gt (Get-Date).AddDays(-6)} | sort LastWriteTime -descending | select name,LastWriteTime,Directory | convertto-html -head $a -body "
FILES LIST FOR PAST 7 DAYS
" | out-file $output\result.htm

A: The mapped drive letter should work as long as you're running the Powershell script as a user who has the drive mapped. Otherwise, you need to use New-PSDrive to map the drive for the session.
New-PSDrive –Name K –PSProvider FileSystem –Root "\\server\data"

A: Try creating a PSDrive at the start of your script. Make sure that the account running the script(through task scheduler) has the required rights on the share.
New-PSDrive –Name "K" –PSProvider FileSystem –Root "\\server\data"
#.... something something, creating $output variable etc.
Get-ChildItem -Recurse $source -Filter *.prt | Where{$_.LastWriteTime -gt (Get-Date).AddDays(-6)} | sort LastWriteTime -descending | select name,LastWriteTime,Directory | convertto-html -head $a -body "
FILES LIST FOR PAST 7 DAYS
" | out-file $output\result.htm


text:
Q: Common Practice for router setup in a business At the company that I'm working for, we have one router (SonicWall TZ 210) and it occasionally go down during business hours. All I have to do to bring it back up is to power cycle the router but during this time all employees in the company has no access to the server, email, file, etc.
How does business deal with unexpected down time because the router needs to be rebooted? What is the common practice to setup something to prevent something like this? Is there a redundancy/backup router?

A: It shouldn't be rebooting, trash it, maybe replace it. There are lots of options available for setting up redundant gateways, other network devices and even servers. Each manufacturer has their own way of doing this. It can also be done in software on regular servers for example with PFsense or Linux.

A: If your firewall is crashing regularly it could be a memory overflow from logging/reporting, or overloading the unit.
Start with the defaults and if you can, upgrade the firmware, the unit you have could be bad and is definitely out of warranty & discontinued.  The  bandwidth coming into that unit can't handle much more than a 50Mbps pipe (With IPS enabled)
Higher end units support HA Pairs, which monitor for failure and fail-over automatically.  You could also establish redundancy with OSPF and dual routers and dual ISPs and use routing and SLA policies on something like a L3 router.
If you are running a TZ210 you don't qualify for any of the built-in high-availability modes from SonicWall, like those available in the TZ300


text:
Q: Scanning a Database and sending an e-mail of changes of a certain tag I have a Database with some goods.These goods have a price on this database. I would like somehow scan this database and when a price of a product changes I want to send an e-mail to a specific address.Is this possible?What programming language should I use php? And What can i do so as to manage this problem? I am kind new to databses and a help would be appreciated.
Thank you very much

A: You can either cache all the prices and run a script that selects all and compares them, or you can set up a trigger on UPDATE that will call a user defined function or stored procedure. From there, you can choose what/where to email.


text:
Q: Partition of integer with size constraint A rather straightforward combinatorial question:
Given numbers $X, q, n$ such that $0 \leq X \leq n(q-1)$, what are the total number of ways to express $X$ as sum of $n$ numbers, where each summand is between $0$ and $q-1$ and the order does matter (e.g. $1+2$ and $2+1$ are considered different)?
I'd assume that there is an established formula for this but I couldn't find it via Google. If someone can give me a pointer to the result it would be much appreciated.
Thanks!

A: You can form a recurrence.  Add $1$ to all the summands to get rid of the zeros.  Now we want the number of compositions of $X+n$ into $n$ parts of maximum size $q$.  Let $N(X+n,n)$ be the desired number of compositions of $X+n$ into $n$ parts of size at most $q$.  Then $$N(i,n)=\begin {cases} 0 & i \lt n\\ 1& i=n\\ \sum_{j=1}^q N(i-j,n-1) & i \gt n\end {cases} $$

A: Turned out "Composition" (en.wikipedia.org/wiki/Composition_(combinatorics)) is the name of the concept I was looking for. Thanks to Newb for pointing it out to me.


text:
Q: i have process it search in all dir in hard drive its take about 15 min i have process it search in all dir in hard drive its take about 15 min how i run parallel with normal  process in web
public class HomeController : Controller
{
    private RapetsDbContext db = new RapetsDbContext();
   public HomeController()
    {
  // i try to call it here with Parallel.Invoke  but  the index waiting  my  dirs() func  to end

       Parallel.Invoke(() => Index(), () => helperCodes.dirs());
    }
    public ActionResult Index()
    {

        ViewBag.Title = "Home Page";

        return View();
    }
}

A: You are blocking the main thread because of the code in HomeController's constructor:
Parallel.Invoke(() => Index(), () => helperCodes.dirs());

Until that parallel is done, the main thread is blocked.
Now to simply unblock the main thread and address your question, you could do:
Task.Factory.StartNew(() =>
            {
                Parallel.ForEach(helperCodes.dirs(), (item) =>

                {
                        // Do something with the dir
                });
            });

which wouldn't block the Ctor from finishing, then you can access Index().
You won't be able to get the task status unless you expose the task as a field or write something to get the task's status. I wouldn't recommend this approach but would write a class to handle this.

A: in the Ctor i user  Task.Factory.StartNew
 public HomeController()
            {
                Task.Factory.StartNew(() => EnitiyGetWorks.GetWorks());
            }

thinks Botonomous for your help your post was the good answer


text:
Q: How to create a class that extends a function Imagine that you have a class in javascript created as it was usual
var Button = function( width ){
    this.width;
}
var button = new button(13);

And now I want to extend it using nice ES6 classes
class ColorButton extends Button {
    constructor( width, color ){
        super(width);
        this.color(color);
    }
}

Is there a way to make it work?

A: This seems to work as expected in Babel REPL: (Code has been modified for the example)
var Button = function( width ){
    this.width = width;

    console.log(this.width);
}
var superButton = new Button(13);

class ColorButton extends Button {
    constructor( width, color ){
      super(width);
      this.color = color;

      console.log(this.color);
    }
}
var subButton = new ColorButton(25, "Red");

A: Finally I could solve my problem by myself. To make a javascript class made as a function extendable, it is needed to set the constructor explicitly in the prototype:
var Button = function( width ){
    this.width = width;
}

// This is the key part
Button.prototype = {
  constructor: Button
}

class ColorButton extends Button {};
var subButton = new ColorButton(25);

console.log( subButton.width ); // 25, it works!


text:
Q: Create a Google Calendar Event In Developer Account I have an requirement to Create an Calendar Event in one of the specified google account. I've been accessing the Api docs and It only shows how to create an event using the OAuth2 to create the Event in User's email account. But how to do this, using .Net Core, for a specified google account If I already have the access to username and password?

A: You cant login to a google api using a login and password this is called client login and google turned this ability off in may 2015.
What you can do is create a service account.   A service account is a dummy user.  If you take the service account email address and share this calendar you want to access with the service account it will be able to create events.
using Google.Apis.Calendar.v3;
using Google.Apis.Auth.OAuth2;
using Google.Apis.Services;
using System;
using System.IO;
using System.Security.Cryptography.X509Certificates;

namespace GoogleSamplecSharpSample.Calendarv3.Auth
{

    public static class ServiceAccountExample
    {

        /// <summary>
        /// Authenticating to Google using a Service account
        /// Documentation: https://developers.google.com/accounts/docs/OAuth2#serviceaccount
        /// </summary>
        /// <param name="serviceAccountEmail">From Google Developer console https://console.developers.google.com</param>
        /// <param name="serviceAccountCredentialFilePath">Location of the .p12 or Json Service account key file downloaded from Google Developer console https://console.developers.google.com</param>
        /// <returns>AnalyticsService used to make requests against the Analytics API</returns>
        public static CalendarService AuthenticateServiceAccount(string serviceAccountEmail, string serviceAccountCredentialFilePath, string[] scopes)
        {
            try
            {
                if (string.IsNullOrEmpty(serviceAccountCredentialFilePath))
                    throw new Exception("Path to the service account credentials file is required.");
                if (!File.Exists(serviceAccountCredentialFilePath))
                    throw new Exception("The service account credentials file does not exist at: " + serviceAccountCredentialFilePath);
                if (string.IsNullOrEmpty(serviceAccountEmail))
                    throw new Exception("ServiceAccountEmail is required.");

                // For Json file
                if (Path.GetExtension(serviceAccountCredentialFilePath).ToLower() == ".json")
                {
                    GoogleCredential credential;
                    using (var stream = new FileStream(serviceAccountCredentialFilePath, FileMode.Open, FileAccess.Read))
                    {
                        credential = GoogleCredential.FromStream(stream)
                             .CreateScoped(scopes);
                    }

                    // Create the  Analytics service.
                    return new CalendarService(new BaseClientService.Initializer()
                    {
                        HttpClientInitializer = credential,
                        ApplicationName = "Calendar Service account Authentication Sample",
                    });
                }
                else if (Path.GetExtension(serviceAccountCredentialFilePath).ToLower() == ".p12")
                {   // If its a P12 file

                    var certificate = new X509Certificate2(serviceAccountCredentialFilePath, "notasecret", X509KeyStorageFlags.MachineKeySet | X509KeyStorageFlags.Exportable);
                    var credential = new ServiceAccountCredential(new ServiceAccountCredential.Initializer(serviceAccountEmail)
                    {
                        Scopes = scopes
                    }.FromCertificate(certificate));

                    // Create the  Calendar service.
                    return new CalendarService(new BaseClientService.Initializer()
                    {
                        HttpClientInitializer = credential,
                        ApplicationName = "Calendar Authentication Sample",
                    });
                }
                else
                {
                    throw new Exception("Unsupported Service accounts credentials.");
                }

            }
            catch (Exception ex)
            {
                throw new Exception("CreateServiceAccountCalendarFailed", ex);
            }
        }
    }
}

Code ripped from my calendar sample project ServiceAccount.cs


text:
Q: Where are the logs for apt-get? I would like to know where I can find the logs for the following package managers:

*

*Synaptic Package Manager

*Ubuntu Software Center

*The logs when using the terminal with apt-get

A: I like /var/log/apt/history.log. It is very concise.
Also note that older logs are archived with logrotate once a month. To combine the current history.log and all the older compressed history.log files you can use cat and zcat like this:
cd /var/log/apt && cat history.log > ~/Desktop/allhistory.log && zcat history.log*gz >> ~/Desktop/allhistory.log && cd
Then you can, for example, use grep to find what you need:
$ grep package_name ~/Desktop/allhistory.log where you will put what you want in place of package_name.
$ grep google ~/Desktop/allhistory.log
Upgrade: google-chrome-stable:amd64 (32.0.1700.102-1, 33.0.1750.117-1)
Upgrade: google-chrome-stable:amd64 (31.0.1650.48-1, 32.0.1700.77-1)
Upgrade: google-chrome-stable:amd64 (32.0.1700.77-1, 32.0.1700.102-1)
Upgrade: google-chrome-stable:amd64 (30.0.1599.101-1, 31.0.1650.48-1)

And, Bohr, in a comment, suggested using zgrep directly if one is searching for lines related to a specific package. This works for me assuming I'm searching both history.log and its existing archived files for smtube:
zgrep smtube /var/log/apt/history*

A: check the file
/var/log/dpkg.log

which records all the apt activities, such as installs or upgrades, for the various package managers
also you can view synaptic logs through its gui

A: Apt logs can be found in /var/log/apt/term.log. To view them with GEdit you can use the command:
gedit /var/log/apt/term.log

A: You can use:
zcat /var/log/dpkg.log.*.gz | cat - /var/log/dpkg.log

or if you want less details:
zcat /var/log/dpkg.log.*.gz | cat - /var/log/dpkg.log | grep -E 'install |upgrade |remove '


text:
Q: Convert to N tier architecture I want to convert my architecure into N tier architecture.Please find below details.
----------------------- Sql--------------------------------
USE [Practice]
GO
/****** Object:  Table [dbo].[Brand]    Script Date: 03/02/2019 00:56:50 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

SET ANSI_PADDING ON
GO

CREATE TABLE [dbo].[Brand](
    [Id] [int] IDENTITY(1,1) NOT NULL,
    [BrandName] [varchar](20) NULL,
    [ProductId] [int] NULL,
 CONSTRAINT [PK_Brand] PRIMARY KEY CLUSTERED
(
    [Id] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]

GO

SET ANSI_PADDING OFF
GO
----------------------------------------------------------------------------------------------------

USE [Practice]
GO

/****** Object:  Table [dbo].[Product]    Script Date: 03/02/2019 00:57:30 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

SET ANSI_PADDING ON
GO

CREATE TABLE [dbo].[Product](
    [Id] [int] IDENTITY(1,1) NOT NULL,
    [ProductName] [varchar](20) NULL,
 CONSTRAINT [PK_Product] PRIMARY KEY CLUSTERED
(
    [Id] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]

GO

SET ANSI_PADDING OFF
GO

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

USE [Practice]
GO

/****** Object:  Table [dbo].[BrandProductAssociation]    Script Date: 03/02/2019 00:58:00 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

SET ANSI_PADDING ON
GO

CREATE TABLE [dbo].[BrandProductAssociation](
    [Id] [int] IDENTITY(1,1) NOT NULL,
    [BrandId] [int] NOT NULL,
    [ProductId] [int] NOT NULL,
    [Price] [int] NOT NULL,
    [Ingrdient] [varchar](10) NULL,
    [UseFor] [varchar](10) NULL
) ON [PRIMARY]

GO

SET ANSI_PADDING OFF
GO

--------------------------------------------------------------------------------------------------------------------
USE [Practice]
GO

/****** Object:  StoredProcedure [dbo].[Proc_SelecBrand]    Script Date: 03/02/2019 00:58:39 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

CREATE Procedure [dbo].[Proc_SelecBrand]
@ProductId int = null
as
begin
select * from Brand where (productid =@ProductId or @ProductId is null)
end
GO

----------------------------------------------------------------------------------------------------------------------
USE [Practice]
GO

/****** Object:  StoredProcedure [dbo].[Proc_SelecProduct]    Script Date: 03/02/2019 00:59:54 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

create Procedure [dbo].[Proc_SelecProduct]
as
begin
select * from Product
end
GO

------------------------------------------------------------------------------------------------------------------------
USE [Practice]
GO

/****** Object:  StoredProcedure [dbo].[Proc_InsertBrandProductDetails]    Script Date: 03/02/2019 01:00:31 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

create Procedure [dbo].[Proc_InsertBrandProductDetails]
@BrandId int,
@ProductId int,
@price int,
@Ingri varchar(10),
@user varchar(10)
as
begin
Insert into BrandProductAssociation ([BrandId],[ProductId],[Price],[Ingrdient],[UseFor]) values (@BrandId,@ProductId,@price,@Ingri,@user)
end
GO

------aspx----------------------------------------------------------------

<%@ Page Title="Home Page" Language="C#" MasterPageFile="~/Site.master" AutoEventWireup="true"
    CodeBehind="Default.aspx.cs" Inherits="TestApp._Default" %>

<asp:Content ID="HeaderContent" runat="server" ContentPlaceHolderID="HeadContent">
</asp:Content>
<asp:Content ID="BodyContent" runat="server" ContentPlaceHolderID="MainContent">
    <asp:ScriptManager ID="ScriptManager1" runat="server">
    </asp:ScriptManager>

    <asp:UpdatePanel ID="UpdatePanel1" runat="server">
        <ContentTemplate>

                        <asp:Label ID="LblMessage" runat="server" ForeColor="Red"></asp:Label>

                        Product

                        <asp:DropDownList ID="ddlProduct" runat="server" Height="19px" Width="200px" OnSelectedIndexChanged="ddlProduct_SelectedIndexChanged"
                            AutoPostBack="true">
                        </asp:DropDownList>
                        *

                        <asp:RequiredFieldValidator ID="RFDProduct" runat="server" ErrorMessage="Please Select Product"
                            InitialValue="--Select Product--" ControlToValidate="ddlProduct" Display="Dynamic" ForeColor="Red" ></asp:RequiredFieldValidator>

                        Brand

                        <asp:DropDownList ID="ddlBrand" runat="server" Height="19px" Width="200px">
                        </asp:DropDownList>
                        *

                        <asp:RequiredFieldValidator ID="RFDBrand" runat="server" ErrorMessage="Please Select Brand"
                            InitialValue="--Select Brand--" ControlToValidate="ddlBrand" Display="Dynamic" ForeColor="Red" ></asp:RequiredFieldValidator>

                Price

                <asp:TextBox ID="txtPrice" runat="server" Width="200px" Height="19px"></asp:TextBox>*

                <asp:RequiredFieldValidator ID="RFDtxtPrice" runat="server" ErrorMessage="Please Enter Price" Display="Dynamic"
                    ControlToValidate="txtPrice" ForeColor="Red" ></asp:RequiredFieldValidator>

                Ingredient

                <asp:TextBox ID="txtIngredient" runat="server" Width="200px" Height="19px"></asp:TextBox>*

                <asp:RequiredFieldValidator ID="RFDIngredient" runat="server" ErrorMessage="Please Enter Ingredient"
                    ControlToValidate="txtIngredient" Display="Dynamic" ForeColor="Red" ></asp:RequiredFieldValidator>

                Use

                <asp:TextBox ID="txtUse" runat="server" Width="200px" Height="19px"></asp:TextBox>*

                <asp:RequiredFieldValidator ID="RFDUse" runat="server" ErrorMessage="Please Enter Use"
                    ControlToValidate="txtUse" Display="Dynamic" ForeColor="Red" ></asp:RequiredFieldValidator>

                <asp:Button ID="BtnSubmit" runat="server" Text="Submit" OnClick="BtnSubmit_Click" />

        </ContentTemplate>
    </asp:UpdatePanel>

</asp:Content>

----------------------------------------------------------------------                            _--------------- cs ------------------------------------------------------using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;

namespace TestApp
{
    public partial class _Default : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            Session["UserId"] = 2;

            if (Session["UserId"] == null)
            {
                Response.Redirect("Login.aspx");
            }
            else
            {
                if(!IsPostBack)
                {
                    PopulateBrand();
                    PopulateProduct();
                }
            }
        }

        private void PopulateProduct()
        {
            try
            {

                DataSet ds = SqlHelpper.GetDataSet(CommandType.StoredProcedure, "Proc_SelecProduct", "Product", "PracticeConnectionString", null);

                if (ds != null)
                {
                    DataTable dt = ds.Tables["Product"];

                    if (dt.Rows.Count > 0)
                    {
                        ddlProduct.Items.Insert(0, "--Select Product--");

                        foreach (DataRow dr in dt.Rows)
                        {
                            ListItem lt = new ListItem(dr["ProductName"].ToString(), dr["Id"].ToString());

                            ddlProduct.Items.Add(lt);

                        }
                    }

                }

            }
            catch (Exception ex)
            {
                throw;
            }
        }

        private void PopulateBrand()
        {
            try
            {
                string Product = null;

                if (ddlProduct.SelectedIndex > 0)
                {
                    Product = ddlProduct.SelectedItem.Value;

                }
                DataSet ds = SqlHelpper.GetDataSet(CommandType.StoredProcedure, "Proc_SelecBrand", "Product", "PracticeConnectionString",
                             new SqlParameter("@ProductId", Product));

                if (ds != null)
                {
                    ddlBrand.DataSource = ds;
                    ddlBrand.DataTextField = "BrandName";
                    ddlBrand.DataValueField = "Id";
                    ddlBrand.DataBind();
                    ddlBrand.Items.Insert(0, "--Select Brand--");
                }
            }
            catch (Exception ex)
            {
                throw;
            }

        }

        protected void ddlProduct_SelectedIndexChanged(object sender, EventArgs e)
        {
            try
            {
                PopulateBrand();
            }
            catch (Exception ex)
            {

            }
        }

        protected void BtnSubmit_Click(object sender, EventArgs e)
        {
            int count = SqlHelpper.ExecuteNonQuery(CommandType.StoredProcedure, "Proc_InsertBrandProductDetails", "PracticeConnectionString",
                new SqlParameter("@BrandId",ddlBrand.SelectedItem.Value),
                new SqlParameter("@price",txtPrice.Text),
                new SqlParameter("@ProductId",ddlProduct.SelectedItem.Value),
                new SqlParameter("@Ingri",txtIngredient.Text),
                new SqlParameter("@user",txtUse.Text));

            if (count > 0)
            {
              // Show message

                //clean control

                txtIngredient.Text = "";
                txtPrice.Text = "";
                txtUse.Text = "";
                ddlBrand.SelectedIndex = 0;
                ddlProduct.SelectedIndex = 0;
                LblMessage.Text = "BrandProduct details inserted sucessfully.";

            }
        }
    }
}

-------------------- Helper class created under app_code-------------------------------------
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;

namespace TestApp
{
    public class SqlHelpper
    {
        public static DataSet GetDataSet(CommandType cmdType, string cmdText, string tabName, string connString, params SqlParameter[] cmdParms)
        {
            string Constring = ConfigurationManager.ConnectionStrings[connString].ConnectionString;
            SqlConnection conn = new SqlConnection(Constring);
            SqlCommand cmd = new SqlCommand(cmdText, conn);
            cmd.CommandType = cmdType;

            if (cmdParms != null)
            {
               foreach(SqlParameter param in cmdParms)
               {

                   cmd.Parameters.Add(param);
               }
            }

            DataSet ds = new DataSet();
            SqlDataAdapter da = new SqlDataAdapter(cmd);
            try
            {
                da.Fill(ds, tabName);

                return ds;
            }
            catch
            {
                conn.Close();

                throw;
            }
            finally
            {
                conn.Close();
            }
        }

        public static int ExecuteNonQuery(CommandType cmdType, string cmdText,string connString,params SqlParameter[] cmdParms)
        {
            SqlConnection conn=null;
            int val=0;
            try
            {
                string Constring = ConfigurationManager.ConnectionStrings[connString].ConnectionString;

                conn = new SqlConnection(Constring);
                SqlCommand cmd = new SqlCommand();
                PrepareCommand(cmd, conn, null, cmdType, cmdText, cmdParms);
                val = cmd.ExecuteNonQuery();
                // cmd.Parameters.Clear();
                int cat = val;
               conn.Close();
                return val;

            }
            catch (Exception)
            {
                conn.Close();
                throw;
                //trans.Rollback();
            }
            finally
            {
              conn.Close();
            }
    }

        private static void PrepareCommand(SqlCommand cmd, SqlConnection conn, SqlTransaction trans, CommandType cmdType, string cmdText, SqlParameter[] cmdParms)
        {
            if (conn.State != ConnectionState.Open)
                conn.Open();
            cmd.Connection = conn;
            cmd.CommandText = cmdText;
            if (trans != null)
                cmd.Transaction = trans;

            cmd.CommandType = cmdType;

            if (cmdParms != null)
            {
                foreach (SqlParameter parm in cmdParms)
                    cmd.Parameters.Add(parm);
            }
        }

     }
}

A: The code in the question is not really n-tier, because the you still have to build SQL commands or list stored procedure names in the ASP.Net code-behind.
If you want n-tier, you must make the SqlHelper methods shown here private. Then, for each query you need to run, add a new method for that specific query, using your current GetDataSet() and ExecuteNonQuery() methods to run the code. Additionally, this class should be in it's own class library project, to end up in it's own dll file.
Later, as the project grows, you can move the individual query methods to separate classes to create logical groupings and enforce different kinds of security, and make the methods in your SqlHelper internal instead of private to facilitate that change.


text:
Q: PNG to Bitmap file conversion I'm developing a RESTful API with Spring where some users can upload some images they draw in a mobile device. The mobile application sends the image in .png format and I would need to generate a bitmap from it for further processing in Delphi. I've been playing around using ImageIO class but it does not seem to do the trick when specifying .bmp format and writing to a new file. Are out there some libraries that do these kind of image conversions? It should be a solved problem nowadays but I am not familiar with image processing.
Thanks

A: This should work:
//Create file for the source
File input = new File("c:/temp/image.png");

//Read the file to a BufferedImage
BufferedImage image = ImageIO.read(input);

//Create a file for the output
File output = new File("c:/temp/image.bmp");

//Write the image to the destination as a BMP
ImageIO.write(image, "bmp", output);


text:
Q: Jquery trigger for remove product from woocommerce cart ajax Looking to run some jQuery when a product is removed from the cart in woocommerce. I thought this would do it, but it's not happening.
Any ideas?
jQuery( document.body ).on( 'updated_wc_div', function(){
//magic
});

A: There can be also triggered updated_cart_totals event when cart has updated. So, you can use the following workaround, as there is no one global event which triggered when the cart is updated:
jQuery( document.body ).on( 'updated_wc_div', do_magic );
jQuery( document.body ).on( 'updated_cart_totals', do_magic );

function do_magic() {
    // do magic
}

A: You can remove the product from cart using this code :
main.js
 $.ajax({
    type: "POST",
    url: 'http://localhost/your_site/wp-admin/admin-ajax.php',
    data: {action : 'remove_item_from_cart','product_id' : '4'},
    success: function (res) {
        if (res) {
            alert('Removed Successfully');
        }
    }
});

functions.php
function remove_item_from_cart() {
$cart = WC()->instance()->cart;
$id = $_POST['product_id'];
$cart_id = $cart->generate_cart_id($id);
$cart_item_id = $cart->find_product_in_cart($cart_id);

if($cart_item_id){
   $cart->set_quantity($cart_item_id, 0);
   return true;
}
return false;
}

add_action('wp_ajax_remove_item_from_cart', 'remove_item_from_cart');
add_action('wp_ajax_nopriv_remove_item_from_cart', 'remove_item_from_cart');

A: Give this set of code in  your js
file
jQuery(document.body)
  .on(
    'removed_from_cart updated_cart_totals',
    function() {
      // your code...
    }
  );


text:
Q: C# Consume WebService authenticated via FormsAuthentication Method so my question is very simple, how could I consume a WebService which is protected by a FormsAuthentication method (aka Cookie's style) ?
Because I've my WinForms application that can't consume authenticated WebServices.
I already saw the WebClient method, do you thing is usefull to what I want to do ?
Thanks for your answers !

A: I don't really found an answer about that !
The only thing I've done, is to protect all the Web pages I need to protect using Forms Authentication, and then consume my famous WebService in order to use it with my application.
Thank you anyway to you all !


text:
Q: errors from numberOfRowsInSection function between two TableViews I'm making a View which is including two tableviews, one of which is the self.tableView and the other one is searchDisplayController.searchResultsTableView to display the search result. The code is below:
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if (tableView == self.searchDisplayController.searchResultsTableView) {
        return [searchResultArray count];
    } else if (tableView == self.tableView){
        return [menuItems count];
    } }

The problem is that I knew the return [menuItems count] value is 10, and if the return value of [searchResultArray count] is bigger than 10, I will get the error message below:
2012-09-26 17:11:50.332 searchResultArray count:80
2012-09-26 17:11:50.337 *** Terminating app due to uncaught exception 'NSRangeException', reason: '*** -[__NSArrayI objectAtIndex:]: index 10 beyond bounds [0 .. 9]'

But if the return value of [searchResultArray count] is smaller than 10, it works fine. How to fix this?
Please Advise! Thanks!

A: if you are using interface-builder check for TableViewController
There should be a "table view" under your view controller.
in the attribute inspector of the table view Check the "content" , if its assigned "Dynamic Prototypes" or "static cell"?
Change it to "Dynamic Prototypes" .

A: The problem is in your search method, each time you run the search logic and add the objects into searchArray- you need to clear the objects from it before it starts adding. You can use
[searchResultArray removeAllObjects];

A: as iMeMyself said you should assigned dynamic prototypes to both tableview. because when datasource method will called it will check the tableview dynamically. so assigned it dynamic prototypes.

A: make sure both of the tableviews are set as "Dynamic Prototypes"


text:
Q: declare TPH with existing TPT (Code First) I have couple of classes which inherits 1 base abstract class. It is mapped via fluent API to existing database (using Table-Per-Concrete-Type, i.e. base abstract class not mapped to any table).
Now I want to add some statistics to my code and the best solution for me is to use TPH approach for 3-4 new classes. It maybe or maybe not inherits the same class as described above.
But I do not know how to instruct EF use TPH-approach for these 3-4 classes. Am I need to add correect table with discriminators and it will be used ok? Or I need to specify it somehow via fluent API?

A: I found. You do not need to specify somehow EF that you want to use TPH. Enough to do following:
Create classes hierarchy
class Base { ... }
class Derived1 : Base { ... }
class Derived2 : Base { ... }
.......
class DerivedN : Base { ... }

Create table called as your base type (otherwise do not forget to map it using ModelBuilder) with common columns (content of Base) and with one column per public property in each derived types. Add "Discriminator" column (nvarchar(128), but I suggest to use varchar unless you using unicode classes names).
In your successor of DbContext add only one DbSet: DbSet<Base> Data { get; set; } and use it for CRUD operations.
That is all!


text:
Q: Has the guidance on the setting for 'cost threshold for parallelism' changed with the advent of columnstore indexes? First off, what I'm not asking.  I'm not asking what my setting should be.
Many are recommending upping the value past the default, and I certainly understand why that's the case for B-Tree based queries.  But I've been reading about the (almost) linear scalability of in-memory clustered columnstore indexes, and I'm wondering if setting the cost threshold too high could cause SQL Server to starve columnstore-based queries for CPU cores.
So the question is this:  Does SQL Server treat columnstore indexes differently when the 'cost threshold for parallelism' is concerned, and should that cause me to change my decision about what my initial setting should be?

A: Beyond the Cost Threshold setting, SQL Server appears to treat parallelism differently for columnstore indexes depending on your SQL Server version (2012 vs 2014) and even the datatypes in your table.
I'd start with Joe Chang's post benchmarking decimal vs float datatypes, and read the comments on that post as well. If you want to get exactly the right MAXDOP and Cost Threshold for Parallelism settings for your system, you'll need to perform the level of detailed testing that Joe does in his post, and that takes a lot of work. Because of that, I would focus on your system's primary bottleneck first - use wait stats to make sure parallelism or CPU pressure are problems for you, and then start by tuning the most CPU-intensive queries rather than making system settings changes.

A: TL;DR:  The suggested initial setting of 50 you read about remains a fine place to start.  MAXDOP of 1 physical core per NUMA node is a good setting for a server like ours which serves both OLTP and OLAP workloads.
Corrolary: SQL Server is really, really good at what it does.
My principal worry with this setting was whether or not I would inhibit parallel execution on a clustered columnstore-based index for what should be pretty short queries.  Would a setting of 50 cause what should be a sub-1 second query on to take a lot more time?  Since columnstore indexes scale so well with CPUs, would the 'cost threshold for parallelism' setting just be ignored?

*

*Q: Will SQL Server even honor 'cost threshold for parallelism' for
columnstore indexes?

*A: Yes.  When configured with a ridiculous setting of 30,000, parallelism
for columnstore indexes was effectively disabled for my workloads.
Trying some other, still obscene values (1,500) inhibited
parallelism for workloads that nominally took about a second to run, but queries which nominally run in about 10 or more seconds exhibited parallel execution plans.

*Q: Is a default setting of 50, as specified in some checklists out there, a safe value that won't inhibit parallelism for my columnstore based queries?

*A: Yes, and by a long shot.  Even jacking the value up to 500 still allowed parallelism for simple, short (sub-second) columnstore based queries.

About my server, workload, and results:

*

*2x Xeon E2650v2, (2 NUMA nodes, 12 physical cores, 24 HT threads), 384 GB RAM

*MAXDOP configured at 6 (6 physical cores per NUMA node)

*SQL Server 2014 Enterprise CU4

*Testing on 111,000,000 row clustered columnstore index, in 6 partitions (by year)

Two workloads tested:

*

*SELECT COUNT(DISTINCT <low cardinality column>) FROM table;

*SELECT COUNT(DISTINCT <high cardinality column>) FROM table;
The query of the high cardinality column took 84 seconds (elapsed) at thresholds over 1500, and about 14 seconds (elapsed) at thresholds under that number.  The query of the low cardinality column took about 250ms (elapsed) at thresholds 500 and under, and 18 (elapsed) seconds at thresholds above 1500.  (I didn't try to gauge the exact point at which it switched plans.)  Interestingly enough, when parallelism is inhibited, the total CPU time for the low cardinality query shoots up dramatically; perhaps the server stops using batch mode for this query.
Heh, ultimately running tests leads to more questions, but that's all blog-fodder, and goes beyond the scope of this question.

A: I would add to the Joe Chang article that you should check out this one by Paul White, where he discusses a Trace Flag that essentially sets CTFP to 0 for the query you're running. I know it's not exactly what you're looking for, but that along with MAXDOP testing can give you a good idea about if your query going parallel will even be beneficial on column store indexesices. I've been trying it out a bit lately (in dev, I swear) in place of artificially complicating the plan to force parallelism.

A: I'm writing this answer from the point of view of SQL Server 2016+. 50 as a value for CTFP isn't a good fit for all columnstore workloads and I recommend starting around 30 instead. A few reasons for that:

*

*Query costs will be lower than what you are used to due to higher compression rates and batch mode processing.

*Queries on columnstore tables often use batch mode processing which has a different model for query parallelism than row mode execution. There is less overhead to parallel queries so parallelism can be a better choice for less expensive queries that would traditionally run best at DOP 1 without batch mode.

*Queries on columnstore tables will have fewer parallel zones compared to rowstore queries. SQL Server will reserve fewer parallel worker threads so running out of threads on the server isn't as likely to happen if many parallel queries are running on the server at the same time.

*There are significant optimizer cost model limitations with columnstore tables that aren't likely to be resolved soon. Rowgroup elimination and aggregate pushdown aren't factored into optimizer costs. If a query is able to eliminate nearly all rowgroups using elimination then it might be okay for it to run at DOP 1. However, if it can't then you might really want the query to run in parallel. The optimizer will assign the same cost either way.

In production workloads, I've seen queries on columnstore tables in the 30-49 optimizer unit range at MAXDOP 1 that really could have benefited from query parallelism. I can't say how common this is across all workloads, but it's something to be aware of.


text:
Q: what makes difference with these two programs in C I have two very similar programs, as follows.
Program A: no problem when running,
#include <string.h>
#include <stdio.h>

typedef struct p_struct{
   unsigned char* pulist;
   int length;
} list_type;

int get_struct(list_type* l)
{
   memset(l->pulist, 0, 4);
   l->length=4;
}

int main ()
{
   list_type str;
   get_struct(&str);
}

Program B: has an additional function call, still compiles, but crashes with run-time error "Segmentation fault" with gcc.
#include <string.h>
#include <stdio.h>

typedef struct p_struct{
   unsigned char* pulist;
   int length;
} list_type;

int get_struct(list_type* l)
{
   memset(l->pulist, 0, 4);
   l->length = 4;
}

int get_struct_a()
{
   list_type str;
   get_struct(&str);
}

int main ()
{
   get_struct_a();
}

I am really struggling to figure out the problem here. Can anyone tell me what causes "Segmentation error"? Also, why program B gives "Segmentation fault" error, while program A does not?

A: You're not allocating memory for the pulist member of your structure. Hence when you memset it, you're overwriting some other memory somewhere else. It's just luck that in the second case the memory you overwrite happens not to give a segfault, but you're still corrupting the memory.

A: You never initialize pulist to anything, so it is pointing just anywhere. It is just pure coincidence that it crashes in one case, but not the other.

A: memset(l->pulist, 0, 14);

Is probably what's crashing it. You're not allocating any memory for l->pulist before you try to use it as a pointer to some memory.
This
memset(l->pulist, 0, 4);

Should also crash, but it's working by chance.
What's happening is you're allocating one of those structs on the stack, and all the members have some random garbage value in them (the value that happened to be in the memory it got allocated). Then you're trying to use one of these random values as a pointer, and telling memset, "go overwrite 14 bytes at this random location with 0s." You can see why that would cause problems. But since the pointer is random, it doesn't always cause problems.
You'll need to do something like
l->pulist = malloc(size);

To make it a valid pointer before using it in operations like that.

A: A segmentation fault occurs when a program attempts to access a memory location that it is not allowed to access, or attempts to access a memory location in a way that is not allowed (for example, attempting to write to a read-only location, or to overwrite part of the operating system).
A few causes of a segmentation fault can be summarized as follows:

*

*attempting to execute a program that does not compile correctly. Note that most compilers will not output a binary given a compile-time error.

*
a buffer overflow.

*
using uninitialized pointers.

*
dereferencing NULL pointers.

*
attempting to access memory the program does not own.

*
attempting to alter memory the program does not own (storage violation).

*
exceeding the allowable stack size (possibly due to runaway recursion or an infinite loop)

Generally, segmentation faults occur because: a pointer is either NULL, points to random memory (probably never initialized to anything), or points to memory that has been freed/deallocated/"deleted".

A: I would say the the struct member pulist is an uninitialized pointer. Befor you use memset you need to allocate some memory for this member.

A: You haven't initialized your pulist member to point anywhere meaningful; it just contains a random bit string.  In program A, that random bit string corresponds to a memory address that just happens to be writable.  In program B, it doesn't.
Both programs are equally wrong.  When you create your list_type object, you need to explicitly set the pulist member to point to a buffer that you own.


text:
Q: C# date format string using windows setting instead of string passed to it I expect ToString("MM/dd/yyyy") to ignore the system settings and always output the format as defined.  The below test passes if I set my Windows 10 date string set to the 08/27/2020 format but fails if I set it to 2020-08-27 format with the below error.
Am I missing something?
[Test]
public void TestDate() {
Assert.AreEqual("08/08/2020", (new DateTime(2020, 8, 8)).ToString("MM/dd/yyyy"));
}

Results
String lengths are both 10. Strings differ at index 2.
Expected: "08/08/2020"
But was:  "08-08-2020"

A: Ok, while typing this, I was shown this work around.  I still this this is a problem.
[Test]
public void TestDate() {
    Assert.AreEqual("08/08/2020", (new DateTime(2020, 8, 8)).ToString(@"MM\/dd\/yyyy"));
}

Per comments below "MM'/'dd'/'yyyy" works too.


text:
Q: mathematica:: 3d piecwise function problem i'm trying to plot a function  $$\ f(x,y)=cos(\sqrt{x^2 +y^2})$$,same as cos(r).. f(x,y)=0 for points ,which are on circle.when the points are out of this circle i want the function f(x,y) to be 0 as well. so the support of my function  to be the circle.i want to plot this situation.. as i thought, my function is
  $$f(x,y)=
\left\{
\begin{array}{c}
cos(r) ,r<\pi/2\\
0,othervise \\
\end{array}
\right.
$$
but my plot isn't continuous...please help me understand the problem.-->
-->

A: I think the problem is with $\texttt{Piecewise[]}$. Try this variation instead:
$\texttt{f[x_, y_] := With[{r = Sqrt[x*x + y*y]}, If[r > Pi/2, 0, Cos@r]];}$
$\texttt{Plot3D[f[x, y], {x, -5, 5}, {y, -5, 5}]}$

You can use the option $\texttt{PlotPoints -> 100}$
to make the base sharper, but using
$\texttt{Piecewise[]}$ leaves a gap in the plot surface as you noticed.

A: That is a feature to indicate that your function is not continuous there. You can use the Exclusions option to prevent it
k[x_, y_] := With[{r = Sqrt[x^2 + y^2]},
  Piecewise[{{Cos[r], r < Pi/2}}, 0]
]
Plot3D[k[x, y], {x, -5, 5}, {y, -5, 5}, Exclusions -> None]

Edit
If you are wondering why this plot looks a bit bumpy at the bottom, the reason is that there are too few polygons used to create a sharp plot. You can try
Plot3D[k[x, y], {x, -5, 5}, {y, -5, 5}, Exclusions -> None,
 PlotPoints -> 100, MaxRecursion -> 6]

and then you clearly see your circle at the bottom


text:
Q: putting selected array in to a listbox I would like to Implement the following feature: when a user selects a movie from the dropdownlist and clicks on the 'Add to cart' button, the movie is then added into the list box below.
protected void addImageButton_Click(object sender, ImageClickEventArgs e)
{
    string[] moviesArrayString = new string[10];

    moviesArrayString[1] = "Badboy 2";
    moviesArrayString[2] = "BadBoy 3";
    moviesArrayString[3] = "The Godfather";
    moviesArrayString[4] = "Inception";
    moviesArrayString[5] = "The Shawshank Redemtion";
    moviesArrayString[6] = "Star Wars";
    moviesArrayString[7] = "The Metrix";
    moviesArrayString[8] = "King Kong";
    moviesArrayString[9] = "Point Break";
    moviesArrayString[10] = "Top Gun";

    cartListBox.Items.AddRange(moviesArrayString);
}

It give me some error and I couldn't figure out how to do so?
error is index was outside the bound of arrays?

A: Arrays in C# are zero-based. Use the indexes from 0 to 9:
protected void addImageButton_Click(object sender, ImageClickEventArgs e)
{
    string[] moviesArrayString = new string[10];

    moviesArrayString[0] = "Badboy 2";
    moviesArrayString[1] = "BadBoy 3";
    moviesArrayString[2] = "The Godfather";
    moviesArrayString[3] = "Inception";
    moviesArrayString[4] = "The Shawshank Redemtion";
    moviesArrayString[5] = "Star Wars";
    moviesArrayString[6] = "The Metrix";
    moviesArrayString[7] = "King Kong";
    moviesArrayString[8] = "Point Break";
    moviesArrayString[9] = "Top Gun";

    cartListBox.Items.AddRange(moviesArrayString);
}

Alternatively, you can use:
string[] moviesArrayString =
{
    "Badboy 2", "BadBoy 3", "The Godfather", "Inception",
    "The Shawshank Redemtion", "Star Wars", "The Matrix", "King Kong", "Point Break", "Top Gun"
};

A: Just set the DataSource instead of adding item into listBox......
string[] moviesArrayString =
{
    "Badboy 2", "BadBoy 3", "The Godfather", "Inception",
    "The Shawshank Redemtion", "Star Wars", "The Matrix", "King Kong", "Point Break", "Top Gun"
};

 listBox1.DataSource = moviesArrayString;

A: Use List<> or ArrayList in the place of string[].
For Example:
ArrayList lst=new ArrayList();
lst.Add("badboy2");
lst.Add("badbo32");
lst.Add("badb2");
lst.Add("bboy2");
lst.Add("bad2");
foreach(string str in lst)
{
cartListBox.Items.Add(str);
}


text:
Q: ComboBox with localizable ComboBoxItems specified in XAML I have a ComboBox which I'd like to populate with members of an enum, with localized representative strings.  I know the standard way to do this is to make a Dictionary in codebehind with the enum values as keys and the text as values, and then set the ItemsSource to that.  But then I wouldn't be able to use my sexy MarkupExtension.  So, I'd like to do this in XAML.  I thought it would be easy; here's what I have:
        <ComboBox x:Name="cmbNewTabPos"
            DisplayMemberPath="Content"
            SelectedValue="{Binding Path=NewTabPosition}"
            SelectedValuePath="Tag">
            <ComboBoxItem
                Content="{qt:Resx Key=SomeKey, Index=0}"
                Tag="{x:Static qt:TabPos.Left}"/>
            <ComboBoxItem
                Content="{qt:Resx Key=SomeKey, Index=1}"
                Tag="{x:Static qt:TabPos.Right}"/>
            <ComboBoxItem
                Content="{qt:Resx Key=SomeKey, Index=2}"
                Tag="{x:Static qt:TabPos.Leftmost}"/>
            <ComboBoxItem
                Content="{qt:Resx Key=SomeKey, Index=3}"
                Tag="{x:Static qt:TabPos.Rightmost}"/>
        </ComboBox>

It almost works; the dropdown is populated correctly, the binding is working, I can see the selected value when I pull down the dropdown, but the box part of the combobox remains blank no matter what I do.  What am I doing wrong here?

A: I write this little example and it works fine.
<Window x:Class="MainWindowCommandBinding.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="MainWindow" Height="350" Width="525">
<Grid>
    <Grid.Resources >
        <Point x:Key="1_2" X="1" Y="2"/>
        <Point x:Key="1_3" X="1" Y="3"/>
        <Point x:Key="1_4" X="1" Y="4"/>
        <Point x:Key="1_5" X="1" Y="5"/>
    </Grid.Resources>
    <ComboBox x:Name="cmbNewTabPos"
        DisplayMemberPath="Y"
        SelectedValuePath="Tag"
        SelectedValue="1"
         Margin="0,12,0,0" HorizontalAlignment="Left" Width="135" Height="37" VerticalAlignment="Top">
        <ComboBoxItem Content="{StaticResource ResourceKey=1_2}" Tag="1"/>
        <ComboBoxItem Content="{StaticResource ResourceKey=1_3}" Tag="2"/>
        <ComboBoxItem Content="{StaticResource ResourceKey=1_4}" Tag="3"/>
        <ComboBoxItem Content="{StaticResource ResourceKey=1_5}" Tag="4"/>
    </ComboBox>
</Grid>

I think you are not using DisplayeMemberPath="Content" properly. That is used to specify which value to display from the selected object. The selected object is not the selected ComboBoxItem but what is in the Content Property of the selected ComboBoxItem. But from your code I can see that object in your ComboBoxItems only have two properties named "Key" and "Index".
Hope this help. If I misunderstood, please let me know.


text:
Q: JSON to setAttribute() I've almost got the following working, but have run across many confusing approaches. The desire is using the key:value in the attr{} for the setAttribute() method properties, WITHOUT a framework.
Please lend a slim solution:
testDiv = document.getElementById("testDiv");

attr = {

    align:"center",
    title:"The Test Div"

};

//Possible converting JSON to String, the use in setAttribute?

for(var x in attr) alert(x + " , " + attr[ x ] );

testDiv.setAttribute( x ,  attr[ x ]);

A: You don't have JSON there, you have an object literal. Anyway, if I understand you correctly you want to set all of the specified attributes for one particular element? A loop in a function should do it easily enough if you want something re-usable:
function setMultipleAttributes(el, attributes) {
   for (var attr in attributes)
     el.setAttribute(attr, attributes[attr]);
}

var testDiv = document.getElementById("testDiv");

setMultipleAttributes(testDiv, { align : "center", title : "The Test Div" });

A: Your problem has nothing to do with "JSON" (actually just a JavaScript object literal) or setting attributes. It's this:
for(var x in attr) alert(x + " , " + attr[ x ] );

testDiv.setAttribute( x ,  attr[ x ]);

Since you do not use braces with the for loop, only the statement immediately following it is executed. If I add braces, the above code looks like this:
for(var x in attr){
    alert(x + " , " + attr[x] );
}
testDiv.setAttribute( x ,  attr[x]);

setAttribute isn't called in the loop — it's just called once at the end. Instead, you probably want…
for(var x in attr){
    alert(x + " , " + attr[x] );
    testDiv.setAttribute( x ,  attr[x]);
}


text:
Q: Ambiguous close callback on Stripe Checkout API with loading screen Is there any way inside the Stripe Checkout close callback to determine how it got triggered?
So for example, I have the following code that gets triggered when someone clicks a checkout button:
        // fade in our loading screen
        $("#loading-screen").stop(true,true).fadeIn(200);

        var handler = StripeCheckout.configure({
            key: STRIPE_PUBLISHABLE_KEY,
            image: STRIPE_ICON,
            closed: function () {
                // if user clicks close button, also hide the loading screen
                $("#loading-screen").stop(true,true).fadeOut(200);
            },
            token: function(token) {
                // post payment info back to the server via ajax
                var data = {
                    action : 'checkout',
                    paymentToken: token.id
                };
                $.post(
                    ajaxurl,
                    data,
                    function (response) {
                        // after response from server, fade out loading screen and update page or trigger error
                        $("#loading-screen").stop(true,true).fadeOut(200);
                        if (response.success) {
                            $("#checkout-form").html(response.output);
                        } else {
                            alert("unknown error. try again later.");
                        }
                    },
                    "json"
                );

            }

The idea here is when I click the close button on the payment window, or once I get some sort of response from my server, the loading screen goes away.
However, it appears that the closed callback is getting triggered not only when someone hits the close button, but also after a payment successfully completes on Stripe's end, but before my ajax call completes.
As a result, the loading screen gets removed prior to the operation's completion, which is confusing users. Obviously things can be done to optimize the slow commands server-side, but I want to try to fix this on the client-side as well.
So basically, I need to find a way to distinguish between closing via the cancel button, and closing via a successful payment and unfortunately the Stripe Checkout Documentation doesn't provide a whole lot of details on that process.
Any suggestions?

Update:
I think I may have found a way to do it, but it's contingent on the token callback always happening before the closed callback.
Basically I just set a flag that indicates whether the token callback was triggered.
        var token_triggered = false;

        // fade in our loading screen
        $("#loading-screen").stop(true,true).fadeIn(200);

        var handler = StripeCheckout.configure({
            key: STRIPE_PUBLISHABLE_KEY,
            image: STRIPE_ICON,
            closed: function () {
                // if user clicks close button, also hide the loading screen
                if (!token_triggered) {
                    $("#loading-screen").stop(true,true).fadeOut(200);
                }
            },
            token: function(token) {
                token_triggered = true;
                // post payment info back to the server via ajax
                var data = {
                    action : 'checkout',
                    paymentToken: token.id
                };
                $.post(
                    ajaxurl,
                    data,
                    function (response) {
                        // after response from server, fade out loading screen and update page or trigger error
                        $("#loading-screen").stop(true,true).fadeOut(200);
                        if (response.success) {
                            $("#checkout-form").html(response.output);
                        } else {
                            alert("unknown error. try again later.");
                        }
                    },
                    "json"
                );

            }

In the few tests I've done, it has seemed to work okay, but does anybody know if there are any guarantees that token will always trigger before closed?

Update #2:
Upon asking in the #stripe channel on freenode, I was told as of April 6, it appears Stripe has ensured that token always will fire prior to closed.
So I believe this solves my problem and allows me to distinguish between the two events.

A: As I indicated in my updates above, as of April 6, 2015 the token callback should always fire prior to the closed callback. This means we can set a flag to indicate whether or not the token callback was ever triggered, allowing us to distinguish between the events.
var token_triggered = false;
var handler = StripeCheckout.configure({
     ...
     closed: function() {
          if (!token_triggered) {
              // close button click behavior goes here
          } else {
              // payment completion behavior goes here
          }
     },
     token: function(token) {
          token_triggered = true;
     }
     ...
});


text:
Q: Collect log files from FTP into Logstash/Elasticsearch I am investigated the Elastic stack for collecting logs files. As I understand, Elasticsearch is used for storage and indexing, and Logstash for parsing them. There is also Filebeat that can send the files to the Logstash server.
But it seems like this entire stack assumes that you have root access to the server that is producing the logs. In my case, I don't have root access, but I have FTP access to the files. I looked at various input plugins for Logstash, but couldn't find something suitable.
Is there a component of the Elastic system that can help with this setup, without requiring me to write (error-prone) custom code?

A: May be you can use exec input plugin with curl. Something like:
exec {
    codec => plain { }
    command => "curl ftp://server/logs.log"
    interval => 3000}
}


text:
Q: What is the best sql data type for x.x.x What is the best data type for field with format like this X.X.X.x
Here is the sample field data
15.8.0
15.8.1
15.8.2
15.8.3
15.8.4
1.8.0
2.8.2
9.8.2
9.8.3
9.8.4
10.8.0
13.15.0.1
13.15.1.1
13.15.2.1
13.15.3.1
13.15.4.1
13.0.0
26.0.0.1
26.0.0.2

This field use as primary field of table
Thanks

A: I can't say it would be the best ("best" in what sense?) but one way to do this is to have the 4 numbers in 4 separate TINYINT columns.
You can have the PRIMARY KEY as a composite 4-column one or as a persisted column. Considering from the data provided that the 4th number can be NULL, I'd choose the persisted as primary key and add a unique constraints on the 4 columns:
create table versions
( a tinyint not null,
  b tinyint not null,
  c tinyint not null,
  d tinyint null,
  version as cast( concat( a, '.', b, '.', c,
                           case when d is null then '' else concat('.',  d) end
                   ) as varchar(15))
      persisted,
  constraint version_uq
      unique clustered (a,b,c,d),
  constraint versions_pk
      primary key (version),
) ;

Tested at rextester.com.

Another option would be to use the HierarchyID type.


text:
Q: How to use wildcards in IVY:  I want to publish my artifacts with ivy but my build path is dynamic and not static since it contains the version TAG i.e.: "build_02.14Test3".
This is from my build.xml:
<target name="go" depends="install-ivy"
            description="--> create and publish">
            <property environment="env"/>
            <fail unless="env.PUBREVISION" message="no publish revision set!"/>
        <ivy:resolve/>
        <ivy:publish resolver="components" pubrevision="${env.PUBREVISION}">
            <artifacts pattern="../Java/build_*/Release/[artifact].[ext]"/>
        </ivy:publish>
    </target>

The whole build.xml file:
<!--
   Licensed to the Apache Software Foundation (ASF) under one
   or more contributor license agreements.  See the NOTICE file
   distributed with this work for additional information
   regarding copyright ownership.  The ASF licenses this file
   to you under the Apache License, Version 2.0 (the
   "License"); you may not use this file except in compliance
   with the License.  You may obtain a copy of the License at

     http://www.apache.org/licenses/LICENSE-2.0

   Unless required by applicable law or agreed to in writing,
   software distributed under the License is distributed on an
   "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
   KIND, either express or implied.  See the License for the
   specific language governing permissions and limitations
   under the License.
-->
<project name="build-ivy" default="go" xmlns:ivy="antlib:org.apache.ivy.ant">
    <!--

        More information can be found at http://ant.apache.org/ivy/
        -->

    <!-- here is the version of ivy we will use. change this property to try a newer
         version if you want -->
    <property name="ivy.install.version" value="2.4.0" />
    <property name="ivy.jar.dir" value="${basedir}/ivy" />
    <property name="ivy.jar.file" value="${ivy.jar.dir}/ivy.jar" />

    <property name="build.dir" value="build" />
    <property name="src.dir" value="src" />

    <target name="download-ivy" unless="skip.download">
        <mkdir dir="${ivy.jar.dir}"/>
        <!-- download Ivy from artifactory so that it can be used even without any special installation -->
        <echo message="installing ivy..."/>
        <get src="https://artifactory.company.com/artifactory/virtual-maven/org/apache/ivy/ivy/${ivy.install.version}/ivy-${ivy.install.version}.jar"
             dest="${ivy.jar.file}" usetimestamp="true" username="svcbuild" password="**********************"/>
    </target>

    <!-- =================================
          target: install-ivy
            this target is not necessary if you put ivy.jar in your ant lib directory
            if you already have ivy in your ant lib, you can simply remove this
            target and the dependency the 'go' target has on it
         ================================= -->
    <target name="install-ivy" depends="download-ivy" description="--> install ivy">
        <!-- try to load ivy here from local ivy dir, in case the user has not already dropped
              it into ant's lib dir (note that the latter copy will always take precedence).
              We will not fail as long as local lib dir exists (it may be empty) and
              ivy is in at least one of ant's lib dir or the local lib dir. -->
        <path id="ivy.lib.path">
            <fileset dir="${ivy.jar.dir}" includes="*.jar"/>
        </path>
        <taskdef resource="org/apache/ivy/ant/antlib.xml"
                  uri="antlib:org.apache.ivy.ant" classpathref="ivy.lib.path"/>
    </target>

    <!-- =================================
          target: go
                    Go ivy, go!
         ================================= -->
   <target name="go" depends="install-ivy"
            description="--> create and publish">
            <property environment="env"/>
            <fail unless="env.PUBREVISION" message="no publish revision set!"/>
        <ivy:resolve/>
        <ivy:publish resolver="components" pubrevision="${env.PUBREVISION}">
            <artifacts pattern="../Java/build_*/Release/[artifact].[ext]"/>
        </ivy:publish>
    </target>

    <!-- =================================
          target: clean
         ================================= -->
    <target name="clean" description="--> clean the project">
        <delete includeemptydirs="true" quiet="true">
            <fileset dir="${src.dir}" />
            <fileset dir="${build.dir}" />
        </delete>
    </target>

    <!-- =================================
          target: clean-ivy
         ================================= -->
    <target name="clean-ivy" description="--> clean the ivy installation">
        <delete dir="${ivy.jar.dir}"/>
    </target>

    <!-- =================================
          target: clean-cache
         ================================= -->
    <target name="clean-cache" depends="install-ivy"
            description="--> clean the ivy cache">
        <ivy:cleancache />
    </target>
</project>

Basically all I wanna know is why my wildcard "*" is not working and how to fix it.
When running my pipeline I run into the issue that the wildcards are not recogniced:
[ivy:publish] :: delivering :: COMPANY#some.product;working@BUILD_PC :: 02.14Test11 :: integration :: Fri Feb 09 09:13:36 CET 2018
[ivy:publish]   options = status=integration pubdate=Fri Feb 09 09:13:36 CET 2018 validate=true resolveDynamicRevisions=true merge=true resolveId=null pubBranch=null
[ivy:publish]   delivering ivy file to D:\gr\builds\3d9e5594\0\plast\products\some.product\Java\build_*\Release\ivy.xml

BUILD FAILED
D:\gr\builds\3d9e5594\0\plast\products\some.product\ivy\build.xml:70: COMPANY#some.product;working@BUILD_PC: java.io.FileNotFoundException: D:\gr\builds\3d9e5594\0\plast\products\some.product\Java\build_*\Release\ivy.xml (The filename, directory name, or volume label syntax is incorrect)
    at java.io.FileOutputStream.open(Native Method)
    at java.io.FileOutputStream.<init>(FileOutputStream.java:212)
    at java.io.FileOutputStream.<init>(FileOutputStream.java:165)
    at org.apache.ivy.plugins.parser.xml.XmlModuleDescriptorUpdater.update(XmlModuleDescriptorUpdater.java:135)
    at org.apache.ivy.core.deliver.DeliverEngine.deliver(DeliverEngine.java:207)
    at org.apache.ivy.Ivy.deliver(Ivy.java:607)
    at org.apache.ivy.ant.IvyDeliver.doExecute(IvyDeliver.java:420)
    at org.apache.ivy.ant.IvyTask.execute(IvyTask.java:271)
    at org.apache.ivy.ant.IvyPublish.doExecute(IvyPublish.java:308)
    at org.apache.ivy.ant.IvyTask.execute(IvyTask.java:271)
    at org.apache.tools.ant.UnknownElement.execute(UnknownElement.java:293)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:601)
    at org.apache.tools.ant.dispatch.DispatchUtils.execute(DispatchUtils.java:106)
    at org.apache.tools.ant.Task.perform(Task.java:348)
    at org.apache.tools.ant.Target.execute(Target.java:435)
    at org.apache.tools.ant.Target.performTasks(Target.java:456)
    at org.apache.tools.ant.Project.executeSortedTargets(Project.java:1405)
    at org.apache.tools.ant.Project.executeTarget(Project.java:1376)
    at org.apache.tools.ant.helper.DefaultExecutor.executeTargets(DefaultExecutor.java:41)
    at org.apache.tools.ant.Project.executeTargets(Project.java:1260)
    at org.apache.tools.ant.Main.runBuild(Main.java:857)
    at org.apache.tools.ant.Main.startAnt(Main.java:236)
    at org.apache.tools.ant.launch.Launcher.run(Launcher.java:287)
    at org.apache.tools.ant.launch.Launcher.main(Launcher.java:113)

Ivy.xml as requested (Note I replaced company and product names!) :
<ivy-module version="2.0">
    <info organisation="MyOrganisation" module="Organisation.product" />
    <publications>

<artifact name="Data1" ext="cab" type="binaries" />
<artifact name="Organisation product" ext="msi" type="binaries" />
<artifact name="setup" ext="exe" type="binaries" />
<artifact name="splash" ext="bmp" type="binaries" />
<artifact name="Java/jre-8u131-windows-i586" ext="exe" type="binaries" />
<artifact name="ProdA RemTool/Data1" ext="cab" type="binaries" />
<artifact name="ProdA RemTool/ProdA RemTool 01.36" ext="msi" type="binaries" />
<artifact name="ProdA RemTool/setup" ext="exe" type="binaries" />
<artifact name="ProdA RemTool/splash" ext="png" type="binaries" />
<artifact name="ProdA RemTool/viewsimba.splash" ext="bmp" type="binaries" />

 </publications>

</ivy-module>

A: The solution to my problem was to fix the build path like this:
<artifacts pattern="../Java/build_${env.PUBREVISION}/Release/[artifact].[ext]"/>

since ${env.PUBREVISION}/ contains the TAG which is my build folder :)


text:
Q: jQuery clone() problem
Category

<select id="category" name="category[]">
<option value="0">None</option>
<option value="3">Item 1</option>
<option value="4">Item 2</option>
<option value="1">Item 3</option>
</select>

When I clicked on the button, the page turned blank except the button instead of cloning it. Is this a bug or my mistake? I've spent hours Googling but couldn't find a solution. Anyone know why?

A: Because you're using document.write(). Don't.

There are a lot of other problems with your code, as well. Here's how to make it work:
HTML
Category

    <select id="category" name="category[]">
        <option value="0">None</option>
        <option value="3">Item 1</option>
        <option value="4">Item 2</option>
        <option value="1">Item 3</option>
    </select>

<input id="addrow" style="margin-left:5px;" type="button" value="+" />

JavaScript
$(function() {
    function _addCategory() {
        var $categoryDiv = $('div.category_div').last();
        $categoryDiv.clone().insertAfter($categoryDiv);
    }

    $('#addrow').click(_addCategory);
});

http://jsfiddle.net/mattball/zYEUY/
Notes

*

*document.write(): just don't use it.

*Element IDs must be unique. The quick solution is to change id="category_div" to class="category_div" and alter the JS accordingly.

*You're already using jQuery, so there's no excuse for not writing unobtrusive JavaScript.

*Incorrect capitalization: your original code used _addcategory instead of _addCategory, so the onclick callback was undefined.