Q:

CSS3 grid layouts: New row after specific element - possible?

I've got a list of items, sorted by date.
Some of the items are in the future (green items), thus more interesting, some are in the past (brown items). I want the second group of items to start in a new row.

.grid{
  width: 120px;
  display:grid;
  grid-template-columns: repeat(3,1fr);
  grid-gap: 10px;
}
.item{
  border:1px solid black;
  height:50px;
  width:50px;
}
.green{
  background:green;
}
.brown{
  background:brown;
}

The number of overall items / items per category is constantly changing, the number of Items per row depends on screen size - that might eliminate some possible solutions to this.
I could of course split the array containing all items at a certain point and organize the output into two separate grids, like so:

.grid{
  width: 120px;
  display:grid;
  grid-template-columns: repeat(3,1fr);
  grid-gap: 10px;
  margin-bottom:10px;
}
.item{
  border:1px solid black;
  height:50px;
  width:50px;
}
.green{
  background:green;
}
.brown{
  background:brown;
}

Probably that's the easiest option. Looks like what I want to achieve & isn't too difficult to do. But anyway, I'm curious: Is there a more elegant approach to this? I was thinking something like:
.item.green + .item.brown:before {
/* force new row */
}

A:

You could target the first .brown after .green and set grid-column-start to 1.

.grid {
  width: 120px;
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  grid-gap: 10px;
}

.item {
  border: 1px solid black;
  height: 50px;
  width: 50px;
}

.green {
  background: green;
}

.brown {
  background: brown;
}

.green + .brown {
  grid-column-start: 1;
}

A:

Since you are using grid-template-columns, you won't be able to acheive this with before or after, you would need to set the grid-column-start to 1 with the  item.green + .item.brown selection:

.grid{
  width: 120px;
  display:grid;
  grid-template-columns: repeat(3,1fr);
  grid-gap: 10px;
}
.item{
  border:1px solid black;
  height:50px;
  width:50px;
}
.green{
  background:green;
}
.brown{
  background:brown;
}
.item.green + .item.brown {

    grid-column-start: 1;

}


Q:

Are there any other ways to be able to change ability sets besides dying?

As far as I know, the only way you can change ability sets when playing online is to die at the hands of another player or get stunned in a "team" game.  Unfortunately it's just not possible to commit suicide without getting assistance from your pursuer and it's inconvenient giving free points to a pursuer/target just because you want to change abilities.
Are there any other methods to be able to switch ability sets in the game that I'm not aware of?
On a side note, this question stems from this PC bug that prevents me from changing ability sets in team games between rounds.  I don't get the "round changing" screen, I'm just left wandering the map until everyone else spawns which makes playing team games for me very frustrating.

A:

There are unfortunately no other ways than the two you mention to change the ability set during a session. It's indeed sometimes frustrating as you say (even more I can imagine if you experience a bug on top of it).
If you have to die, try heading for an honorable death, canceling your pursuer's bonuses.


Q:

Determining a calendar year (with/without leap-years)

UPDATE: The moral of the story is to trust a gut feeling and not to go looking for problems.  In the end the user reported issue was in a completely different area and as Jon highlighted we introduced a bug in our testing, which we missed because the result appeared to validate what were looking for.
Original Question:
In many applications there is a requirement to display a start / end date, where the end date encompasses one calendar year.  So if the start date is 1st Jan 2012, the end date is 31st Dec 2012.  The basic rule is add a year, take a day off - as an extension method that you be:
    public static DateTime CalendarYear(this DateTime dateTime)
    {
        return dateTime.AddYears(1).AddDays(-1);
    }

However, the code above does not cope with leap years!  Our unit tests flagged up 365 occurences where the expected date date did not match the determined end date when testing from a start date of 1st Jan 2011 thru to 31st Dec 2014. The dates that define the error boundaries are:

Start Date: 01 Mar 2011, Expected End Date: 28 Feb 2012: Actual End
Date: 29 Feb 2012
Start Date: 28 Feb 2012, Expected End Date: 26 Feb
2013: Actual End Date: 27 Feb 2013

Dates before 1st Mar 2011 behave as expected, those after 28th Feb 2012 behave as expected.
I know the reason that the tests are failing is because the start / end dates contain the 29th Feb leap year event, but does anyone have a simple, reliable suggestion (which copes with the leap year event) to replace the basic "AddYears(1).AddDays(-1)" to quickly determine a calendar year ?

A:

It looks to me like the "actual" versions are correct... why would you expect "one year minus a day" from Feb 28th to be Feb 26th? How can you say that it encompasses a calendar year if Feb 27th isn't included anywhere?
If you really want those values, have you considered just calling AddDays(364) instead?


Q:

Populating HTML Divs (projects) from a SQL database

I have finaly took the breath again to work on my portfolio. I am populating an div with data out of a SQL database. It is working, but something tells me I am using PHP the wrong way, and I should not have PHP and HTML codes mixed up in eachother.
My PHP Output is like this:

{ Showcase }

    <?php
    while($row = mysqli_fetch_assoc($result))
        {
            $typeDescription = $row['type_description'];
            $typeDescription = ucfirst($typeDescription);

            echo ('
');
            echo ('
');
            echo ('
'.$typeDescription."
");
            echo ('');
            echo ('');
            echo ('
');
            echo ('');
            echo('
'.$row['project_year'].'
');
            echo('
'.$row['project_name'].'
');
            echo('
'.$row['project_description']."
");
            echo ('
');
        }
    ?>

What is a more effective way to achieve what I want, (Load Name / Image / Content) out of a database and for each project create an div so my projects will be sorted on my Showcase (Portfolio Page)?
I have searched around the boards, and even looked up for video's if there is a possible way to make some neater code. But all i get are Form Application Tutorials with Ajax.
I hope you guys can help me out!
Kind Regards!!

A:

The problem with your approach is that you are mixing presentation with your business logic.  This is like
using HTML
RED

instead of using HTML/CSS
RED
 and p { color:red}
One approach to do this in PHP involves template engines such as twig, eg
require_once '/path/to/vendor/autoload.php';

$loader = new Twig_Loader_Array(array(
    'index' => 'Hello {{ name }}!',
));
$twig = new Twig_Environment($loader);

echo $twig->render('index', array('name' => 'Fabien'));


Q:

Cannot update listview

In my GUI I have a listview in which I want to change the value of a cell.  I've tried everything and everytime I call lv_modify() it returns 0 which means something was in error - which also means the change doesn't get made...
Here is my sample script - you should be able to run it just like this.  Right-click on an item in any of the listview controls and try to edit the text.  The messagebox reports the variables.
Where am I going wrong?
;-------- http://ahkscript.org/boards/viewtopic.php?f=5&t=3656 ---
MODIFIED=20140531
Tabnumber:=1
gui, mainui:new, hwndmainui, ListViews On Tab2
gui,add, Tab2,  vTabnumber AltSubmit, one|two|three|four
gui,tab, one
gui,add, listview, r5 vlistview1 hwndlistview1 gListViewEvents -Readonly +altsubmit -multi, col1|col2
LV_Add("", "bob", "harry")
LV_Add("", "first", "111111111")
gosub,width1
gui,tab, two
gui,add, listview, r5 vlistview2 hwndlistview2 gListViewEvents -Readonly +altsubmit -multi, col1|col2
LV_Add("", "george", "harvey")
LV_Add("", "second", "222222")
gosub,width1
gui, tab, three
gui,add, listview, r5 vlistview3 hwndlistview3 gListViewEvents -Readonly +altsubmit -multi, col1|col2
LV_Add("", "michael", "richard")
LV_Add("", "third", "33333333")
gosub,width1
gui, tab, four
gui,add, listview, r5 vlistview4 hwndlistview4 gListViewEvents -Readonly +altsubmit -multi, col1|col2
LV_Add("", "harold", "marcel")
LV_Add("", "fourth", "44444")
gosub,width1
gui, show

RETURN

mainuiGuiclose:
exitapp

width1:
T1=70
T2=140
LV_ModifyCol(1,T1)
LV_ModifyCol(2,T2)
return

LISTVIEWEVENTS:
current_listview := a_guicontrol
gui, mainui:listview, %current_listview%

if(A_GuiEvent == "Normal"){
    LV_GetText(current_var, A_EventInfo, 1)
    LV_GetText(current_val, A_EventInfo, 2)
    msgbox, %current_var% : %current_val%
}
if(A_GuiEvent == "RightClick"){
    mousegetpos, mousex, mousey
    LV_GetText(current_var, A_EventInfo, 1)
    LV_GetText(current_val, A_EventInfo, 2)
    current_row := A_EventInfo
    gosub, EDITListViewVALUE
}
RETURN

;------------------------------------------------------------------------------------
EDITListViewVALUE:

gui, %current_listview%Editor:new
gui, +resize
gui, add, text, , Edit Value
gui, add, edit, w300 h50 -wrap r1 vnew_%current_listview%, %current_val%
Gui, Font, S10 CPurple Bold
Gui, Add, Button,   x12 gListViewEditorACCEPT default, Accept
Gui, Add, Button,   x+4 gListViewEditorCANCEL, Cancel
Gui, Show, center, Data Editor
Return

ListViewEditorACCEPT:
gui, %current_listview%Editor:submit
;now assign the new value to it's matching variable
%current_var% := new_%current_listview%

msgbox % "Current Row=" . current_row . "`rListView=" . current_listview . "`rOld Value=" . current_val . "`rNew Value=" . new_%current_listview%

gui, mainui:listview, %current_listview%
msgbox % "Success=" . lv_modify(current_row, "Col1", new_%current_listview%)
Return

ListViewEditorCANCEL:
gui, %current_listview%Editor:cancel
Return

[update]
It looks like the access to the default listview is lost, despite the fact that 'gui, mainui:listview, %current_listview%' is called just before lv_modify.  But lv_modify works fine if not called in the ListViewEditorACCEPT sub.

A:

Ah!  The trick was to reset the thread operation back to the main GUI.  When we opened the second GUI window, it took over the thread operation.
This goes at the tail end of the ListViewEditorACCEPT sub.
;Reset the thread operation to the main GUI
gui, mainui:default

;Now reset the default listview
gui, mainui:listview, %current_listview%


Q:

python 3.x xml parsing similar to plistlib?

I have GPS data stored as as .tcx file.
This is a xml file (begging of file below)
<?xml version="1.0" encoding="utf-8"?>
<TrainingCenterDatabase xmlns="http://www.garmin.com/xmlschemas/TrainingCenterDatabase/v2" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:tp1="http://www.garmin.com/xmlschemas/TrackPointExtension/v1" xmlns:gpx="http://www.topografix.com/GPX/1/1" xsi:schemaLocation="http://www.garmin.com/xmlschemas/TrainingCenterDatabase/v2 http://www.garmin.com/xmlschemas/TrainingCenterDatabasev2.xsd">
    <Activities>
        <Activity Sport="Other">
            <Id>2012-01-17T11:44:35Z</Id>
            <Lap StartTime="2012-01-17T11:44:35Z">
                <TotalTimeSeconds>0</TotalTimeSeconds>
                <DistanceMeters>0</DistanceMeters>
                <Calories>0</Calories>
                <Intensity>Active</Intensity>
                <TriggerMethod>Manual</TriggerMethod>
                <Track>
                    <Trackpoint>
                        <Time>2012-01-17T11:44:35Z</Time>
                        <Position>
                            <LatitudeDegrees>59.720211518183351</LatitudeDegrees>

The only similar thing I have worked with have been apple .plists which use a similar format, although the info is nested within a <dictionary> tag I believe.
Where the following would give me nested dictionaries...
import plistlib
pl = plistlib.readPlist('/Users/name/Documents/file.plist')

for sub_dict in pl:
    print(sub_dict['keyA'])
    print(sub_dict['keyD'])
    print(sub_dict['keyE'])
    print(sub_dict['keyG'])

I am aware of xml.dom.minidom, etree and lxml, but I am having trouble working out how to get the same output as the above plistlib module gives me.
My final aim is to be able to merge selected keys from the two data sets together. One step at a time...
EDIT -----------------
I have got something working:
from xml.dom.minidom import parse
doc = parse('/Users/name/Documents/GPS/gps.tcx')
lat = doc.getElementsByTagName("LatitudeDegrees")
time = doc.getElementsByTagName("Time")

for x in lat:
    print(x.firstChild.data)

A:

I had to add closing tags to your posted XML so the lxml parser could parse it.
Once that is done, the Time and LatitudeDegrees data can be pulled out using calls to doc.xpath.
import lxml.etree as ET
import io

content='''<?xml version="1.0" encoding="utf-8"?>
<TrainingCenterDatabase xmlns="http://www.garmin.com/xmlschemas/TrainingCenterDatabase/v2" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:tp1="http://www.garmin.com/xmlschemas/TrackPointExtension/v1" xmlns:gpx="http://www.topografix.com/GPX/1/1" xsi:schemaLocation="http://www.garmin.com/xmlschemas/TrainingCenterDatabase/v2 http://www.garmin.com/xmlschemas/TrainingCenterDatabasev2.xsd">
    <Activities>
        <Activity Sport="Other">
            <Id>2012-01-17T11:44:35Z</Id>
            <Lap StartTime="2012-01-17T11:44:35Z">
                <TotalTimeSeconds>0</TotalTimeSeconds>
                <DistanceMeters>0</DistanceMeters>
                <Calories>0</Calories>
                <Intensity>Active</Intensity>
                <TriggerMethod>Manual</TriggerMethod>
                <Track>
                    <Trackpoint>
                        <Time>2012-01-17T11:44:35Z</Time>
                        <Position>
                            <LatitudeDegrees>59.920211518183351</LatitudeDegrees>
</Position>
</Trackpoint>
</Track>
</Lap>
</Activity>
</Activities>
</TrainingCenterDatabase>
'''

doc = ET.fromstring(content)

ns = {'ns':'http://www.garmin.com/xmlschemas/TrainingCenterDatabase/v2'}
for trackpoint in doc.xpath('//ns:Trackpoint', namespaces = ns):
    print(trackpoint.xpath('(ns:Time|ns:Position/ns:LatitudeDegrees)/text()', namespaces = ns))

yields
['2012-01-17T11:44:35Z', '59.920211518183351']


Q:

Accessing individual item from model in partial view

In MVC 5, i am looping through the Model item in my view.
@foreach (var item in Model.invoices)

During each loop i am calling a partial view
@{
       Html.RenderPartial("~/Views/Invoice/CommonSegment.cshtml", item);
 }

But i am not able to access model ('item') in CommonSegment.cshtml
Snap from Visual Studio

                @item.orderId.label
                @item.orderId.value

I am referring to same model in View and PartialView.
I wouldn't like to go with ViewBag.
Thanks in advance.

A:

May be you can do this during the Loop,
@foreach (var item in Model.invoices)
{
   @Html.RenderPartial("~/Views/Invoice/CommonSegment.cshtml", item);
}

But why writing foreach loops when you can use editor templates.
@model IEnumerable<Invoices>
@Html.EditorForModel()

and then simply define the corresponding editor template (~/Views/Invoice/CommonSegment.cshtml) It will automatically rendered for each element of your model:
@model Invoices

    @Html.EditorFor(x => x.abc)


Q:

Rewrite URLs with .htaccess but ignore specific Directories

I have a directory on a site:

http://example.com/directory/

In it I have a .htaccess file.
I want it to take any URL like this:

http://example.com/directory/section/day/

And rewrite it to:

http://example.com/directory/index.php?arg1=section&arg2=day

Except for any URLs that refer to these directories:

http://example.com/directory/css/
http://example.com/directory/javascript/
http://example.com/directory/images/

I have the first part working, but unable to tell it to exclude files in certain directories:
Options +FollowSymlinks
RewriteEngine on

RewriteRule ^([^/]+)/([^/]+) index.php?arg1=$1&arg2=$2 [NC]

Update:
This works in a very basic and simple sense:
RewriteRule ^css - [L,NC]
RewriteRule ^javascript - [L,NC]
RewriteRule ^images - [L,NC]
RewriteRule ^([^/]+)/([^/]+) index.php?arg1=$1&arg2=$2 [NC]

but I'm sure there is a more elegant solution?

A:

I think the keyword you're looking for is RewriteCond. It's pretty similar to what you ended up with.
RewriteCond %{REQUEST_URI} !^(css|javascript|images)
RewriteRule ^([^/]+)/([^/]+) index.php?arg1=$1&arg2=$2 [NC]


Q:

Creating gridview with 3 rows of imageviews that fill the whole screen

I have been searching everywhere for similar solutions but none seem to work for me.
On my first screen I will have a gridview which consists of 1 column and 3 rows vertically. Each row will have an imageview and a partially transparent textview on top of the text view. The imageviews span the screen width fine. My only problem is that the 3 image views do not span the full screen vertically, there is space inbetween rows, although I have tried many methods to fix this. I will post up my xml files and code:
row_layout.xml - this is the gridview items
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical" >

<ImageView
    android:id="@+id/item_image"
    android:adjustViewBounds="true"
    android:scaleType="fitXY"
    android:layout_width="fill_parent"
    android:layout_height="180dp"
    android:src="@drawable/season1">
</ImageView>

<TextView
    android:id="@+id/item_text"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignLeft="@+id/item_image"
    android:layout_alignTop="@+id/item_image"
    android:layout_alignRight="@+id/item_image"
    android:layout_alignBottom="@+id/item_image"
    android:gravity="bottom|left"
    android:textSize="30sp"
    android:textAlignment="center"
    android:lines="1"
    android:layout_marginTop="145dp"
    android:background="#99000000">

</TextView>

main.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="fill_parent"
tools:context=".MainActivity" >

<GridView
    android:id="@+id/gridView1"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:layout_margin="0dp"
    android:padding="0dp"
    android:gravity="center"
    android:numColumns="1"
    android:fitsSystemWindows="true"
    android:stretchMode="columnWidth" >
</GridView>

My custom adapter:
public class CustomGridViewAdapter extends ArrayAdapter<Item> {
Context context;
int layoutResourceId;
ArrayList<Item> data = new ArrayList<Item>();

public CustomGridViewAdapter(Context context, int layoutResourceId, ArrayList<Item> data) {
    super(context, layoutResourceId, data);
    this.layoutResourceId = layoutResourceId;
    this.context = context;
    this.data = data;
}

@Override
public View getView(int position, View convertView, ViewGroup parent) {
    View row = convertView;
    RecordHolder holder = null;

    if (row == null) {
        LayoutInflater inflater = ((Activity) context).getLayoutInflater();
        row = inflater.inflate(layoutResourceId, parent, false);
        row.setMinimumHeight(MainActivity.height1/3);

        holder = new RecordHolder();
        holder.txtTitle = (TextView) row.findViewById(R.id.item_text);
        holder.imageItem = (ImageView) row.findViewById(R.id.item_image);
        row.setTag(holder);
    } else {
        holder = (RecordHolder) row.getTag();
    }

    Item item = data.get(position);
    holder.txtTitle.setText(item.getTitle());
    holder.imageItem.setImageBitmap(item.getImage());// my image
    return row;

}

static class RecordHolder {
    TextView txtTitle;
    ImageView imageItem;

}

}
MainActivity:
public class MainActivity extends ActionBarActivity {

GridView gridView;
ArrayList<Item> gridArray = new ArrayList<Item>();
CustomGridViewAdapter customGridAdapter;
public static int height1;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    //this.requestWindowFeature(Window.FEATURE_NO_TITLE);
    setContentView(R.layout.main);

    ActionBar ab = getActionBar();
    ab.setDisplayShowTitleEnabled(false);
    ab.setDisplayShowHomeEnabled(false);

    Resources res = this.getResources();

    Bitmap bMap = BitmapFactory.decodeResource(res, R.drawable.actionbar);
    BitmapDrawable actionBarBackground = new BitmapDrawable(res, bMap);
    ab.setBackgroundDrawable(actionBarBackground);

    //set grid view item

    Bitmap season1Icon = BitmapFactory.decodeResource(res, R.drawable.season1);
    Bitmap season2Icon = BitmapFactory.decodeResource(res, R.drawable.season2);
    Bitmap season3Icon = BitmapFactory.decodeResource(res, R.drawable.season3);

    gridArray.add(new Item(season1Icon,"Season 1"));
    gridArray.add(new Item(season2Icon,"Season 2"));
    gridArray.add(new Item(season3Icon,"Season 3"));

    DisplayMetrics metrics = new DisplayMetrics();
    getWindowManager().getDefaultDisplay().getMetrics(metrics);
    height1 = metrics.heightPixels;

    gridView = (GridView) findViewById(R.id.gridView1);
    customGridAdapter = new CustomGridViewAdapter(this, R.layout.row_grid, gridArray);

    gridView.setAdapter(customGridAdapter);

    gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        public void onItemClick(AdapterView<?> parent, View v,
                                int position, long id) {
            Intent a = new Intent(MainActivity.this, House.class);
            a.putExtra("Position", position);
            startActivity(a);
        }

    });
}

}
Any help will be greatly appreciated, I've spent hours trying to fix this!

A:

Dynamically set the layout params of your imageview, once you know the height of the screen.
if (row == null) {
    LayoutInflater inflater = ((Activity) context).getLayoutInflater();
    row = inflater.inflate(layoutResourceId, parent, false);
    //row.setMinimumHeight(MainActivity.height1/3);  //don't need this, since wrap content will make the row height match your image view's

    holder = new RecordHolder();
    holder.txtTitle = (TextView) row.findViewById(R.id.item_text);
    holder.imageItem = (ImageView) row.findViewById(R.id.item_image);

    holder.imageItem.setLayoutParams(new RelativeLayout.LayoutParams(LayoutParams.MATCH_PARENT, MainActivity.height1/3);
    row.setTag(holder);
} else {
    holder = (RecordHolder) row.getTag();
}


Q:

Android how to check gps is connected to the satellites?

i got this gps method:
// GPS
    private void addGPSListener() {

        globalconstant.db.setVersion(1);
        globalconstant.db.setLocale(Locale.getDefault());
        globalconstant.db.setLockingEnabled(true);

        final String gps =

        "CREATE TABLE IF NOT EXISTS GPS_Values ("

                + "id INTEGER PRIMARY KEY AUTOINCREMENT, Latitude float(10, 8), Longitude float(10, 8),Accuracy INTEGER,Speed INTEGER,City TEXT,timestamp TIMESTAMP);";
        globalconstant.db.execSQL(gps);

        Log.d("FESTIVALE :: ", "Frissítési idő: "
                + globalconstant.gps_update_value);
        float f = Float.valueOf(globalconstant.gps_update_value.trim())
                .floatValue();
        float update = f * 1000;

        globalconstant.mlocManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
        globalconstant.mlocListener = new MyLocationListener();
        globalconstant.mlocManager.requestLocationUpdates(
                LocationManager.GPS_PROVIDER, (long) update, 5f,
                globalconstant.mlocListener);

        // if(Global.getInstance().currentGPSLocation != null){
        //
        // }

    }

    public class MyLocationListener implements LocationListener {

        public void onLocationChanged(Location loc) {

            float szel = (float) loc.getLatitude();
            float hossz = (float) loc.getLongitude();
            int horiAcc = (int) (loc.getAccuracy());
            // int speed=(int) ((loc.getSpeed()*3600)/1000); //sebesség km/h-ban
            int speed = 0;

            if (loc.hasSpeed()) {
                speed = (int) ((loc.getSpeed() * 3600) / 1000); // sebesség
                                                                // km/h-ban
            } else {
                speed = 0;
            }

            String test = String.format("%.08f", szel);
            String test2 = String.format("%.08f", hossz);

            Geocoder geocoder = new Geocoder(main.this, Locale.getDefault());
            try {
                List<Address> addresses = geocoder.getFromLocation(szel, hossz,
                        1);
                city = addresses.get(0).getLocality();
            } catch (IOException e) {
                e.printStackTrace();
            }

            ContentValues gps_values = new ContentValues();

            gps_values.put("Latitude", test);
            gps_values.put("Longitude", test2);
            gps_values.put("Accuracy", horiAcc);
            gps_values.put("Speed", speed);
            gps_values.put("City", city);

            SimpleDateFormat dateFormat = new SimpleDateFormat(
                    "yyyy-MM-dd HH:mm:ss");
            Date date = new Date(System.currentTimeMillis());

            gps_values.put("timestamp", dateFormat.format(date));

            try {
                globalconstant.db.beginTransaction();
                globalconstant.db.insert("GPS_Values", null, gps_values);
                globalconstant.db.setTransactionSuccessful();
            } finally {
                globalconstant.db.endTransaction();
            }

            Log.d("FESTIVALE :: ",
                    "Hely " + test + ", " + test2 + " , " + horiAcc + " , "
                            + speed + " , " + city + ","
                            + dateFormat.format(date));
            // String Text = "My current location is: " + "Latitude = "
            // + loc.getLatitude() + "\nLongitude = " + loc.getLongitude();

            // Toast.makeText(getApplicationContext(), "Hely" +test + "\n" +
            // test2 + "\n" + horiAcc + "\n" +speed + "\n" +city,
            // Toast.LENGTH_SHORT)
            // .show();

        }

        public void onProviderDisabled(String provider) {
            Toast.makeText(getApplicationContext(), "Gps Disabled",
                    Toast.LENGTH_SHORT).show();
            DialogInterface.OnClickListener dialogClickListener = new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int which) {
                    switch (which) {
                    case DialogInterface.BUTTON_POSITIVE:
                        // show gps otions
                        Intent gpsOptionsIntent = new Intent(
                                android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS);
                        startActivity(gpsOptionsIntent);
                        break;

                    case DialogInterface.BUTTON_NEGATIVE:
                        dialog.cancel();
                        break;
                    }
                }
            };

            AlertDialog.Builder builder = new AlertDialog.Builder(main.this);
            builder.setMessage("A GPS nincs aktiválva!\nAktiválja most?")
                    .setPositiveButton("Aktivál", dialogClickListener)
                    .setNegativeButton("Nem", dialogClickListener).show();
        }

        public void onProviderEnabled(String provider) {
            Toast.makeText(getApplicationContext(), "Gps Enabled",
                    Toast.LENGTH_SHORT).show();

        }

        public void onStatusChanged(String provider, int status, Bundle extras) {
            /* This is called when the GPS status alters */
            switch (status) {
            case LocationProvider.OUT_OF_SERVICE:
                Log.v(tag, "Status Changed: Out of Service");
                Toast.makeText(main.this, "Status Changed: Out of Service",
                        Toast.LENGTH_SHORT).show();
                break;
            case LocationProvider.TEMPORARILY_UNAVAILABLE:
                Log.v(tag, "Status Changed: Temporarily Unavailable");
                Toast.makeText(main.this,
                        "Status Changed: Temporarily Unavailable",
                        Toast.LENGTH_SHORT).show();
                break;
            case LocationProvider.AVAILABLE:
                Log.v(tag, "Status Changed: Available");
                Toast.makeText(main.this, "Status Changed: Available",
                        Toast.LENGTH_SHORT).show();
                break;
            }

        }
        public void onGpsStatusChanged(int event) {
            if (event == GpsStatus.GPS_EVENT_FIRST_FIX) {
                // showMessageDialog("GPS fixed");
                Toast.makeText(getApplicationContext(), "GPS fixed",
                        Toast.LENGTH_SHORT).show();
            }
        }
    }// gps vége

I want to make a simple loader dialog until it's connected to the satellite.
How can i manage that? how can i check that it connected to the satellite first before this method is called?
Thanks for your answers!

A:

You need to implement GpsStatus.Listener for this.
for example,
public class MyActivity extends Activity implements GpsStatus.Listener
{
         ...
         ...
         ...
         // add listener into locationManager
        locationManager.addGpsStatusListener(this);

       @Override
       public void onGpsStatusChanged(int)
       {

          switch (event)
         {
            case GpsStatus.GPS_EVENT_SATELLITE_STATUS:
            break;
            case GpsStatus.GPS_EVENT_FIRST_FIX:   // this means you  found GPS Co-ordinates
            break;
            case GpsStatus.GPS_EVENT_STARTED:
            break;
            case GpsStatus.GPS_EVENT_STOPPED:
            break;
          }
       }
}


Q:

Javascipt при событии onclick изменяются два разных Id

Нужно чтобы при нажатии на ссылку, менялась картинка и описание. Они надятся в разных id и далеко друг от друга на странице.
Например если использовать такую функцию, то менятся будет один и с одними данными. А нужно чтобы данные брались с двух разных скрипов и вставлялись в разные места.
function getColorList(id, type, desc, link)
{
    jQuery.ajax({url: "/catalog/colors.php",
        dataType: "html",
        type: "GET",
        data: { c: id, types: type, desc: desc},
        success: function(msg) {
            //alert(msg);
            document.getElementById('colCont').innerHTML = msg;
        },
        error: function(XMLHttpRequest, textStatus, errorThrown) {
            //alert('Ошибка');
        }
    });
};

A:

var elements = new Array('id1','id2','id3');
for(idAttr in elements){
 element = document.getElementById(idAttr);
 element.onclick = function(id, type, desc, link){
  getColorList(id, type, desc, link);
 }
}


Q:

Golang: Error while make test: signal: killed

I am getting this error while running make test on a Golang project:
signal: killed
FAIL <package name>
make: *** [test] Error 1

The same code was running perfectly fine until yesterday.
Note: I tried doing make test on other branches also but same result.

A:

UPDATE on 04/27/2017:
The new Go1.8.1 (released 2017/04/07) fixed this issue. Please download and install the latest version.
OLD ANSWER:
Mainly the reason was that Command Line Tool 8.3 is not compatible.
According to the solutions from https://github.com/golang/go/issues/19734:

Remove /Library/Developer/CommandLineTools first, download and install Command Line Tool 8.2 from https://developer.apple.com/download/more/?name=Xcode

OR

use -ldflags -s option for compilation or run


Q:

Ist "Arbeiten in die Tourismusbranche" korrekt?

Ist "Arbeiten in die Tourismusbranche" korrekt? There is no subject on this sentence, so we could not say "Arbeiten in der Tourismusbranche" because there is not a reference to make an indirect complement. If it's Dative, I would like to know where is the linguistic explanation.

A:

Es spielt keine Rolle, ob es ein Subjekt gibt oder nicht.
Es spielt auch keine Rolle, ob es ein Verb gibt oder nicht.
Es kommt nur darauf an,
ob "in" mit einer Richtungsangabe (*) gebraucht wird
(dann steht der Akkusativ),
oder nicht
(dann steht der Dativ).
Das gilt selbst dann, wenn gar kein Beziehungswort vorhanden ist,
zum Beispiel in Überschriften oder bei Zeitangaben:
"Im Juni 2019", "Im Urlaub", "In der Natur",
"In guten und in schlechten Zeiten",
"Europa im Mittelalter", "Jobs im Handwerk"
(alle mit Dativ).
(*) Auch wenn "in" temporal gebraucht wird, kann es sich manchmal um eine Richtungsangabe handeln. Zum Beispiel steht bei "Tanz in den Mai" der Akkusativ, da es sich um eine Veranstaltung vom 30. April bis zum 1. Mai handelt. Meist steht bei Zeitangeben aber "in" mit Dativ.

A:

Forget about direct vs. indirect objects (or complements, as you put it) because they don't match accusative vs. dative objects. They do it four out of five times and that fifth time they don't will drive you nuts. Forget about this concept. It does not help you in German.
But this isn't the problem you face with this snippet in either case.

What this snippet is about is an adverbial featuring one of the nine dual-way-prepositions an, auf, hinter, in, neben, über, unter, vor, zwischen. These prepositions

require the accusative when a direction is meant.
require the dative when a place is meant.

IMPORTANT: this rule only applies to these nine prepositions. Other prepositions may require the accusative and mean a place or require the dative and mean a direction, or even require the genitive. Some change the case depending on whether they are used as a preposition or postposition. As always in German, it's quite a mess.

Arbeiten in die Tourismusbranche

Die Tourismusbranche is put in accusative in your example. It's the preposition in, so this is a direction.
What should that even mean?
You are talking about working at a place, not in some direction. So it must be

Arbeiten in der Tourismusbranche

You could of course use arbeiten with a direction in another context, e.g.

Der Bohrer arbeitet sich in die Wand.


Q:

Security evaluation during project management

Generally speaking.
How do a project manager evaluate and track the security issue for a project? Or is there any online resource that I can use as a reference ?

A:

I would say that you would track this like everything else you track on your project.
Make sure that there is an architecture and project requirement review -- go though all aspect of the architecture and design and document any issues and questions as you go along.  Depending on your application, it may include securing external communication and communication between different parts of the application, and understand any possibilities for  malicious user input.  If your application store any data, review what data is stored, and ask "what would happen if the data was lost or leaked".   Understand how all sensitive data store is encrypted, and make sure that user passwords are never stored  (store a oneway hash instead).   Review how/if any encryption keys can be rotated, so that loss/leak of key does not mean compromise of security.
Document all issues and questions found in your favorite bug tracking and task management tool, even if just as reminder to get back and inspect actual implementation.


Q:

How to fix 'Invalid operands to binary expression' error in C++

I'm trying to make a program which saves in an object, all names got from another object, for example I have class Cheltuieli which saves a char and I have class Repo which saves an array with chars from Cheltuieli
I've tried changing cout << *c; with cout << *c->getName(); and I only get 1 letter: p instead of ["pizza", "pizza"]
Mancare.hpp
#ifndef Mancare_hpp
#define Mancare_hpp

class Cheltuieli{
private:
    char* name;
public:
    Cheltuieli();
    Cheltuieli(char* n);
    ~Cheltuieli();
    void setName(char* n);
    char* getName();
};

#endif

Mancare.cpp
#include "Mancare.hpp"
#include <string.h>

Cheltuieli::Cheltuieli()
{
    this -> name = NULL;
}
Cheltuieli::Cheltuieli(char* n)
{
    this -> name = new char[strlen(n) + 1];
    strcpy(this -> name, n);
}

Cheltuieli::~Cheltuieli()
{
    if(this -> name != NULL)
    {
        delete[] this -> name;
        this -> name = NULL;
    }
}

void Cheltuieli::setName(char *n)
{
    if(this -> name)
        delete[] this -> name;
    this -> name = new char[strlen(n) + 1];
    strcpy(this -> name, n);
}

char *Cheltuieli::getName()
{
    return this -> name;
}

void Repo::addElement(Cheltuieli &c)
{
    this -> cheltuieli[this -> size] = c;
    this -> size++;
}

Cheltuieli* Repo::getAll()
{
    return this -> cheltuieli;
}

char* const ps = "pizza";
Cheltuieli a = Cheltuieli(ps);

Repo n = Repo();
n.addElement(a);
n.addElement(a);

Cheltuieli* c = n.getAll();
cout << *c;

I get the output: 0x100503b38 with error Invalid operands to binary expression ('std::__1::ostream' (aka 'basic_ostream') and 'Cheltuieli')
Thank you!

A:

From what I can tell, the Cheltuieli class is implementing a very small subset of what's already done in the std::string class - but it's incomplete, so if you do:
Cheltuieli orig("something");
Cheltuieli cpy = orig;

both orig and cpy will have a name member pointing at the same address because of the default copy constructor. Read about The rule of three/five/zero.
Similarly, the Repo class seems to be implementing something close to a std::vector. I suggest that you don't start fiddling about with raw pointers but to use the standard classes for this. You could even make aliases for them:
using Cheltuieli = std::string;
using Repo = std::vector<Cheltuieli>;

Used like this:
Cheltuieli a = "pizza";
Repo n;
n.push_back(a);
n.push_back(a);

for(auto& cheltuieli : n) {
    std::cout << cheltuieli << "\n";
}


Q:

Why does monodevelop on linux only provide an "any cpu" platform?

I am building a c# console application on linux. But all of my applications I have built are in x86 architecture.
When I go into
Solution Options -> Configurations -> Add
the only Platform option I get is Any CPU
How do I get a 64-bit build configuration?

A:

Any CPU will pick the best option for your particular architecture, but your project will still build x86 even if you are on x64 if you have your compiler set to x86.
Somehow my Project Options -> Build -> Compiler -> Platform Target got set to x86. I'm not sure if it was me updating xaramin studio/monodevelop or what that caused that to get reverted to x86 but at some point i had correctly set that to x64.
Now that I moved the compiler back to x64 and rebuilt, i have a 64 bit application building again!
So something to watch out for if you are someone else who is seeing that same problem.


Q:

jQuery: change background color after animation completes

I'm having trouble with my jQuery right now. What I want is that the background color is changed after the animation completes. I haven't been able to figure out how to make it work. I don't understand there are no console errors.
http://jsfiddle.net/4pmzf/
jQuery:
$("#slider").toggle(function () {
    $(this).animate({
        "height":"100px"
    }, 1000).addClass('red');
}, function () {
    $(this).animate({
        "height":"20px"
    }, 1000).removeClass('red');
});

CSS
#slider {
    width: 100%;
    background: black;
    height: 20px;
    cursor: pointer;
}
.red {
    background: red;
}

A:

This is a specificity issue. The initial background declaration has a higher specificity because it was declared with an id. You could solve this by overwriting it with a more specific selector:
UPDATED EXAMPLE HERE
#slider.red {
    background:red;
}

The initial selector, #slider, has a specificity of 100.
The new selector, #slider.red, has a slightly higher specificity of 110.
Aside from this, the background really isn't being changed after the animation completes. I'd suggest adding a callback/complete function to the animation(s)..
CALLBACK EXAMPLE HERE
$("#slider").toggle(function () {
    $(this).animate({
        "height":"100px"
    }, 1000, function(){
        $(this).css('background','red');
    });
}, function () {
    $(this).animate({
        "height":"20px"
    }, 1000, function(){
        $(this).css('background','');
    });
});

Also.. rather than changing classes, it's probably better to just modify the CSS.


Q:

Nested Cell Structure in MATLAB

I am attempting to organize a large amount of data into nested structures in MATLAB and I would like for each structure to contain a cell array but I get

A dot name structure assignment is illegal when the structure is empty.  Use a subscript on the structure.

Example of code:
Year.Org1 = struct('Set1',{},'Set2',{});
Year.Org2 = struct('Set1',{},'Set2',{});

and then I want Set1/Set2/etc to be cell arrays of n-rows with column 1 str, column 2 str, column 3 value, and so on.
Any advice on initializing this structure and then accessing various parts would be greatly appreciated.

A:

With single curly braces the structure is initialized empty. You can achieve what you want by doubling the curly braces:
Year.Org1 = struct('Set1',{{}},'Set2',{{}});

Best,


Q:

Spring REST API for posting jar file

I am using RESTful endpoints  for some file operations. I would want to post a jar file to my service via REST , I tried below approach but still it fails, I almost tried googling but could not find any solution.
@RestController
public class MyController {
 ...

@RequestMapping(value="/jobs/upload", method=RequestMethod.POST)
public @ResponseBody ResponseEntity<Void> handleFileUpload(HttpEntity<byte[]> requestEntity){
    byte[] payload = requestEntity.getBody();
    InputStream logo = new ByteArrayInputStream(payload);
    HttpHeaders headers = requestEntity.getHeaders();
    return ResponseEntity.ok().build();
 }
...
}

Curl Command :  curl -X POST --data-binary @/Users/path/to-jar/test-jar.jar localhost:8008/ctx/jobs/upload
[EDIT] : If I have to achive via --data-binary , how should my code look like?
I am not able to proceed further could anyone please help. I saw lot of solutions on MultiPart but I am not able to fit it in.

A:

You need to configure a servlet for MUltipart:
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
    <property name="maxUploadSize" value="200000"/>
</bean>

Then in your REST service
@RequestMapping(value="/jobs/upload", method=RequestMethod.POST)
@ResponseBody
public ResponseEntity<Void> handleFileUpload(@RequestParam("file") MultipartFile multipartFile,
                                             HttpServletRequest request) {
    ...
}


Q:

Is it possible to inject YAML file to a service in Symfony?

I would like to inject a YAML configuration to a service in Symfony. Currently, I inject path of my bundle and a relative path to the file and parse it manually with Yaml::parse but is there an easier way to do this?
So the goal would be that the constructor of the service would receive an array of the already parsed YAML config.

To put some more detail about it:
Currently, I have a YAML file in a Resources directory in my bundle and to parse it in a service, I use something like this:
$yamlFile = sprintf(
        '%s/%s',
        $container->get('kernel')->getBundle('MyBundle')->getPath(),
        $pathToFile
);

So I have to inject both the container (can I somehow inject just the path to the bundle?) and the path to the file. I wouldn't mind restructuring my system a bit, e.g. put the yaml file in the config directory of the bundle, if that would help, but I'd like to keep it separate from other configuration.

A:

You can load needed configuration in bundle extension like described there: http://symfony.com/doc/current/cookbook/bundles/extension.html and save it to new parameter, or inject to any service you like.


Q:

what is the correct command to reach .php page?

I want line 4 on code to go to page index.php ...
  what is the correct command???
if($count==1){
    echo "Welcome...";
    #LINE 4
}
else {
    echo "Wrong Username or Password";
}

A:

I guess you wanted some kind of redirection like this :
<?php

if($count==1){
    echo "Welcome...";
    $golink = 'index.php';
   ?>

<title>A web page that points a browser to a different page after 2 seconds</title>
<meta http-equiv="refresh" content="2; URL=<?php  echo $golink; ?>">
<meta name="keywords" content="automatic redirection">

If your browser doesn't automatically go there within a few seconds,
you may want to go to
<a href="<?php echo $golink ?>">the destination
manually.

<?php
    } else {
echo "Wrong Username or Password";
?>

hope this helps !


Q:

Perforce new workspace trigger to create a file at client's workspace directory

We are pretty new to Perforce.
What we are trying to achieve is to create a file that will be placed on the client's machine Workspace directory when a new Workspace is created.
I couldn't find the right trigger for the Workspace creation.
Does anyone have any idea or suggestion?
I do see that in most of the trigger I can get the Workspace directory from on the client's machine and the IP of the machine, but I can't find the trigger for the Workspace creation.

A:

You can define a form-commit trigger on the client form that will fire when a client spec is created or modified.
Note that this runs on the server, not the client, so if you want to do something like create a file on the client machine you'll need to use your own mechanism for that.  Perforce itself will only place files on the client machine in response to a command like p4 sync.


Q:

List nested array results from decoded json

I am working with the riot api and I am trying to figure out how to list the results from the summoner api. Here is what I have so far:
//Start getting Summoner Name
$summjsonstring = 'https://na.api.pvp.net/api/lol/na/v1.4/summoner/by-name/' . $name . '?api_key=' . $key;
//echo $summjsonstring;
$summjsonstringcontents = file_get_contents($summjsonstring);
echo $summjsonstringcontents;
echo "
";
$summnameresults = json_decode($summjsonstringcontents, true);
foreach($summnameresults as $data => $value)
   echo '
'. $data.' : '. $value;

This seems to only return
testname : Array

Here is what the JSON looks like:
{"testname ":{"id":2354235,"name":"Test Name","profileIconId":691,"summonerLevel":30,"revisionDate":1410406459000}}

A:

That's exactly what it is supposed to be ;) Your $data var holds a string, and can be printed as-is, but the $value var is an array, and cannot be printed just like that. However you can access it like any array, example given: echo $value['id']; will print out 2354235.
Try this piece of code, it'll help you further:
//Start getting Summoner Name
$summjsonstring = 'https://na.api.pvp.net/api/lol/na/v1.4/summoner/by-name/' . $name . '?api_key=' . $key;
//echo $summjsonstring;
$summjsonstringcontents = file_get_contents($summjsonstring);
echo $summjsonstringcontents;
echo "
";
$summnameresults = json_decode($summjsonstringcontents, true);
foreach($summnameresults as $data => $value)
   echo '
'. $data.' : '. $value['name'];


Q:

Persisting Data in a Twisted App

I'm trying to understand how to persist data in a Twisted application.  Let's say I've decided to write a Twisted server that:

Accepts inbound SMTP requests
Sends the message to a 3rd party system for modification
Relays the modified message to its destination

A typical Twisted tutorial would have you build this app using Deferreds and callbacks, roughly:

A Factory handles inbound requests
Each time a full email is received a call is sent to the remote message processor, returning a deferred
Add an errback that substitutes the original message if anything goes wrong in the modify call.
Add a callback to send the message on to the recipient, which again returns a deferred.
A real server would add/include additional call/errbacks to retry or notify the sender or whatnot.  Again for simplicity, assume we consider this an acceptable amount of effort and just log errors.

Of course, this persists NO data in the event of a crash/restart/something else.  I get that a solution involves a 3rd party persistent datastore (RabbitMQ is often mentioned) and could probably come up with a dozen random ways to achieve the outcome.
However, I imagine there are a few approaches that work best in a Twisted app. What do they look like? How do they store (and restore in the event of a crash) the in-process messages?

A:

If you found this question, you probably already know that Twisted is event-based.  It sounds simple, but the "hardest" part of the answer is to get the persistence platform generating the events we need when we need them. Naturally, you can persist the data in a DB or a message queue, but some platforms don't naturally generate events.  For example:

ZeroMQ has (or at least had) no callback for new data. It's also relatively poor at persistence.

In other cases, events are easy but reliability is a problem:

pgSQL can be configured to generate events using triggers, but they're one-time things so you can't resume incomplete events

The light at the end of the tunnel seems to be something like RabbitMQ.

RabbitMQ can persist the message in a database to survive a crash
We can use acknowledgements on both legs (incoming SMTP to RabbitMQ and RabbitMQ to outgoing SMTP) to ensure the application is reliable.  Importantly, RabbitMQ supports acknowledgements.
Finally, several of the RabbitMQ clients provide full asynchronous support (see for example pika, txampq, and puka)

It's enough for our purposes that the RabbitMQ client provides us an event-based interface.
At a more theoretical level, however, this need not be the case.  In fact, despite the "notification" issue above, ZeroMQ has an event-based client.  Even if our software is elegantly event-based, we will run into systems that aren't.  In these cases, we have no choice but to fall back on polling.  In principle, if not in practice, we just query the message provider for messages.  When we exhaust the current queue (and immediately if there are no messages), we use a callLater command to check again in the future.  It may feel anti-pattern, but it's (to the best of my knowledge anyway) the right way to handle this particular case.


Q:

When does a row standardized adjacency matrix have a real spectrum?

A colleague in spatial statistics was looking at a map with about 600 regions. For the application she's considering, the induced adjacency matrix had some undesirable properties (where two regions are neighbors if they share a border). Instead, she calculated the row-standardized adjacency matrix and somewhat surprisingly, the entire spectrum was real.
I was wondering whether this was to be expected, or if there is something special about the particular example.
Edit: I have edited out the rest of the question, which was trying to understand the probability. The answer explains why this is always the case.

A:

If the adjacency matrix is $A,$ the "row-standardized" matrix is $DA$, where $D$ is a diagonal matrix all of whose diagonal entries are positive, so has a positive diagonal square root $D^{1/2}$. Now,
$$DA = D^{1/2} D^{1/2} A D^{1/2} D^{-1/2},$$ so your matrix is similar to
$$D^{1/2} A D^{1/2},$$ which is a symmetric matrix, and so has real spectrum.


Q:

Estou sofrendo ataques do tipo SQL Injection

Desde que abri um projeto online estou tendo problemas com invasão, onde alguém está fazendo inserções diretas no Banco de Dados. Foi o que me deu iniciativa para por em todas as variáveis recebidas através do método $_GET e $_POST. As funções:
$variavel = trim(strip_tags(mysqli_real_escape_string($conn, $_POST['recebe'])));

Utilizei dois programas para fazer scanner para analisar o site ('Acunetix' e 'Scrawlr'), onde na primeira vez retornou variáveis vulneráveis, mas agora fiz todo o procedimento nas mesma e agora não da mais sinal de problema.
Porém, mesmo assim, o atacante ainda consegue invadir o servidor, mesmo tendo a certeza depois de ter verificado todas as linhas de código do projeto..

A:

Depois de ter sido atacado ele pode ter colhido informações importantes que permitem que ele faça a invasão por outros meios. Quando você tem um servidor invadido não é simples torná-lo seguro novamente. Se não conseguiu fazer eficazmente o que é simples, que é deixá-lo seguro inicialmente, agora vai ser bem mais difícil. Ele pode até estar fazendo isto por ter acesso direto ao servidor agora.
Um especialista em segurança (raro encontrar um realmente capacitado) poderia fazer uma análise nesse servidor para ver se existe algo que possa ser feito. Se preferir por conta própria, o melhor caminho provavelmente é começar um servidor novo com todos dados diferentes, especialmente senhas. Não vá copiar nada que estava no servidor comprometido. Se tiver mesmo que copiar algo, terá que fazer análise minuciosa do conteúdo. E senhas, esqueça, isso não pode ser aproveitado.
A privacidade já era. Isso nunca mais terá solução, uma vez perdida, não volta mais.
Fora isso, o código provavelmente ainda está vulnerável. Esses softwares fazem análises superficiais, não confie neles como uma solução definitiva. Se não conseguir achar todas as vulnerabilidades terá que contratar um especialista. E cuidado, muita gente vende o que não tem.
Lembre-se que agora o atacante provavelmente conhece seu código e sabe explorar qualquer falha, até aquelas que antes passavam desapercebidas.
Veja mais em Como acontece um SQL Injection?.


Q:

Core Data: delay calling endUpdates till viewWillAppear

I have a Core Data app with a tab-bar controller that displays 2 view controllers. If I add something in the first tab's view controller, it should display in the 2nd tab's VC. Both VCs are based off a NSFetchedResultsController which is based off the same entity; the only difference is that one has a predicate and the 2nd VC doesn't.
This works fine for the normal template, and when data is added from the 1st VC, it gets updated instantly in the 2nd tab using controllerWillChangeContent and controllerDidChangeContent. The problem is that if the user adds or deletes any rows in the 1st VC, when the user comes to the 2nd tab they don't see the rows animatedly inserted or deleted... everything's already there.
What I would like to do, in the 2nd tab's VC, is delay calling the [self.tableView endUpdates] (which causes the animated inserting/deleting of rows in the table) till the user actually goes to that tab, in that VC's viewWillAppear. I've tried this, but doesn't seem to work:
- (void)controllerDidChangeContent:(NSFetchedResultsController *)controller
{
        tableviewUpdates = TRUE;
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    if (tableviewUpdates) {
        tableviewUpdates = FALSE;
        [self.tableView endUpdates];
    }
}

This works if adding one row at a time and then switching to the 2nd tab, but not if I add multiple rows in the 1st tab and then switch.
Any help would be appreciated.

A:

You're working against the purpose of the NSFetchedResultsController which is to make updating the tableview automatic and effortless.
I'm pretty sure, however, that if you override all the FRC delegate methods you can block all the automatic updates.
You might want to rethink this design. Are users really going to expect to see changes in one view reenacted in a second? Will they understand they are watching a rewind of the previous changes or will they intuitively think that the app is doing something to their data on its own?
The standard UI grammar teaches users to expect that one change animates once and then subsequently just shows up in a standard display. I would suggest you test this design with naive users carefully before deploying such a non-standard interface.


Q:

Android - Changing Positive Button Text of EditTextPreference's Dialog Programmatically

I am trying to change the positiveButtonText of Dialog in the `EditTextPreference. I have tried the following with no success :
    // The reference to the preference in the view heirarchy
    mUrlPreference = (EditTextPreference) getPreferenceScreen().findPreference(pref);
    // Add a textwatcher
    mUrlPreference.getEditText().addTextChangedListener(prefWatcher);

The prefWatcher is the following :
private TextWatcher prefWatcher = new TextWatcher() {

    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {
    }

    @Override
    public void beforeTextChanged(CharSequence s, int start, int count,
            int after) {

    }

    @Override
    public void afterTextChanged(Editable s) {
        Log.i(TAG_LOG, "Updating the positive button text");
        mUrlPreference.setPositiveButtonText("Download");
    }
};

When I change the text in the EditText, the Log gets printed, but the Positive button text is not changing. Is there anything I'm missing here? My initial thought was that I would have to refresh the dialog's view hierarchy, but I don't see any methods in the API to do it. Any ideas as to what I'm missing here?

A:

As per the documentation of setPositiveButtonText(), the updated text will be shown on subsequent dialogs. So to actually affect the button, do this instead:
@Override
public void afterTextChanged(Editable s) {
    mUrlPreference.setPositiveButtonText("Download");

    Button button = (Button) mUrlPreference.getDialog().findViewById(android.R.id.button1);
    button.setText("Download");
    button.invalidate(); // if necessary
}


Q:

Add a list as a property of an object

Having an array of objects like this:
List<object> myArray = new List<object>();

myArray = [{name = "abc", id = 1},
           {name = "xxx", id = 2},
           {name = "abc", id = 3},
    ];

I want that if there are more objects having the same name to combine them into one object and save the ids into a list. For the above array the desired result should be something like:
myArray = [{name = "abc", (id = 1, id = 3)},
           {name = "xxx", id = 2},
    ];

Maybe it is not the best way to do it like this. I would like to find out any useful suggestions.

A:

Just group your data based on the Name-property:
var result = myList.GroupBy(x => x.Name).Select(x => new
    {
        Name = x.Key,
        Ids = x.Select(y => y.id).ToList()
    });


Q:

Maybe monad in Python with method chaining

I'm trying to implement the Maybe monad in python.
However what I also want is some kind of a chaining ability.
So I have a class:
class Maybe:
    def __init__(self, val):
        self.val = val

    def do(self, func):  # Bind function
        if self.val is None:
            return None
        else:
            return func(self.val)

I have two functions :
def double(number):
    try:
        result = number * 2
        return Maybe(result)
    except:
        return Maybe(None)

def square(number):
    try:
        result = number * number
        return Maybe(result)
    except:
        return Maybe(None)

Here's how I'm using this :
 result = Maybe(5).do(double).do(square)
    print(result.val)

I'm looking at a way to chain multiple functions each performing a specific task. Each function takes the output of the previous function as input. The chain should break if any function in the chain throws an exception.
Is this the right way to model the Maybe monad ?
Is this the right way to handle exceptions too ?
Can this be improved upon ?
Thanks a lot.

A:

The following does what you ask for and lets the functions be a tad bit cleaner. Also updated to capture exceptions properly:
class Maybe:
    def __init__(self, val, err=None):
        self.val = val
        self.err = err

    def __repr__(self):
        if self.err is not None:
           return 'Maybe('+repr(self.val)+', '+repr(self.err)+')'
        else:
           return 'Maybe('+repr(self.val)+')'

    def do(self, func):  # Bind function
        if self.val is not None:
            try:
                val = func(self.val)
            except Exception as e:
                return Maybe(None, e)
            if not isinstance(val, Maybe):
                return Maybe(val)
            else:
                 return val
        else:
            return Maybe(None, self.err)

def double(number):
    result = number * 2
    return result

def square(number):
    result = number * number
    return result

result = Maybe(5).do(double).do(square)
print(result.val)
print(result)
result2 = Maybe('a').do(double).do(square)
print(result2.val)
print(result2)

Prints:
100
Maybe(100)
None
Maybe(None, TypeError("can't multiply sequence by non-int of type 'str'",))

A:

The downside to this is that it intentionally suppresses errors, which is generally considered a bad idea in python.
However, you can catch and store any errors occur in your Maybe instance and report them back.
For example:
class Maybe(object):
    def __init__(self, val, error=None):
        self.val = val
        self.error = error

    def __repr__(self):
        if self.val is not None:
            return repr(self.val)
        else:
            return repr(self.error)

    def do(self, func):
        if self.val is None:
            return self
        try:
            return Maybe(func(self.val))
        except Exception as e:
            return Maybe(None, e)

def squared(x):
    return x * x

def addone(x):
    return x + 1

result1 = Maybe(5).do(squared).do(addone)
result2 = Maybe('a').do(squared).do(addone)
print result1
print result2

This yields:
26
TypeError("can't multiply sequence by non-int of type 'str'",)

This is similar to DanD's answer, but has the advantage of storing the error that occurred instead of completely suppressing it.
No matter how you slice it, this idiom is going to feel somewhat "unpythonic", but this is a slightly more robust way of handling it.

A:

This question has already been answered, but I felt the interface using the Maybe monad could be made more readable. An interface that would allow for a left-right call such as:
 square(double(Maybe(5)))

Also, it would be nice to return a Maybe type to the user to use so they can choose to further chain rather than immediately retrieve the value. This functionality is similar to Swift's Optional type.
class Maybe(object):
  def __init__(self, val=None)
     self.val

  def unwrap(self):
     return self.val

  def calc(self, func):
     try:
       return func(self.val)
     except:
       return None

def double(number):
    return Maybe(maybe.calc(lambda x: x*2))

def square(number):
    return Maybe(maybe.calc(lambda x: x**2))

print square(double(Maybe(5))) # prints Maybe type
print square(double(Maybe(5))).unwrap() # prints '100'
print square(double(None)) # prints 'None'

Exceptions are not stored in my answer because the caller expects the maybe monad to check the exception itself and convert to "nothing" (i.e. None) if a chained operation fails. This allows the user to handle failures easily in conditionals using chains.


Q:

Calling Oracle Stored Procedure From Classic ASP

here is a snippet of my code:
  Set cmd = Server.CreateObject("ADODB.Command")
cmd.ActiveConnection = objCon
       cmd.CommandType = 4
    cmd.CommandText = "SP_USERLOGIN"

       response.Write(p_user_id)
       cmd.Parameters.Append cmd.CreateParameter ("User_locked",adVarChar, adParamInput)
        cmd.parameters(0).value = p_user_id
       cmd.Execute

When i try to Append the parameter, i get the following error:

Arguments are of the wrong type, are out of acceptable range, or are
  in conflict with one another.

my stored procedure only takes 1 parameter:
create or replace PROCEDURE        SP_USERLOGIN ( User_locked VARCHAR2 ) as
BEGIN
update tusers Set user_account_status='status' where user_id = User_locked;
commit;
END;

A:

The problem turned out to be that the constants such as adVarChar, etc. weren't defined. There may have been a second problem with the length of the parameter not defined (that's the 4th argument)
There's a file name ADOVBS.INC that defines these, and if it isn't included then the constant values must be used instead.
To problem went away when this...
cmd.Parameters.Append cmd.CreateParameter ("User_locked",adVarChar, adParamInput)

... was changed to this:
cmd.Parameters.Append cmd.CreateParameter ("User_locked",200, 1, 30)

The 30 above is a length value for the varchar.


Q:

Is there an ASP.NET data type equivalent to the XML data type in SQL Server?

I need to create an app where a user uploads an xml document and that document gets stored in a database column of type "xml". Does anyone know a class equivalent to it?

A:

If you're using a SqlCommand object to interact with your database, see this from MSDN:

For SqlDbType Xml enumeration values, you can use a string, an XML value, an XmlReader derived type instance, or a SqlXml object.

If you're using Linq-to-SQL or Entity Framework, please refer to these questions:

Linq-to-SQL With XML Database Fields -- Why does this work?
Does Entity Framework(EF5) support XML data type yet?


Q:

jQuery call function only when object is created

I am using FitText https://github.com/davatron5000/FitText.js to resize the text of some text I have in specific DIVs. The fact is that these DIVs are created into objects added to the page only when needed. But doing this way FitText won't get the DIV when page loads because in fact the DIV is not already there and so won't resize the text.
Here is how I call FitText:

And here is the function that creates the DIV into an object:
function makeCvdBubble(params)
    {
    var cvdIndexId = params.cvdIndexId;
    var cvdTweetAuthor = params.cvdTweetAuthor;
    var cvdAuthorName = params.cvdAuthorName;
    var cvdTweetDescription = params.cvdTweetDescription;

    objectreference = document.createElement('div');
    objectreference.setAttribute('id', 'indexId-'+cvdIndexId.toString());

    $(objectreference).html('\

\

\
                        @UserName\
                        User Name\
                        Lorem ipsum dolor sit amet, consectetur adipiscing elit. Cras ut posuere justo, eget consequat tortor. In sollicitudin condimentum arcu sed.\

\

\
                    \

\
');

    if (cvdTweetAuthor) $(objectreference).find('.cvd_right_tweet_username').html(cvdTweetAuthor);
    if (cvdAuthorName) $(objectreference).find('.cvd_right_tweet_author').html(cvdTweetAuthor);
    if (cvdTweetDescription) $(objectreference).find('.cvd_right_tweet_text').html(cvdTweetDescription);

    return (objectreference) //objectreference is the reference of the just created tweet
    }

Now how do I do to make FitText resizing the text when the object is created?
Thank you!

A:

After appending the object to the DOM.
Try this:
   var myObj = $("TheParentDOMObject").appendChild(makeCvdBubble(params));
   myObj.fitText(2.8);


Q:

Google Analytics Fetch Custom Report

I'm trying to display data from Google Analytics on a custom dashboard built in React.JS. I've created a custom report in my Google Analytics dashboard and want to make a GET call to retrieve this custom report to get the report's data.
The GA documentation only shows an example for constructing your own custom report with the query, not actually making a call for an already created custom report. Is there a way of making a GET call to a specific custom report to get its data?
This is an example provided by Google Analytics
function queryReports() {
gapi.client.request({
  path: '/v4/reports:batchGet',
  root: 'https://analyticsreporting.googleapis.com/',
  method: 'POST',
  body: {
    reportRequests: [
      {
        viewId: VIEW_ID,
        dateRanges: [
          {
            startDate: '7daysAgo',
            endDate: 'today'
          }
        ],
        metrics: [
          {
            expression: 'ga:sessions'
          }
        ]
      }
    ]
  }
}).then(displayResults, console.error.bind(console));
}

A:

No, there's no other way to access user's custom reports programmatically, you'd probably need to save the reporting request on your side to reuse it. Each request to reporting API batchGet endpoint should contain an explicitly provided reportRequests object.


Q:

Is there a name for refactoring technique that turns hardcoded values into configurable parameters?

What is that technique called when you take values in the code that are hardcoded and make them variable, possibly constructing elaborate OO constructs to make that variable properly configurable?
For example you are printing labels, and you are specifying a value of labels to print per page, like say 4.
Later you realize you have different label sizes, and shapes.  You construct a label factory, which calls proper label files, which also configure themselves and know their own size in relation to the page which is then returned via a function call using polymorphism, and that value is then used instead of the hardcoded 4.
In my own words I can describe it as

Refactoring in effort to increase configurability and flexibility of the software.

but as far as naming specific technique, no..

A:

Often among my friends we would call this softcoding. It's a play on words to imply the opposite of hardcoding and has the nice advantage that it's recognizable for most programmers.
More technically, if I were to describe it in documentation it would simply be "making the software more configurable" or variations of such.
In math related software I sometimes hear it being called parameterizing the code. Or parameterization. It's the name of the process of making equations able to change behavior by changing variables (parametric equations).


Q:

Javascript web content filtering

I am trying to build a filterable listing of Resumes for a Club website that I work on. My goal is to be able to a all the resumes (in PDF) in a folder on the web server. I would Then like to offer the option for a user to generate a listing of Names with associated Link to the PDF document Like
"Name                   Resume Link"
"Name2 ...."
etc
However I would like give drop down menus to select a filter type (by Major, Minor, Graduation Year, etc) And then depending on what filter type is selected to give a listing of all possible choices to filter by. Then I would like to find all related resumes in my folder of resumes and populate a listing (preferrable with some nice formatting so each line has a subtle alternating background color).
I haven't really worked with JavaScript much. So my main questions are:
1) How do I search the PDFs for criteria (do I need to tag them in some way?, as a note, the resumes are not formatted the same, as one would expect)
2) Do I need to populate a Table with information in some way? I found a website showing me how to populate an (un)ordered list with javascript but that was with one dropdown and predefined values.
Sorry for the novel. Any help will be and is appreciated. I have worked with HTML and Java a lot. But really never JavaScript.
Thanks,
Ross
website: www.indiana.edu/~blsc

A:

JavaScript is a Client-Side programming language, but the PDFs sit on the server, so they can't be searched with JavaScript unless your web page provides meta information to the page in some way already.


Q:

Percona install failing

After installing percona server so many times without issue it seems I've hit a unique one.
# yum list installed | grep -i perc
percona-release.noarch               0.1-10                           @percona-release-noarch

As you can see I only have the repo installed. When I go to install PXC5.7, I get this:
# yum install Percona-XtraDB-Cluster-server-57
Loaded plugins: fastestmirror
Loading mirror speeds from cached hostfile
 * base: mirror.atlanticmetro.net
 * epel: fedora-epel.mirrors.tds.net
 * extras: mirror.atlanticmetro.net
 * updates: mirror.atlanticmetro.net
percona-release-sources                                                                                | 2.9 kB  00:00:00
percona-release-sources/7/primary_db                                                                                |  82 kB  00:00:00
Resolving Dependencies
--> Running transaction check
---> Package Percona-XtraDB-Cluster-server-57.x86_64 0:5.7.23-31.31.2.el7 will be installed
--> Processing Dependency: Percona-XtraDB-Cluster-client-57 = 5.7.23-31.31.2.el7 for package: Percona-XtraDB-Cluster-server-57-5.7.23-31.31.2.el7.x86_64
--> Processing Dependency: Percona-XtraDB-Cluster-shared-57 = 5.7.23-31.31.2.el7 for package: Percona-XtraDB-Cluster-server-57-5.7.23-31.31.2.el7.x86_64
--> Processing Dependency: percona-xtrabackup-24 >= 2.4.12 for package: Percona-XtraDB-Cluster-server-57-5.7.23-31.31.2.el7.x86_64
--> Processing Dependency: perl-DBD-MySQL for package: Percona-XtraDB-Cluster-server-57-5.7.23-31.31.2.el7.x86_64
--> Processing Dependency: qpress for package: Percona-XtraDB-Cluster-server-57-5.7.23-31.31.2.el7.x86_64
--> Running transaction check
---> Package Percona-XtraDB-Cluster-client-57.x86_64 0:5.7.23-31.31.2.el7 will be installed
---> Package Percona-XtraDB-Cluster-shared-57.x86_64 0:5.7.23-31.31.2.el7 will be installed
---> Package percona-xtrabackup-24.x86_64 0:2.4.12-1.el7 will be installed
---> Package perl-DBD-MySQL.x86_64 0:4.023-6.el7 will be installed
--> Processing Dependency: libmysqlclient.so.18(libmysqlclient_18)(64bit) for package: perl-DBD-MySQL-4.023-6.el7.x86_64
--> Processing Dependency: libmysqlclient.so.18()(64bit) for package: perl-DBD-MySQL-4.023-6.el7.x86_64
---> Package qpress.x86_64 0:11-1.el7 will be installed
--> Running transaction check
---> Package Percona-Server-shared-56.x86_64 0:5.6.42-rel84.2.el7 will be installed
--> Processing Conflict: Percona-XtraDB-Cluster-shared-57-5.7.23-31.31.2.el7.x86_64 conflicts Percona-Server-shared-56
--> Finished Dependency Resolution
Error: Percona-XtraDB-Cluster-shared-57 conflicts with Percona-Server-shared-56-5.6.42-rel84.2.el7.x86_64
 You could try using --skip-broken to work around the problem
 You could try running: rpm -Va --nofiles --nodigest

Running the suggested commands result in nothing. I've tried installing PXC56 and it works fine. I then yum remove those packages and try this again only to get the same exact thing. I've also tried installing the specific package it mentions in conflict with
yum install https://repo.percona.com/centos/7/RPMS/x86_64/Percona-Server-shared-56-5.6.42-rel84.2.el7.x86_64.rpm

It'll install fine, yum remove works, try to install PXC57, get the same conflict. I've even tried removing this with rpm -e and using yum-utils. I've never had this be a problem before.
UPDATE:
I've narrowed it down to perl-DBD-MySQL being the problem package.
# yum install perl-DBD-MySQL
Loaded plugins: fastestmirror
Loading mirror speeds from cached hostfile
 * base: mirror.atlanticmetro.net
 * epel: fedora-epel.mirrors.tds.net
 * extras: mirror.atlanticmetro.net
 * updates: mirror.atlanticmetro.net
Resolving Dependencies
--> Running transaction check
---> Package perl-DBD-MySQL.x86_64 0:4.023-6.el7 will be installed
--> Processing Dependency: libmysqlclient.so.18(libmysqlclient_18)(64bit) for package: perl-DBD-MySQL-4.023-6.el7.x86_64
--> Processing Dependency: libmysqlclient.so.18()(64bit) for package: perl-DBD-MySQL-4.023-6.el7.x86_64
--> Running transaction check
---> Package Percona-Server-shared-56.x86_64 0:5.6.42-rel84.2.el7 will be installed
--> Processing Conflict: Percona-XtraDB-Cluster-shared-57-5.7.23-31.31.2.el7.x86_64 conflicts Percona-Server-shared-56
--> Finished Dependency Resolution
Error: Percona-XtraDB-Cluster-shared-57 conflicts with Percona-Server-shared-56-5.6.42-rel84.2.el7.x86_64
 You could try using --skip-broken to work around the problem
 You could try running: rpm -Va --nofiles --nodigest

Still don't know how to fix though

A:

unfortunately, you have run into a known issue here, and you are right it is to do with the perl-DBD-MySQL package
You should be able to remedy this by running this
yum install perl-DBD-MySQL

After that, install the Percona repo package, and then after that you can install Percona XtraDB Cluster, Percona Server for MySQL
For more information you can find a number of reports at https://jira.percona.com ... hope this works for you!
Disclosure: I work for Percona


Q:

Angular, trouble getting directive to work

I seem to be having trouble getting my directive to work, I think I may be registering it incorrectly, but I can't seem to figuire out how. Possibly the naming convention?
Here's what I have -
My Directive -
'use strict';

angular.module('demoApp')
.directive('packeryAngular', ['$rootScope', '$timeout',
function($rootScope, $timeout) {
return {
  restrict: 'A',
  scope: true,
  link: function(scope, element, attrs) {

};

}
]);

On my div, I just call it like so
<div packeryAngular>

However, when I call it just like this, nothing seems to be happening. My first assumption was that I needed to register on my app like so
angular.module('demoApp', [ 'packeryAngular ']

However, when I do that I get the error in the console of :
Error: [$injector:modulerr] Failed to instantiate module packeryAngular due to:
Error: [$injector:nomod] Module 'packeryAngular' is not available! You either misspelled the module name or forgot to load it. If registering a module ensure that you specify the dependencies as the second argument.

So, I'm pretty new to this but I'm not entirely sure what I'm doing wrong here, I've tried to copy other working examples and can't seem to get it working. Would appreciate any help, and thank you very much for reading!

A:

You dont need to inject the directive , you just need to use it in html .Second Word of Directive with capital first letter becomes small proceeding with a hyphen,So on all next Capital first letters will become small and will be preceded with hyphen like yourCustomDirective becomes your-custom-directive
<div packery-angular>

get rid of injecting it in module
angular.module('demoApp', []);


Q:

Java replaceAll - Replace "/**" with ""

I am currently doing comment analysis with some Java code and needed to do the following opperation:
comment = comment.replaceAll("/**", "");

But I am meet with this Exception:
    Exception in thread "main" java.util.regex.PatternSyntaxException: Dangling meta character '*' near index 2
/**
  ^
    at java.util.regex.Pattern.error(Unknown Source)
    at java.util.regex.Pattern.sequence(Unknown Source)
    at java.util.regex.Pattern.expr(Unknown Source)
    at java.util.regex.Pattern.compile(Unknown Source)
    at java.util.regex.Pattern.<init>(Unknown Source)
    at java.util.regex.Pattern.compile(Unknown Source)
    at java.lang.String.replaceAll(Unknown Source)
    at commentCoupler.coupler.commentCriteriaForfilled(coupler.java:234)
    at commentCoupler.coupler.analyze(coupler.java:64)
    at commentCoupler.coupler.recursiveCoupler(coupler.java:27)
    at commentCoupler.coupler.recursiveCoupler(coupler.java:22)
    at commentCoupler.coupler.recursiveCoupler(coupler.java:22)
    at commentCoupler.main.main(main.java:16)

Edit: The exception also occurs when I do
comment = comment.replaceAll("**/", "");

and
comment = comment.replaceAll("*/", "");

Do anyone know why this happens and do anyone have a workaround?

A:

replaceAll takes a regular expression, and /** isn't a valid regular expression.
If you just want to remove /**, use replace instead.


Q:

Spring custom validation annotation + Validator implementation

I have a simple POJO which is considered valid if one of the 2 attributes (ssn / clientId) is populated. I have written a custom Spring Validator to do the validation.
The question I have is, is there a way I can annotate my POJO so that my custom Validator is invoked for validation automatically? I'm trying to avoid manually invoking it from multiple places.
public class QueryCriteria {
    @NotNull
    private QueryBy queryBy;
    private String ssn;
    private String clientId;
}

public class QueryCriteriaValidator implements org.springframework.validation.Validator {
    @Override
    public boolean supports(Class<?> clazz) {
        return QueryCriteria.class.equals(clazz);
    }

    @Override
    public void validate(Object target, Errors errors) {
        QueryCriteria criteria = (QueryCriteria) target;

        switch (criteria.getQueryBy()){
            case CLIENT:
                //validation logic
                break;

            case SSN:
                //validation logic
                break;

            default:
                break;
        }
    }
}

A:

With Spring MVC, just add the custom validator to your controller's data binder:
@Autowired
private QueryCriteriaValidator validator;

@InitBinder
public void initializeBinder(WebDataBinder binder) {
    binder.addValidators(validator);
}

Otherwise, you'll want to inject the custom validator and call it yourself.
@Autowired
private QueryCriteriaValidator validator;

public void process(QueryCriteria criteria) {
    check(validator.validate(criteria));
    // Continue processing.
}


Q:

BindingFailure when calling Service Reference method

My .NET 4.0 project contains a few service references.
One of them if giving problems when calling a service method.
It's a SOAP service and when testing with SoapUI i can connect to it and execute methods successfully.
This is the .NET code:
var client = new MyNamespace.MyProject.MyServiceReference.MyServiceClient();
client.Open();

var response = client.SaveApplication(request);

client.Close();

Opening the connection works fine, but when i call the SaveApplication method, i get the following exception:

The assembly with display name 'MyNamespace.MyProject.XmlSerializers' failed to load in the 'LoadFrom' binding context of the AppDomain with ID 2. The cause of the failure was: System.IO.FileNotFoundException: Could not load file or assembly 'MyNamespace.MyProject.XmlSerializers, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null' or one of its dependencies. The system cannot find the file specified.

I really have no clue to what causes this exception...
Please help :)

A:

Found the answer here: How do I fix a Binding Failure in Soap?
I had to turn off MDA BindingFailure exceptions in Visual Studio because i don't want to add the service as Web Reference.


Q:

Getting "The entity type  is not part of the model for the current context."

I am having this issue updating my database 1 column at a time in asp.net using web api. I am trying to query a PUT to just update one value in the row instead of updating that one and setting the rest to null. I made a separate model outside of the controller to take in the update so I could do one at a time. When I hit this line db.Entry(user).State = EntityState.Modified; in the controller that is where it is erroring out. Any advice how I can fix this?
This is my separate ViewModel I am taking in in the put method:
namespace WebAPI.Models.ViewModels
{
    public class UserViewModel
    {
        public string FirstName { get; set; }
        public string LastName { get; set; }
    }
}

This is my controller calling in the method with the ViewModel in my parameter:
public HttpResponseMessage PutUser(int id, UserViewModel user)
        {
            HttpResponseMessage response;

            if (db.User.IsInRole("Admin"))
            {
                try
                {
                        db.Entry(user).State = EntityState.Modified;
                        db.SaveChanges();
                }
                catch (DbUpdateConcurrencyException)
                {
                    if (!UserExists(id))
                    {
                        response = new HttpResponseMessage(HttpStatusCode.NotFound);
                        return response;
                    }
                    else
                    {
                        throw;
                    }
                }

                response = new HttpResponseMessage(HttpStatusCode.NoContent);
                return response;
            }

This is my DBContext file:
public partial class Entities : DbContext
    {
        public Entities()
            : base("name=Entities")
        {
        }

        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            throw new UnintentionalCodeFirstException();
        }
        public virtual DbSet<User> Users { get; set; }
    }
}

A:

This always happened if your repository needs to dynamic accessing different Entity Framework DbContext which means different databases.
Check your data connection string in web.config file for each Entity Frmework DbContext.
For example:
 <add name="CRMEntities" connectionString="metadata=res://*/CRMEntities.csdl|res://*/CRMEntities.ssdl|res://*/CRMEntities.msl;provider=System.Data.SqlClient;provider connection string="data source=Your Data Source;initial catalog=CRM;integrated security=True;MultipleActiveResultSets=True;App=EntityFramework"" providerName="System.Data.EntityClient" />

check metadata in connectionString if it is pointing to a correct DbContext.
In this example, it is pointing to demx file called "CRMEntities".

A:

The error comes from how you initialize the data context db.
The user object has been created in a separate db, so, when you are trying to update user, the current db doesn't know about this user object.
You could solve it by getting a user
try
{
    // or check on FirstName and LastName if you don't have a user id
    var updatedUser = db.Users.SingleOrDefault(x => x.id == id);

    updatedUser.FirstName = user.FirstName;
    updatedUser.LastName = user.LastName;

    db.Entry(updatedUser).State = EntityState.Modified;
    db.SaveChanges();
 }

Alternatively, you could make sure that the data context you are using to create the user object is the same as the one that is trying to update the user.
Does this make sense to you?

A:

Make sure you have the correct metadata part should be same as in edmx.
connectionString="metadata=res://*/Model1.csdl|res://*/Model1.ssdl|res://*/Model1.msl;"


Q:

Count with last 4 digits which represent Date

I have a question
Can we convert date 20-06-2011 (dd-mm-yyyy) into 0611 using sql (SQL server database) ?
And
Can we count ID below
keeping in mind last 4 digits which represent date (last 4 digits represent date in the form MMYY) so numbers with last 4 digits 0611 count should be 3
What would be the SQl Query for the count?
ID

AOB2340511
AOB4560511
AOB3500611
AOB4410611
AOB5120611
AOB1250411

A:

EDIT: Corrected DATE data type option.
If your date fields are DATE data types you can do the following.
SELECT RIGHT('0' + CAST(DATEPART(MM, @TheDate) as VARCHAR), 2)
    + RIGHT(CAST(DATEPART(YY, @TheDate) as VARCHAR), 2)

If your date fields are stored as a string type, such as VARCHAR, NVARCHAR, etc, then try the following
select SUBSTRING(TheDate, 4, 2) + SUBSTRING(TheDate, 9, 2)

For the question about count, you can try this
SELECT RIGHT(ID, 4) AS TheDate, Count(*) AS TheCount
FROM MyTable
GROUP BY RIGHT(ID, 4)

If you need a query for the count that also shows the ID value, give this a try
SELECT ID, RIGHT(ID, 4) as MMYY,
    COUNT(*) OVER (PARTITION BY RIGHT(ID, 4)) AS TheGroupCount
FROM MyTable
ORDER BY ID


Q:

C# Command-Line Parsing of Quoted Paths and Avoiding Escape Characters

How is it possible to parse command-line arguments that are to be interpreted as paths?   args[] contains strings that are automatically joined if they are quoted, e.g.:
example.exe one two "three four"
args[0] = one
args[1] = two
args[2] = three four

However, args[] will not property parse "C:\Example\" as an argument.  Rather, it will supply the argument as "C:\Example""  (with the extra quote included.)  This is due to the backslash in the path being treated as an escape character and thus the end quotation that the user supplied on the command-line becomes part of the argument.
.e.g:
example.exe one "C:\InputFolder" "C:\OutuptFolder\"
args[0] = one
args[1] = C:\InputFolder"
args[2] = C:\OutputFolder"

An easy kludge might be:
_path = args[i].Replace("\"", @"\");

However, I'm sure there is a best-practice for this.  How might one correctly parse a command line that inlcudes paths, preventing the args[] array from improperly being populated with stings that have been parsed for escape characters?
NOTE: I would not like to include an entire command-line parsing library in my project!  I need only to handle quoted paths and wish to do so in a "manual" fashion.  Please do not reccomend NConsoler, Mono, or any other large "kitchen sink" command-line parsing library.
ALSO NOTE:  As far as I can tell, this is not a duplicate question.  While other questions focus on generic command-line parsing, this question is specific to the problem that paths introduce when parts of them are interpreted as escape sequences.

A:

Not an answer, but here's some background and explanation from Jeffrey Tan, Microsoft Online Community Support (12/7/2006):

Note: this is not not a code defeat
  but by design, since backslashe are
  normally used to escape certain
  special character. Also, this
  algorithm is the same as Win32 command
  line arguments parsing function
  CommandLineToArgvW. See the Remarks
  section below:
  http://msdn2.microsoft.com/en-us/library/bb776391.aspx

Also makes reference to the FX method Environment.GetCommandLineArgs for further explanation of the slash handling behavior.
Personally I think this is a drag, and I'm surprised I haven't been bit by it before.  Or maybe I have and don't know it?  Blind replacement of quotes with slashes doesn't strike me as a solution, though.  I'm voting the question up, because it was an eye opener.


Q:

Always Return the Previous Saturday's Date Using NOW Function in MS Excel 2007

I have a workbook that I am using the NOW function to return today's date and then I have another cell to convert to WEEKNUM that I use to MATCH on with a different tab. I need to be able to create a formula to read today's date and always return the previous Saturday. Example: Today is 6-8-2015. I want this formula to return 6-6-2015. Any ideas on how to make this work. I am struggling here.

A:

How about:
=NOW()-(WEEKDAY(NOW(),1))
This will return the time 'now' minus the number of days from Saturday where Sunday = 1, Monday = 2 etc.
Note, this does include the timestamp along with the day (eg. 6/6/2015 14:48).  If you want just the date you could daisy-chain a text function around it.


Q:

What's the most scalable way to track user activity?

I would like to track certain user activity and limit this activity using a time constraint. An example of this could be the votes per day limit enforced by SO. Which of the following methods provides a better solution in terms of scalability and ease of use?

Store activity info in the database
Store activity info in the application scope
Use an entirely different method to track this information

Method 1:

Advantages: data integrity, which is not important in my use case.
Disadvantages: requires database interaction, stores redundant data, requires a scheduled event to reset the values being tracked

Method 2

Advantages: does not require database interaction, appears to be easier
Disadvantages: I'm unsure of the implications on application memory given a large user-base to track, or how easy it is to find and manipulate struct data with hundreds of keys

I'm using ColdFusion with MySQL, if this matters.

A:

Assuming you only care about this data on a per-person basis, and won't be getting aggregates of this, I'd suggest you go with a key/val store that supports TTL.  Redis sounds like it fits your requirements pretty well.

Though it runs in memory, it does snapshot to disk periodically (which mean it's fast, and if something goes down, you'll get most everything back).
Easy interaction, as with your "method 2", but without having to worry about managing a large in-memory structure.

Example Setup
Going with the SO points-per-day scenario, we'll have a time-frame of one day, and our value will be a simple value that increments on some user activity.
Our key would be a combination of the user's id and the current timeframe (day, in this case).  After we have set the key, we set a ttl, which means after today is up, the key will eventually expire and clean itself up.
redis> incr user123-2011-10-09
(integer) 1  # no value found for key, defaulting to 1
             # if this key already had a value it would be incremented.

redis> expire user123-2011-10-09 86400
(integer) 1  # expiration of 1 day was successful

redis> get user123-2011-10-09
"1"          # current value of user key

More info on these commands (incr, get, expire, and ttl would be of most interest to you) can be found on the redis commands reference (complete with an interactive shell to try these things out).
Edit
This method could obviously be applied with any number of k/v stores, I've used Redis here as a concrete example since I believe it meets the requirements closely.


Q:

Insert text into the input/textarea using Jquery

Name
<input name="name" id="name" type="text" class="textInput small" />

The name of the item you are submitting

How can I insert predefined text into a input element. I'd like this function to active when the user doubleclicks the label element.
$('#name.label').dblclick(function(){
    $('#name').val('some text');
});

A:

here check this fiddle
you can use .text("yourPreDefinedText") to replace the text of an element


Q:

Kubernetes keeps creating objects

Being new to the K8s, I am trying to clean up the whole namespace after running some tests on a Windows 10 machine. In short, I thought it would be as easy as running kubectl.exe delete deployment but the deployments are created back after a second and I don't know how to get rid of them. See the followings for the details of what I did:
1.kubectl get deployments,rs (to see what we already have)
NAME                               DESIRED   CURRENT   UP-TO-DATE   AVAILABLE AGE
deployment.extensions/postgresql   1         1         1            1           18m
deployment.extensions/redis        1         1         1            1           16m
NAME                                         DESIRED   CURRENT   READY     AGE
replicaset.extensions/postgresql-c8cb9fff6   1         1         1         18m
replicaset.extensions/redis-5678477b7c       1         1         1         16m

2. kubectl scale deployment redis --replicas=0 (Scale down the deployment)
deployment.extensions "redis" scaled

3. kubectl get deployments,rs (Check again how it looks)
NAME                               DESIRED   CURRENT   UP-TO-DATE   AVAILABLE   AGE
deployment.extensions/postgresql   1         1         1            1           21m
deployment.extensions/redis        0         0         0            0           19m
NAME                                         DESIRED   CURRENT   READY     AGE
replicaset.extensions/postgresql-c8cb9fff6   1         1         1         21m
replicaset.extensions/redis-5678477b7c       0         0         0         19m

4. kubectl delete deployment.extensions/redis (Delete the deployment)
deployment.extensions "redis" deleted

5. kubectl get deployments,rs (Check again and see that it is back!)
NAME                               DESIRED   CURRENT   UP-TO-DATE   AVAILABLE   AGE
deployment.extensions/postgresql   1         1         1            1           23m
deployment.extensions/redis        1         1         1            1           27s
NAME                                         DESIRED   CURRENT   READY     AGE
replicaset.extensions/postgresql-c8cb9fff6   1         1         1         23m
replicaset.extensions/redis-5678477b7c       1         1         1         27s

6. kubectl.exe get events (Looking into the events):
Among other things I can see "Scaled down replica set redis-5678477b7c to 0" and then "Scaled up replica set redis-5678477b7c to 1" which looks like it was never actually deleted but immediately scaled up again after the delete command was executed.
Not sure what I am missing but have already checked a couple of other posts like Kubernetes pod gets recreated when deleted and How to delete all resources from Kubernetes one time? but neither one worked for me.
Forgot to say that the K8s cluster is managed by the Docker Desktop.

A:

Use kubectl delete deployment <the name of deployment >
If you need to clean up whole namespace , use kubectl delete namespace <namespace-name>
Then re-create the same namespace by kubectl create ns command , if you need the same namespace.
You can also clean up the namespace by using --all options with objects:

e.g
   kubecetl delete deployment --all
   kubecetl delete statefulset --all
   kubectl delete pvc --all
   kubectl delete secrets --all
   kubectl delete service --all

and so on.
As pointed out by @David Maze, you're deleting the ReplicaSet instead of the Deployment that's managing it.
From the documentation:

You can define Deployments to create new ReplicaSets

The Deployment will automatically create and manage a ReplicaSet to control the pods. You need to delete the Deployment to erase it's managed resources.


Q:

How to find the next expiration date in Php

In my Php project, i want to find out the expiration date ( eg,today is my joining date then my expiry date is the next month  ie validity is 1 month)
What is the best way to do this.

A:

How about this ?
http://php.net/manual/en/function.strtotime.php
$date = date("Y-m-d");// current date

$date = strtotime(date("Y-m-d", strtotime($date)) . " +1 day");
$date = strtotime(date("Y-m-d", strtotime($date)) . " +1 week");
$date = strtotime(date("Y-m-d", strtotime($date)) . " +2 week");
$date = strtotime(date("Y-m-d", strtotime($date)) . " +1 month");
$date = strtotime(date("Y-m-d", strtotime($date)) . " +30 days")


Q:

Displaying a table next to a fixed width span

I have a html
 that have dynamic width (changes with window size), and a fixed width  (500px).
I want to display both next to each other so that both would fill the whole width of the parent container
I want to do so only using CSS (not js)
I have been playing around with CSS but it seems to be ruining the table's width
HTML

....

   ....

CSS
.container {
   ......
}

.table {
  .....
}

.span {
   width: 500px;
   display: inline-block; //or block if neccessary
}

A:

You may give a try with the table-layout propertie to .container and span.
Browsers should create themselves the element missing to produce the first table-cell.
DEMO
span {
  display:table-cell;
  width:500px;
  border:solid;
}
table {
  border:solid;
  margin:0;
  width:100%;
}
.container {
  display:table;
  width:100%;
  table-layout:fixed;
}

This should work
because of table-layout:fixed
and because browser should create themselves the missing element (like a tbody is always produced in a
 when missing or when in a document is missing either  tags like html or body ).