jQuery resizing images upon initial load of webpage

Ok, Looking at this page in Google Chrome here on a MAC OSX:  http://opportunityfinance.net/Test/2013conf/index.html

Scrolling down to see the following:

If you resize the browser window, it than aligns correctly as in the following picture below:

So, my question is how can I get the appearance in the 2nd pic upon initial loading of the page?  Google Chrome initially sets the height of the <div class="gold"> to 0px with the following code:

jQuery(document).ready(function($){

    var gold = $(".gold");

    $(window).bind("resize", function(){
        gold.css({'height': gold.children(":first").children("img").height()});
    }).trigger("resize");
});

Here is the HTML that I'm using:

<div class="gold" style="width: 100%; position: relative; margin-top: 1em; margin-bottom: 1em;">
    <div style="position: absolute; bottom: 0px; right: 0px; width: 32%;">
        <img src="images/wellsfargo.png" alt="Wells Fargo" style="border: none; max-width: 100%;">
    </div>
    <div style="float: left; width: 32%; bottom: 0px; left: 0px; position: absolute;">
        <img src="images/citi.png" alt="Citi" style="max-width: 100%; border: none;">
    </div>
    <div style="margin: 0 auto; width: 34%; position: absolute; bottom: 0px; left: 0px; right: 0px;">
        <img src="images/gs10ksb.png" alt="Goldman Sachs 10000 Small Businesses" style="border: none; max-width: 100%;">
    </div>
</div>


Places API textSearch vs nearbySearch

Here I have a demo that use nearbySearch to search for objects inside boxes (route boxer utility):

http://www.geocodezip.com/v3_SO_RouteBoxerPlaces.html
CODE:

function findPlaces(boxes,searchIndex) {
   var request = {
       bounds: boxes[searchIndex],
       types: ["gas_station"]
   };
   // alert(request.bounds);
   service.radarSearch(request, function (results, status) {
   if (status != google.maps.places.PlacesServiceStatus.OK) {
     alert("Request["+searchIndex+"] failed: "+status);
     return;
   }
   // alert(results.length);
   document.getElementById('side_bar').innerHTML += "bounds["+searchIndex+"] returns "+results.length+" results<br>"
   for (var i = 0, result; result = results[i]; i++) {
     var marker = createMarker(result);
   }
   searchIndex++;
   if (searchIndex < boxes.length)
     findPlaces(boxes,searchIndex);
   });
}

Now when I try to use textSearch instead nearbySearch I see that code with textSearch and query search for objects outside boxes... http://jsbin.com/ifUZIti/1/edit

function findPlaces(boxes,searchIndex) {
   var request = {
       bounds: boxes[searchIndex],
       query: 'gas station'
   };
   // alert(request.bounds);
   service.textSearch(request, function (results, status) {
   if (status != google.maps.places.PlacesServiceStatus.OK) {
     alert("Request["+searchIndex+"] failed: "+status);
     return;
   }
   // alert(results.length);
   document.getElementById('side_bar').innerHTML += "bounds["+searchIndex+"] returns "+results.length+" results<br>"
   for (var i = 0, result; result = results[i]; i++) {
     var marker = createMarker(result);
   }
   searchIndex++;
   if (searchIndex < boxes.length)
     findPlaces(boxes,searchIndex);
   });
}

What is difference beetween textSearch and nearbySearch and WHY when I try to use textSearch code search and looking for objects outside defined boxes ? What is problem here?
with nearbySearch all works fine but I can't use query with nearbySearch so I must use textSearch but with textSearch script search objects outside boxes ?
How I can solve this?


WPF Dispatcher.Run throws null exception on Win 7 64

I have the following code to create a new UI thread on a .NET 3.5 application.

  private void OnCreateNewWindow(object sender, RoutedEventArgs e)
        {
            var rect = this.RestoreBounds;
            double l = rect.Left;
            double wth = rect.Width;
            double t = rect.Top;
            double ht = rect.Height;
            var progressThread = new Thread(() =>
            {

                progressWindow = new ProgressWindow(Visibility.Collapsed) { Height = 50, Width = 50 };
                progressWindow.WindowStartupLocation = WindowStartupLocation.Manual;
                progressWindow.Left = l + (wth - progressWindow.Width) / 2;
                progressWindow.Top = t - 35 + (ht - progressWindow.Height) / 2;

                progressWindow.Show();
                progressWindow.Activate();
                Dispatcher.Run();
            });

            progressThread.SetApartmentState(ApartmentState.STA);
            progressThread.Start();
        }

Crash is demonstrated here:

This works perfectly on 32 bit versions of Windows.  The first time I run this program upon PC reboot on 64 bit Windows 7, I get a null exception, if run via Visual Studio or an application crash outside of Visual Studio.

Exception details is dry:

System.NullReferenceException was unhandled

Stack trace is given below:

    [Managed to Native Transition]
    WindowsBase.dll!MS.Win32.HwndWrapper.DestroyWindow(object args) + 0xfc bytes
    WindowsBase.dll!MS.Win32.HwndWrapper.Dispose(bool disposing, bool isHwndBeingDestroyed) + 0xce bytes
    WindowsBase.dll!MS.Win32.HwndWrapper.Dispose() + 0x15 bytes
    PresentationCore.dll!System.Windows.Media.MediaContextNotificationWindow.DisposeNotificationWindow() + 0x22 bytes
    PresentationCore.dll!System.Windows.Media.MediaContext.Dispose() + 0xba bytes
    [Native to Managed Transition]
    [Managed to Native Transition]
    WindowsBase.dll!System.Windows.Threading.Dispatcher.ShutdownImplInSecurityContext(object state) + 0x47 bytes
    mscorlib.dll!System.Threading.ExecutionContext.runTryCode(object userData) + 0x178 bytes
    [Native to Managed Transition]
    [Managed to Native Transition]
    mscorlib.dll!System.Threading.ExecutionContext.Run(System.Threading.ExecutionContext executionContext, System.Threading.ContextCallback callback, object state) + 0x62 bytes
    WindowsBase.dll!System.Windows.Threading.Dispatcher.ShutdownImpl() + 0x87 bytes
    WindowsBase.dll!System.Windows.Threading.Dispatcher.PushFrameImpl(System.Windows.Threading.DispatcherFrame frame) + 0x121 bytes
>   EMS.Controls.Dictionary.dll!EMS.Controls.Dictionary.Views.AuthenticateWindow.OnCreateNewWindow.AnonymousMethod() Line 56 + 0x5 bytes    C#
    mscorlib.dll!System.Threading.ExecutionContext.Run(System.Threading.ExecutionContext executionContext, System.Threading.ContextCallback callback, object state) + 0x9b bytes
    mscorlib.dll!System.Threading.ThreadHelper.ThreadStart() + 0x4d bytes

If I continue to run the program again, I get a message from the Program Compatibility Assitant, indicating that some compatibility settings have been applied.  Next time I run the program I no longer get this exception.  Anyone experienced this?


Python Twisted JSON RPC

Can anyone recommend some simple code to set up a simple JSON RPC client and server using twisted?

I found txJSON-RPC, but I was wondering if someone had some experience using some of these anc could recommend something.


2 side by side youtube videos bootstrap 3

I'm having a problem with my responsive embedded youtube where I have 2 videos side by side. It looks fine until the screen size is mobile. Instead of stacking on top of each other they size down to tiny boxes, like in this picture.

Here is my page this is on http://www.pscompetitiveedge.com/references.html

HTML code for that top part of the page:

<h1>References</h1>

<div class="row">
<div class="col-sm-6">
<div class="embed-responsive embed-responsive-16by9">
  <iframe class="embed-responsive-item" src="https://www.youtube.com/embed/aaINOaWt938?rel=0?"></iframe>
<p>Click Above To View Testimonial Video!</p>
</div>
</div>

<div class="col-sm-6">
<div class="embed-responsive embed-responsive-16by9">
  <iframe class="embed-responsive-item" src="https://www.youtube.com/embed/e6UWqeLaMm4?rel=0?"></iframe>
<p>Click Above To View Peter In Seminar Action!</p>

</div>
</div></div>
<div class="clearfix"></div>


Why destructor is called twice?

I have the following code:

#include <cstdio>
#include <iostream>
using namespace std;

class A
{
    int a, b;
public:
    A() : A(5, 7) {}
    A(int i, int j)
    {
        a = i;
        b = j;
    }
    A operator+(int x)
    {
        A temp;
        temp.a = a + x;
        temp.b = b + x;
        return temp;
    }
    ~A() { cout << a << " " << b << endl; }
};

int main()
{
    A a1(10, 20), a2;
    a2 = a1 + 50;
}

Output it shows:

60 70
60 70
10 20

The code works almost as expected. The problem is it prints the values of object a2 twice... that means the destructor is called twice... but why it is called twice?


Razor like intelliSense in custom razor-based template file

I am using Razor Engine, which is a library to render any any file using razor syntax, to render Markdown files with extension csmd. So far everything is working like a charm but I would like to have IntelliSense like on a regular MVC razor file .cshtml.

So my questions are:

Can I configure VS' IntelliSense to this for me?

Can I build a library (nupkg)? In case the above is not possible.

Is it too hard (or even possible) to make an extension vsix to accomplish this?


Why this custom button is redrawing itself without invalidate

So, I'm trying to learn how to create custom views, and I learned that I should redraw the view after the desired changes using invalidate() method.

This little program is one of the exercises in some website. It should be a standard button that contains a colored rectangle inside of it. And when we click the button, the rectangle changes color.

It seems very logic, simple and it works very well. But when I wanted to play with it, and eliminate the invalidate() method in onTouchEvent() method, I was expecting that the colored rectangle won't change color after the click, but it worked as much well as with invalidate() !!

So it seems the invalidate() method is useless here, and it confuses me and I want to understand why ? Thanks

public class ColorButton extends AppCompatButton {

    private TypedArray mCouleurs = null; // contains 4 colors
    private int position = 0;
    private Rect mRect = null;
    private Paint mPainter = new Paint(Paint.ANTI_ALIAS_FLAG);

    public ColorButton(Context context) {
        super(context);
        init();
    }

    public ColorButton(Context context, AttributeSet attrs) {
        super(context, attrs);
        init();
    }

    public ColorButton(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init();
    }

    private void init() {
        Resources res = getResources();
        mCouleurs = res.obtainTypedArray(R.array.colors);
        setText(R.string.change_color);
        mRect = new Rect();
        mPainter.setColor(mCouleurs.getColor(position, -1));
    }

    @Override
    protected void onLayout(boolean changed, int left, int top, int right, int bottom) {

        if(changed) {
            mRect.left = Math.round(0.5f * getWidth() - 50);
            mRect.top = Math.round(0.75f * getHeight() - 50);
            mRect.right = Math.round(0.5f * getWidth() + 50);
            mRect.bottom = Math.round(0.75f * getHeight() + 50);
        }

        super.onLayout(changed, left, top, right, bottom);
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {

        if(event.getAction() == MotionEvent.ACTION_DOWN) {

            position++;
            position %= mCouleurs.length();

            mPainter.setColor(mCouleurs.getColor(position, -1));

            //invalidate();
        }

        return super.onTouchEvent(event);
    }

    @Override
    protected void onDraw(Canvas canvas) {

        canvas.drawRect(mRect, mPainter);

        super.onDraw(canvas);
    }
}


Accessing Windows Server AppFabric caching from classic ASP application?

I am considering using Windows Server Appfabric for it caching functionality.

I have an existing classic ASP application that I want to rewrite in ASP.NET MVC. However, I want to be able to do this "piecemeal" i.e. a few pages at a time.

The problem is session state between the ASP and ASP.Net MVC application. I could use a database but I would like to use Appfabric since it has good scalabilty, admin, etc.

My question is: Does the Appfabric caching service/functionality have an API that I could wrap in .Net and expose to my classic ASP application as a com object?

I could then change all the Session and Application caching in the classic application to use the com object i.e. Appfabric. In this way I can share session state between ASP.Net MVC and classic ASP. I will have to test the performance penalty associated with interop as well.


Spring Data MongoDB @CreatedDate using Java 8 LocaDate Converter

I wan't to use java.util.LocalDate in my domain class that get persisted to MongoDB using Spring Data.

My domain classes has this as parent :-

public abstract class AuditableMongoEntity extends VersionAwareMongoEntity {

    /**
     * serialVersionUID
     */
    private static final long serialVersionUID = -67203638183725497L;

    @CreatedDate
    protected LocalDate dateCreated;

    @LastModifiedDate
    @JsonIgnore
    protected LocalDate lastUpdated;
}

My requirements:-

'dateCreated' field should be saved as no. of days passed since epoch. My business does not need millisecs level of details and does not require hour/minute/sec infromation.

I also want to persist 'year','month','week' along with days for the dateCreated field and enable indexing on them.

For the first requirement I can register a custom Converter<LocalDate, Long>.

How should implement the second requirement?

Spring Boot version 1.3.x


Separating requests to same page in load testing

I've recorded a web performance test in Visual Studio 2013 and then created a load test off of that.

In the load test results, I want to differentiate between two requests to the same page (different form parameters passed in). How would I do that?

I'll try to illustrate the problem in screenshots:

Here's my web performance test:

And here are the load test results:

I want the Respond page to be shown as two separate entries in this results table. Any ideas?


Neo4j-driver (official one) Modeling with nodejs (like Mongoose)?

I am trying to use Passport.js in conjunction with neo4j and nodejs using a tutorial with Mongo DB and it's node helper Mongoose. I have searched for a feature like this in the docs --> Link to Docs, but I can't seem to find anything like that. I really like the ease of use with the official neo4j-driver, and was wondering if I can make models/functions similar to the way mongoose does. Any suggestions on how to achieve this? Or how to use passport without it? I am basically just trying to authenticate users before allowing access to my REST points.

As I mentioned before, I have looked for something like this that is relevant but to the official driver, but no luck. I also couldn't find much on Stackoverflow about Neo4j in conjunction with nodejs and passport.

I am fairly new to Nodejs and web programming all together, so a nudge in the right direction would be great!

Thanks.


MVC Html data attribute rendering difference

I have experienced a very strange issue which I cannot find the cause of.

In my Asp.Net MVC app (.net4.0/MVC4) I am rending html data attributes within some html element to then be used within the JavaScript.

So in the app I have a Model, e.g.

public class MyModel{
    public bool MyFlag { get; set; }
}

I am then passing this model through onto a simple MVC view page and rendering the boolean value into the html data attribute, e.g.

@model MyProject.MyModel

<a href="#" data-is-flagged="@Model.MyFlag">Click Me</a>

Now when running the project locally the html is rendered as:

<a href="#" data-is-flagged="True">Click Me</a>

However when running on the server, the html is rendered as:

<a href="#" data-is-flagged="data-is-flagged">Click Me</a>

At first I thought that maybe the boolean was not being set somehow, so I added this to the element Click Me @Model.MyFlag which renders as Click Me True. Now I suspected that this has maybe something to do with Debug vs Release mode, however after playing about with this it made no difference.

My fix to this was to change the code to output the boolean value as a string value, e.g. data-is-flagged="@Model.MyFlag.ToString()" which then renders the same locally and on the server.

Any ideas what is the cause of this?


how to save gmail emails accordingly in database

i want to have a script that will save gmail emails from an account in mysql db  using php. Mails(both freshly new and reply ones) will be marked to be in the same category if they have the same subject. That is just the same way in gmail or yahoo mail.

So far as I know gmail IMAP does not give the facility to track which are the reply mails.

Which API or whatever should I use??

The script will keep running.

Do I need to use scheduled task for that?


RPI as a central server for co-located android devices

I would like to use a raspberry pi as a central server for an application I'm building. Basically, I want the raspberry Pi to act as a server which can be used by co-located mobile devices to communicate with each other. I'm trying to build a local access network, and there is no need for an Internet connection. I am going to build an application on Android to interface with the server.

I have considered using an ad-hoc network, however, I have found through the following (among others):

Can
Android do peer-to-peer ad-hoc networking?

xda-developers
thread

that Android does not play nicely with ad-hoc networks unless rooted. I am not in a position to root the cellphones, so what else could one do in this instance?

What is a replacement for an ad-hoc network that is compatible with android?


How to use ls command from module?

I want to run the commands like ls,cd,cat from my module.
Actually I want to run this command ls >> file.txt which makes a text file in that directory and save all the fle names in this text file...
How can I do this??


How can I pool gradients in Theano?

I'm using Theano for the first time to build a large statistical model. I'm performing a kind of stochastic gradient descent, but for each sample in the minibatch I need to perform a sampling procedure to compute the gradient. Is there a way in Theano to pool the gradients while I perform the sampling procedure for each datapoint in a minibatch, and only afterward perform the gradient update?


Multiple Queries same route endpoint in node express

I'm trying to make 2 queries for 2 different tables inside the same endpoint. I can do this for simple get queries, but not for more complex update/replace queries. Also I'm not sure how to properly handle errors in this case.

Below is what I tried:

function upvotePost(req,res,next){
        /*query 1*/
        r.table('posts').filter(function(post){
          return post('id').eq(someId);
        }).update(
            {"upvotes": r.row("upvotes").add(1)}).run(req._rdbConn)
        /*query 2*/
        .then(function(){
            r.table('users').filter(r.row('login').eq(someUser))
            .update({upvotelist: r.row('upvotelist').changeAt(someId,1)})
            .run(req._rdbConn).then(function(result){
                res.send(JSON.stringify(result));
            })
        }).error(handleError(res))
         .finally(next);
    }

Right now this returns a connection closed error.


Magento get product

I have a site into my Magento where I want to make a custom query.
My query is ok (I have tried it into phpmyadmin)

I have tried this code into my file .phtml

<?php
// fetch write database connection that is used in Mage_Core module
$db = Mage::getSingleton('core/resource')->getConnection('core_read');
$result = $db->query("select * from catalog_product_flat_1 WHERE short_description LIKE '%".$description_search."%' AND entity_id != ".$product_id." ;");
//After running  check whether data is available or not
if(!$result) {
  echo 'No data found';
}
else
{
//Here we are fetching the data
 echo('<p>here '.$result->fetchAll(PDO::FETCH_ASSOC).'</p>');
 foreach ($result->fetchAll() as $row)
    {
        echo ('<p><br>Name: </p>');
    }
}

Into the foreach doesn't print anything  and the fetchAll is empty.
But if I make:

var_dump($result);

With this var_dump I have the object for example:

object(Varien_Db_Statement_Pdo_Mysql)#631 (9) { ["_fetchMode":protected]=> int(2) ["_stmt":protected]=> object(PDOStatement)#572 (1) { ["queryString"]=> string(130) "select * from catalog_product_flat_1 WHERE short_description LIKE '%Riferimento originale: TN-1700%' AND entity_id != 733536 ;" } ["_adapter":protected]=> object(Varien_Db_Adapter_Pdo_Mysql)#14 (30) { ["_defaultStmtClass":protected]=> string(29) "Varien_Db_Statement_Pdo_Mysql" ["_transactionLevel":protected]=> int(0) ["_connectionFlagsSet":protected]=> bool(true) ["_ddlCache":protected]=> array(1) { [1]=> array(4) { ["eav_attribute"]=> array(17) { ["attribute_id"]=> array(14) { ["SCHEMA_NAME"]=> NULL....

How can I retrieve correctly my product?


Using mb_substr still breaks accent character at the end

Logic: I am getting username from DB and if it is greater than 30 in length then i show 30 characters with "..." appended at the end.
Code is

$username = htmlspecialchars($username);
if(mb_strlen($username, 'utf-8')>30){
    $username_trimmed = mb_substr($username, 0, 30, 'utf-8').'...';
}

and in my navivation I am just printing this username

<class="userName">Hello, <?php echo $username_trimmed; ?>

My encoding in set as utf-8, and mbstring extension is enabled in php.

Output of above code : It still breaks the accent character É because it is multi-byte character and it is getting cut the in the middle.
Actual word is MARCHÉS and output is:

Question what am I missing? mb_substr should not consider it as a single character and should not stop it from breaking in the middle as it does?


I have been running VirtualBox for a few months now and I recently updated El Capitan. After do so, the VirtualBox would no longer start. The error message that displayed was:

"Callee RC: NS_ERROR_FACTORY_NOT_REGISTERED 0x80040154". Does anyone have a solution to this problem?

Thank you.


Joining tables using criteria and sqlProjection

I have the following function that builds a Hibernate Criteria to generate binned data:

private Criteria getCustomBinResultCriteriaSQL(double binSizeX, double binSizeY, String xVar, String yVar, String customBinQuery) {
    return createCriteria(Residue.class)
            .setProjection(Projections.projectionList()
                    .add(Projections.sqlGroupProjection(
                            "floor(" + xVar + " / " + binSizeX + ") * " + binSizeX + " as xBin, " +
                                    "floor(" + yVar + " / " + binSizeY + ") * " + binSizeY + " as yBin, " +
                                    "CAST (" + customBinQuery + " AS DOUBLE PRECISION) as customBinResult",
                            "xBin, yBin",
                            new String[] { "xBin", "yBin", "customBinResult" },
                            new Type[] { Hibernate.DOUBLE, Hibernate.DOUBLE, Hibernate.DOUBLE })))
            .setResultTransformer(Transformers.aliasToBean(CustomBinResult.class));
}

This all works pretty well for data within the same table (residue), but let's say my datastructure is like this:

pdbentry:
id
pdbvar

expmethod:
id
expvar

residue:
id
resvar

pdbentry has a one-to-one relation with expmethod, and a one-to-many relation with residue.

How would I go about joining the residue table with expmethod, based on the criteria-builder above. So in other words: what do I need to add to the criteria to be able to have "expvar" as xVar?

I tried adding something like:

.setFetchMode("pdbentry", FetchMode.JOIN);
.setFetchMode("expmethod", FetchMode.JOIN);

at the end, but then I still couldn't put "expvar" nor "expmethod.expvar" as xVar.

Any ideas?


Passing String to Fragment

I have an EditText view in my MainActivity that the user can input a url. This MainActivity also contains a fragment which will hold a WebView.

I have it set up so that when the fragment is displayed the url will load in the WebView. However I don't know how I can pass the String to the Fragment?

Below is the Main Activity code:

public class MainActivity extends FragmentActivity {

Button goBtn;
EditText urlInput;
String url;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    goBtn = (Button)findViewById(R.id.button1);
    urlInput = (EditText)findViewById(R.id.editText1);

    goBtn.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            url = "http://"+urlInput.getText().toString(); //THIS TO FRAGMENT!

            Toast.makeText(v.getContext(), "Search:" + url, Toast.LENGTH_SHORT).show();
        }
    });

and this is the fragment code:

    WebView webDisplay;
String url;
AsyncHttpClient client;

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {
    View v = inflater.inflate(R.layout.frag1_layout, container, false);
    urlDisplay = (TextView)v.findViewById(R.id.textView1);
    webDisplay = (WebView)v.findViewById(R.id.webView1);
    return v;
}

@Override
public void onActivityCreated(Bundle savedInstanceState) {
    super.onActivityCreated(savedInstanceState);
    //url = "http://"+this.getActivity() ???
    client = new AsyncHttpClient();
    client.get(url, new AsyncHttpResponseHandler(){

        @Override
        public void onSuccess(String response) {
            Toast.makeText(getActivity(), "Success!", Toast.LENGTH_SHORT).show();
            webDisplay.setWebViewClient(new WebViewClient() {
                public boolean shouldOverrideUrlLoading(WebView view, String url) {
                          view.loadUrl(url);
                          return true;
                }});
            webDisplay.loadUrl(url);
        }
    });

The value I am concerned about it the String URL variable in MainActivity.java.

The transaction of the fragments is controlled by a class TabFragment.

public class TabFragment extends Fragment {

private static final int TAB1_STATE = 0x1;
private static final int TAB2_STATE = 0x2;
private int mTabState;

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {
    View v  = inflater.inflate(R.layout.fragment_tab, container, false);
    //References to buttons in layout file
    Button tabBtn1 = (Button)v.findViewById(R.id.tabBtn1);
    Button tabBtn2 = (Button)v.findViewById(R.id.tabBtn2);

    //add listener to buttons
    tabBtn1.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View arg0) {
            //Action to perform when Tab 1 clicked...
            goToTab1View();

        }
    });

    tabBtn2.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            //Action to perform when Tab 2 clicked...
            goToTab2View();
        }
    });

    return v;

}

//Tab action functions.
protected void goToTab1View() {
    if(mTabState != TAB1_STATE){
        mTabState = TAB1_STATE;
        FragmentManager fm = getFragmentManager();
        if(fm!= null){
            //Perform fragment transaction
            FragmentTransaction ft = fm.beginTransaction();
            ft.replace(R.id.fragment_content, new FragTab1());
            ft.commit();
        }
    }
}

protected void goToTab2View() {
    if(mTabState != TAB2_STATE){
        mTabState = TAB2_STATE;
        FragmentManager fm = getFragmentManager();
        if(fm!= null){
            //Perform fragment transaction
            FragmentTransaction ft = fm.beginTransaction();
            ft.replace(R.id.fragment_content, new FragTab2());
            ft.commit();
        }
    }

}


JLabel setText is not working

I am trying to update JLabel by using setText() method. But I can't redraw JLabel. Do I have to use repaint() method to do that? I searched every forum but I can't find a solution.

Here is the part of code. I do not get any errors, but it is not updating JLabel.

public void actionPerformed(ActionEvent e) {
    fc = new JFileChooser();
    if(e.getSource() == addButton) {
         int returnVal = fc.showOpenDialog(Main.this);
         if (returnVal == JFileChooser.APPROVE_OPTION) {
                filesList = fc.getSelectedFiles();
                setFilesList(filesList);

                StringBuilder logString = new StringBuilder();
                logString.append("Files to Convert " + "\n");
                for(int i = 0; i < getFiles().length; i++) {
                    logString.append(filesList[i].getAbsolutePath());
                }
                //JLabel log = new JLabel(); created above.
                log.setText(logString.toString());
            } else {
                //log.append("Open command cancelled by user." + newline);
            }
            //log.setCaretPosition(log.getDocument().getLength());
    }
}


c# printing a "*" char using entered coordinates with 2d array

I have been trying to do a task I recieved a few days earlier. Basically the task is a console application in C# :

Prompt the user for input of 2 coordinates in untill the word "stop" is entered. Once the word "stop" is hit, print a "*"(star char) at each of the input coordinates. The field where the coordinates are printed is 20x20. I have tried doing this, but to no avail. If somebody could help me out and show me how to store the input x,y into a 2d array, that'd be great :)

How the application should work : http://imgur.com/a/SnC1k

The [0,5] [18,18]etc are the entered coordinates which are later on printed down below. The "#" chars dont need to be printed , they are here only to help with the understanding of the task.

How I tried to do it but DIDN'T work :

namespace ConsoleApplication1
{
class Program
{
    static void Main(string[] args)
    {
        bool stopped = false;
        int x=0;
        int y=0;

        while (stopped)
        {
            string[,] coordinates = Console.ReadLine();
            string response = Console.ReadLine();
            response = response.ToLower();

            if (response == "STOP")
                stopped = true;
            else
            {
                string[] xy = coordinates.Split(',');
                x = int.Parse(xy[0]);
                y = int.Parse(xy[1]);

                Console.SetCursorPosition(x, y);
                Console.Write("*");
            }

        }

    }
    }
    }

The code I did just doesn't do it. It shows multiple errors that I do not know how to fix and the only thing I was able to do is get it to print a char immediately when I enter the first coordinates, instead of printing a char at every entered coordinate, AFTER the word STOP is hit.


Implementing a simple proxy server using node.js

I'm trying to create a simple node.js proxy server for experimental purposes and I came up with this simple script:

var url = require("url");
var http = require("http");
var https = require("https");

http.createServer(function (request, response) {
    var path = url.parse(request.url).path;

    if (!path.indexOf("/resource/")) {
        var protocol;
        path = path.slice(10);
        var location = url.parse(path);

        switch (location.protocol) {
        case "http:":
            protocol = http;
            break;
        case "https:":
            protocol = https;
            break;
        default:
            response.writeHead(400);
            response.end();
            return;
        }

        var options = {
            host: location.host,
            hostname: location.hostname,
            port: +location.port,
            method: request.method,
            path: location.path,
            headers: request.headers,
            auth: location.auth
        };

        var clientRequest = protocol.request(options, function (clientResponse) {
            response.writeHead(clientResponse.statusCode, clientResponse.headers);
            clientResponse.on("data", response.write);
            clientResponse.on("end", function () {
                response.addTrailers(clientResponse.trailers);
                response.end();
            });
        });

        request.on("data", clientRequest.write);
        request.on("end", clientRequest.end);
    } else {
        response.writeHead(404);
        response.end();
    }
}).listen(8484);

I don't know where I'm going wrong but it gives me the following error when I try to load any page:

http.js:645
    this._implicitHeader();
         ^
TypeError: Object #<IncomingMessage> has no method '_implicitHeader'
    at IncomingMessage.<anonymous> (http.js:645:10)
    at IncomingMessage.emit (events.js:64:17)
    at HTTPParser.onMessageComplete (http.js:137:23)
    at Socket.ondata (http.js:1410:22)
    at TCP.onread (net.js:374:27)

I wonder what could the problem be. Debugging in node.js is so much more difficult than in Rhino. Any help will be greatly appreciated.


In R, how do I make an iterative calculation without using a loop?

Here is a simple example of one type of iterative calc:

vals <- data.frame( "x"=c( 14, 15, 12, 10, 17 ), "ema"=0 )
vals$ema[1] <- vals$x[1]
K <- 0.90
for( jj in 2:nrow( vals ) )
  vals$ema[jj] <- K * vals$ema[jj-1] + (1-K) * vals$x[jj]

vals
   x     ema
1 14 14.0000
2 15 14.1000
3 12 13.8900
4 10 13.5010
5 17 13.8509

The more involved examples use if...else to determine the next value:

for( jj in 2:nrow( vals ) )
    if( K * vals$ema[jj-1] + (1-K) * vals$x[jj] < 5.0 )
        vals$ema[jj] <- 5.0
    else if( K * vals$ema[jj-1] + (1-K) * vals$x[jj] > 15.0 )
        vals$ema[jj] <- 15.0
    else
        vals$ema[jj] <- K * vals$ema[jj-1] + (1-K) * vals$x[jj]

I am not sure if it would be more involved or not, but the decision can be based on the previous value as well:

K1 <- 0.999
K2 <- 0.95
K3 <- 0.90
for( jj in 2:now( vals ) )
    if( vals$ema[jj-1] < 0.0 )
        vals$ema[jj] <- K1 * vals$ema[jj-1] + (1-K1) * vals$x[jj]
    else if( vals$ema[jj-1] > 100.0 )
        vals$ema[jj] <- K3 * vals$ema[jj-1] + (1-K3) * vals$x[jj]
    else
        vals$ema[jj] <- K2 * vals$ema[jj-1] + (1-K2) * vals$x[jj]


the type system does not tell the whole story due to "exception"

My question should be somewhat vague and very superficial. Sorry. But I am wondering whether it is a bad style to use "exception".  For example, in Ocaml, the exception does not appear as the .mli file. So it appears to me that "exception" is something that cannot be tracked by a type system.

So my question in general is, is using exception a bad style because it hides information against the type system?

Concretely, I am trying to implement a type checker for an imperative language, say, Pascal. The essential judgment should have been of this signature,

well-typed_1: environment -> statement -> unit

But this seems to be insufficient because the environment would be modified due to a local variable declaration,  thus a more reasonable interface for typechecker would be

well-typed_2: environment -> statement -> environment

An alternative would be use the former one, well-typed_1, dealing with local variables declaration through an exception Var_declaration (e : environment) which returns the updated environment to the type checker for its other recursion.

So, my question for this concrete example is , should I use the well-typed_1 + exception for variable declaration, or well-typed_2?

The disadvantage of well-typed_2 seems to be that, for most statement there are no side effect with regard to environment of types, thus that signature of well-typed_2 seems to be a bit redundant. The disadvantage of well_typed_2 + exception seems to reveal a general issue: the the signature of well-typed_1 in does not tell the whole story. (it does not tell the potential exception)


Why does git rm -rf not get rid of a folder with a submodule in it?

When I do git status this is what I see:

$ git status
# On branch main
# Your branch is ahead of 'github/main' by 1 commit.
#   (use "git push" to publish your local commits)
#
# Changes not staged for commit:
#   (use "git add <file>..." to update what will be committed)
#   (use "git checkout -- <file>..." to discard changes in working directory)
#   (commit or discard the untracked or modified content in submodules)
#
#   modified:   octopress (modified content, untracked content)
#
no changes added to commit (use "git add" and/or "git commit -a")

When I do git rm -rf octopress, this is what I see:

$ git rm -rf octopress
error: submodule 'octopress' (or one of its nested submodules) uses a .git directory
(use 'rm -rf' if you really want to remove it including all of its history)

Thoughts?


Visual Studio variadic macro expansion yields unexpected results

currently I'm trying to compile some code with Visual Studio 2015 Service Pack 2 that makes use of the following macros not written by me:

#define REM(...) __VA_ARGS__
#define EAT(...)

// Retrieve the type
#define TYPEOF(x) DETAIL_TYPEOF(DETAIL_TYPEOF_PROBE x,)
#define DETAIL_TYPEOF(...) DETAIL_TYPEOF_HEAD(__VA_ARGS__)
#define DETAIL_TYPEOF_HEAD( x , ... ) REM x
#define DETAIL_TYPEOF_PROBE(...) (__VA_ARGS__),
// Strip off the type
#define STRIP(x) EAT x
// Show the type without parenthesis
#define PAIR(x) REM x

Supposedly the TYPEOF macro would isolate the type of an expression.
I have tried to invoke the TYPEOF macro with the following call:

TYPEOF( (int) m ) c;

In theory, the result should be

int c;

but instead the preprocessor outputs

int, m, c;

Replacing

#define DETAIL_TYPEOF_HEAD(x, ...) REM x

with

#define DETAIL_TYPEOF_HEAD( x , ... ) X = x and VA_ARGS = __VA_ARGS__

Yields this output:

X = (int), m, and VA_ARGS =  c;

It seems that receiving the input (int), m, the DETAIL_TYPEOF_HEAD macro is unable to pick the first entry x from the variadic parameter list and instead puts the whole list into x.

Do you know this phenomenon?

Regards


ValueError: The file could not be found with <pipeline.storage.PipelineCachedStorage object>

I'm trying to compile SASS and compress CSS files with django pipeline on Django 1.6.3, but I get the following error after visiting my site:

ValueError: The file 'css/test2.css' could not be found with <pipeline.storage.PipelineCachedStorage object at 0x0585DF50>.

I configured pipeline following the guide on readthedocs.org: I added pipeline to INSTALLED_APPS then I defined STATIC_URL and STATIC_ROOT:

STATIC_URL = '/test/forum/skins/default/media/'
STATIC_ROOT = '/test/forum/skins/default/media/'

Folders tree:

test

forum

skins

default

media (static files)

css

js

images

site1

site2

site3

views

utils

settings.py

I added SASSCompiler to PIPELINE_COMPILERS and then I added the path to the file to be compressed:

# pipeline settings
STATICFILES_STORAGE = 'pipeline.storage.PipelineCachedStorage'
PIPELINE_COMPILERS = (
  'pipeline.compilers.sass.SASSCompiler',
)
PIPELINE_CSS = {
    'main': {
        'source_filenames': (
          'css/test.scss',
        ),
        'output_filename': 'css/test2.css',
    },
}

Finally I linked the css to my XHTML index:

{% load compressed %}
<html xmlns="http://www.w3.org/1999/xhtml">
    <head>
        {% compressed_css 'main' %}
    </head>

I do not understand what I did wrong.
Thanks for any help!

UPDATE:

When I run collectstatic this copy the files from django and not from my project

F:\DEV\DJANGO\apps\test>python manage.py collectstatic

You have requested to collect static files at the destination
location as specified in your settings:

    F:\test\forum\skins\default\media

This will overwrite existing files!
Are you sure you want to do this?

Type 'yes' to continue, or 'no' to cancel: yes
Copying 'F:\DEV\DJANGO\apps\django\django\contrib\admin\static\admin\css\base.
css'
Copying 'F:\DEV\DJANGO\apps\django\django\contrib\admin\static\admin\css\chang
elists.css'
Copying 'F:\DEV\DJANGO\apps\django\django\contrib\admin\static\admin\css\dashb
oard.css'
Copying 'F:\DEV\DJANGO\apps\django\django\contrib\admin\static\admin\css\forms
.css'
Copying 'F:\DEV\DJANGO\apps\django\django\contrib\admin\static\admin\css\ie.cs
s'
[etc .... ]

But the path F:\test\forum\skins\default\media is wrong, my project is located
in F:\DEV\DJANGO\apps\test\forum\skins\default\media.

Then I tried to find the static file:

F:\DEV\DJANGO\apps\test> python manage.py findstatic css/main.css

No matching file found for 'css/main.css'.

But the file exists.


Error from the SQL syntax

SELECT * FROM `111_dossier` AS d
LEFT JOIN `008_vehicule` AS v
LEFT JOIN `053_dates` AS da
LEFT JOIN `descriptif` AS des

WHERE (`d.site_gestion` = 57 OR `d.site_creation` = 57)
AND `d.etat_dossier` IN("V","W")
AND year(`da.date_entree`) >= 2014
AND `v.marque` = "Tesla"
AND `des.C4` LIKE %LONGERON%

#1064 - You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to
use near 'WHERE (d.site_gestion = 57 OR d.site_creation = 57)
     AND d.etat_dossier IN(' at line 6

*

I'm trying to run this request since 2 hours , can someone help me?
Sorry, I think that it's only a small error in the syntax but I'm a beginner.

Suggest the changes to be done.


Pagination DataTable Full Number - No Ellipsis still not showing after initialize plugin

I'm new in using DataTables I have some problem when trying to use pagination. I have initialized plugin pagination but the pagination still doesn't showing on my table, but function like sort table and search I used work. Here is what i'm doing.

groupCategory = $('#groupCategory').DataTable({
  searching: true,
  responsive: true,
  "bSortClasses": true,
  "scrollY": "470px",
  "sDom": "ti",
  "bPaginate": true,
  "pagingType": "full_numbers_no_ellipses"
});

And use it on my table by doing

<table id="groupCategory" class="table table-bordered table-hover">
  <thead>
    <tr>
      <td>Group</td>
      <td>Description</td>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>Group 1</td>
      <td>Placeholder 1</td>
    </tr>
    <tr>
      <td>Group 2</td>
      <td>Placeholder 2</td>
    </tr>
    <tr>
      <td>Group 3</td>
      <td>Placeholder 3</td>
    </tr>
    <tr>
      <td>Group 4</td>
      <td>Placeholder 4</td>
    </tr>
    <tr>
      <td>Group 5</td>
      <td>Placeholder 5</td>
    </tr>
    <tr>
      <td>Group 6</td>
      <td>Placeholder 6</td>
    </tr>
    <tr>
      <td>Group 7</td>
      <td>Placeholder 7</td>
    </tr>
    <tr>
      <td>Group 8</td>
      <td>Placeholder 8</td>
    </tr>
    <tr>
      <td>Group 9</td>
      <td>Placeholder 9</td>
    </tr>
    <tr>
      <td>Group 1</td>
      <td>Placeholder 1</td>
    </tr>
    <tr>
      <td>Group 10</td>
      <td>Placeholder 10</td>
    </tr>
    <tr>
      <td>Group 11</td>
      <td>Placeholder 11</td>
    </tr>
    <tr>
      <td>Group 12</td>
      <td>Placeholder 12</td>
    </tr>
    <tr>
      <td>Group 13</td>
      <td>Placeholder 13</td>
    </tr>
    <tr>
      <td>Group 14</td>
      <td>Placeholder 14</td>
    </tr>
    <tr>
      <td>Group 15</td>
      <td>Placeholder 15</td>
    </tr>
    <tr>
      <td>Group 16</td>
      <td>Placeholder 16</td>
    </tr>
    <tr>
      <td>Group 17</td>
      <td>Placeholder 17</td>
    </tr>
    <tr>
      <td>Group 18</td>
      <td>Placeholder 18</td>
    </tr>
    <tr>
      <td>Group 19</td>
      <td>Placeholder 19</td>
    </tr>
    <tr>
      <td>Group 20</td>
      <td>Placeholder 20</td>
    </tr>
  </tbody>
</table>

On table information it show that table has data Showing 1 to 10 of 20 entries, but the pagination still not showing. I was declared on my html page

<script src="https://code.jquery.com/jquery-1.12.4.min.js"></script>
<script src="https://cdn.datatables.net/1.10.13/js/jquery.dataTables.min.js"></script>
<script src="https://cdn.datatables.net/plug-ins/1.10.13/pagination/full_numbers_no_ellipses.js"></script>
<script src="https://cdn.datatables.net/1.10.13/js/dataTables.bootstrap.min.js"></script>

Please help me to solve this


How to organize xml data using equivalent to #region / #endregion (outlining) from C# .NET

I'd like to organize my XML data to be collapsable and expandable  using a preprocessor command like the #region/#endregion command in C#/.NET. I'm editing this file Visual Studio 2008.

Does any such ability exist? I've googled to no avail. The closest I can come to so far is to expand and collapse the tags themselves, so I can collapse between

<Data>
(this is collapsed)
</Data>


DataTables pagination doesn't seem to work with server side data

I do not understand why this pagination doesn't working: http://goo.gl/8jexmc

 jQuery(function($) {
    $('#lista-contatti').DataTable({

        "processing": true,
        "serverSide": true,
         //"info": true,
        "ajax": {
            url: "http://www.derattizzazione.info/test/ajax_datatable.cfm",
            cache:  false,
        },

        "columns": [
                { "data": "id" },
                { "data": "ute_nominativo" },
                { "data": "ute_email" },
                { "data": "ute_data" },
                { "data": "ute_ip" },
                { "data": "ute_lista"},
                { "data": "azioni" }
        ]

        });
});

It works only the first page, but do not load the next pages. I'm still missing something…


MySQL inner join?

I have 3 tables (2 columns)such as

table s
NUM  GRADE
1    A
2    B
3    C
5    D

table p
NUM  GRADE
1    B
2    C
2    D
3    A

table g
NUM  GRADE
1    A
3    C
3    B
4    D

I want to inner join them each other such (on s.NUM=p.NUM=g.NUM) as

NUM  GRADE
1    A
1    B
1    A
2    B
2    C
2    D
3    A
3    C
3    B

What should I do?

Thank you


Import binascii Python 2.5.2

I'm trying an example almost straight out of the version 2.5.2 documentation for the Python Library Reference for the function "a2b_base64()" which is part of the "binascii" module.  I am trying to convert a hex number to its binary value.  Eventually I need to convert a whole hex file to binary.

The function is techniclly for a string, but the error I'm getting says "NameError : name 'a2b_base64' is not defined".  Any idea why this fails? I wish I could use a more mordern version of Python and avoid the a2b_base64() function, but can't. Thanks.

import binascii
num = a2b_base64("04")
print num


CoreData migration in iOS 7

Finally got this migration working, it was a big pain.

source code

Everything works fine in iOS6 but in iOS7 app crash


Nesting components in Angular4 (RC5)

Getting into Angular and watching an outdated tutorial which is in fact for Angular2 (y, I know).

Angular4:

@NgModule({
  imports: [ BrowserModule ],
  declarations: [ AppComponent , MyChildComponent ],
  bootstrap: [ AppComponent ]
})

Seems that this is how you nest components now but isn't there a way to do it how it was done (or similarly) in Angular 2? As in you could import it in the now-deprecated 'directives' property DIRECTLY IN YOUR ROOT COMPONENT (found this really convenient for fast development).

Angular2:

@Component({
   selector: 'app-root',
   directives: [MyChildComponent]
   template: '<div><ChildComponent></ChildComponent></div>'
})
export class AppComponent {}

Edit: Here's the MyChildComponent declaration (still part of Angular2):

@Component({
   selector: 'ChildComponent',
   template: '<h2>Child component</h2>'
})
export class MyChildComponent {}

Note: Omitted the import declarations


Replace text in XamlPackage

I have some text in a RichTextBox. This text includes tags eg: [@TagName!]. I want to replace these tags with some data from a database without losing formatting (fonts, colors, image, etc). I've created a method:

 void ReplaceTagsWithData(FlowDocument doc)
    {
        FileStream fs = new FileStream("tmp.xml", FileMode.Create);
        TextRange trTextRange =
            new TextRange(doc.ContentStart, doc.ContentEnd);

        trTextRange.Save(fs, DataFormats.Xaml);
        fs.Dispose();
        fs.Close();

        StreamReader sr = new StreamReader("tmp.xml");

        string rtbContent = sr.ReadToEnd();

        MatchCollection mColl =
            Regex.Matches(rtbContent,
                          string.Format(@"\{0}+[a-zA-Z]+{1}",
                          prefix,
                          postfix));

        foreach (Match m in mColl)
        {
            string colname =
                m.Value.Substring(prefix.Length,
                   (int)(m.Value.Length - (prefix.Length + postfix.Length)));

            rtbContent = rtbContent.Replace(m.Value.ToString(),
                                            dt.Rows[0][colname].ToString());
        }

        rtbEdit.Document =
            new FlowDocument(
                (Section)XamlReader.Load(
                    XmlReader.Create(new StringReader(rtbContent))));
        sr.Dispose();
        sr.Close();
    }

It's quite good but it removes images from content. I know that I should use XamlPackage instead of Xaml but then I can't get it as a plain text. Is there any other solution for this?

Thanks for answers. ;)

[EDIT: 13-02-2012 02:14(am)]

My working solution:

    void ReplaceTagsWithData(RichTextBox rtb)
{
    FlowDocument doc = rtb.Document;

    FileStream fs = new FileStream("tmp", FileMode.Create);
    TextRange trTextRange = new TextRange(doc.ContentStart, doc.ContentEnd);
    trTextRange.Save(fs, DataFormats.Rtf);
    fs.Dispose();
    fs.Close();

    StreamReader sr = new StreamReader("tmp");
    string rtbContent = sr.ReadToEnd();
    sr.Dispose();
    sr.Close();

    MatchCollection mColl =
        Regex.Matches(rtbContent,
                      string.Format(@"\{0}+[a-zA-Z]+{1}",
                      prefix,
                      postfix));

    foreach (Match m in mColl)
    {
        string colname =
            m.Value.Substring(prefix.Length,
                (int)(m.Value.Length - (prefix.Length + postfix.Length)));

        rtbContent = rtbContent.Replace(m.Value.ToString(),
                                        dt.Rows[0][colname].ToString());
    }
    MemoryStream stream =
        new MemoryStream(ASCIIEncoding.Default.GetBytes(rtbContent));
    rtb.SelectAll();
    rtb.Selection.Load(stream, DataFormats.Rtf);

}

Maybe it's not the best but it's working correctly.

It was solved. But I can't post solution because it is on company server which I can't access anymore.


understanding c++11 rvalues, move semantics and performance

Possible Duplicate:

  What happens if I return literal instead of declared std::string?

Consider the following code

1| string getName () {
2|     return "meme";
3| }
4|
5| string name = getName();

The function getName() returns a temporary object. In c++03, I understand the copy constructor of "string" gets called and the temporary object is destroyed. Actually it seems compiler (atleast in gcc 4.7) optimizes line 5 by not creating the object "name" but replacing it with the temporary object itself and not destroying the temporary object (I tried with a MyVector class; not std::string).

As defined in C++11 standards,

 1. Is getName() returning an rvalue?

 2. In line 5 above, which constructor of string gets called (move or copy) ?  Should I necessarily call std::move() for the move constructor to get called?

 3. With move semantics, is it less efficient then the "copy elision" optimization provided by the compiler?


Numeric expression in if condition of awk

Pretty new to AWK programming. I have a file1 with entries as:

15>000000513609200>000000513609200>B>I>0011>>238/PLMN/000100>File Ef141109.txt>0100-75607-16156-14 09-11-2014
15>000000513609200>000000513609200>B>I>0011>Danske Politi>238/PLMN/000200>>0100-75607-16156-14 09-11-2014
15>000050354428060>000050354428060>B>I>0011>Danske Politi>238/PLMN/000200>>4100-75607-01302-14 31-10-2014

I want to write a awk script, where if 2nd field subtracted from 3rd field is a 0, then it prints field 2. Else if the (difference > 0), then it prints all intermediate digits incremented by 1 starting from 2nd field ending at 3rd field. There will be no scenario where 3rd field is less than 2nd. So ignoring that condition.

I was doing something as:

 awk 'NR > 2 { print p } { p = $0 }' file1 | awk -F">" '{if ($($3 - $2) == 0) print $2; else l = $($3 - $2); for(i=0;i<l;i++) print $2++; }'

(( Someone told me awk is close to C in terms of syntax ))

But from the output it looks to me that the String to numeric or numeric to string conversions are not taking place at right place at right time. Shouldn't it be taken care by AWK automatically ?

The OUTPUT that I get:

513609200
513609201
513609200

Which is not quiet as expected. One evident issue is its ignoring the preceding 0s.

Kindly help me modify the AWK script to get the desired result.

NOTE:

awk 'NR > 2 { print p } { p = $0 }' file1 is just to remove the 1st and last entry in my original file1. So the part that needs to be fixed is:

awk -F">" '{if ($($3 - $2) == 0) print $2; else l = $($3 - $2); for(i=0;i<l;i++) print $2++; }'


ASP.NET MVC - problem logically undertanding how to structure a report section

The problem: Using ASp.NET MVC for reporting.

Given:
 1. A report that is tabular in output, so it can easiyl be represented by a class (static field list).
 2. A filter mask containing halfa dozen or more possible conditions to apply to the data.

How is the approach for the MVC file layout?

I would say one controller for the complete report.

But how does the model look? One property with all the filter conditiond (or: a property per filter condition), one property with an enumeration of results?

I would also love to do a redirect when the search parameters change and would love to see the parameters as parameters (i.e. the URL ending in /Reports/Assets?From=...&To=...) so users can bookmark a specific favourite report or email the URL around.

How to do? I have a lon gbackground in ASP.NET, but MVC somehow eludes me ;)


OpenERP7.0 form_view_ref can't ref inherit view

                  <field name="move_lines_qc" context="{'zuhu_id': supplier_id, 'form_view_ref':'view_stock_qc_form', 'tree_view_ref':'view_jp_stock_qc_tree'}" options='{"reload_on_button": true}'/>

The above records in my definition of view,"form_view_ref" need ref another view view_stock_qc_form,

inheritance

<record id="view_stock_qc_form" model="ir.ui.view">
        <field name="name">jp.stock.qc.form</field>
        <field name="model">jp.stock.qc</field>
        <field name="inherit_id" ref="view_jp_move_picking_form"/>
        <field name="arch" type="xml">
            <xpath expr="//field[@name='product_number']" position="replace">
                    <field name="product_number" string="From"/>
            </xpath>
        </field>
    </record>

no inheritance

 <record id="view_stock_qc_form" model="ir.ui.view">
        <field name="name">jp.stock.qc.form</field>
        <field name="model">jp.stock.qc</field>
        <field name="arch" type="xml">
        <form string="Stock Moves" version="7.0">
            <header>
            </header>
            <group>
                <group>
                    <field name="product_id" on_change="onchange_product_id(product_id)" domain="[('zuhu_id','=',zuhu_id)]" context="{'default_zuhu_id':zuhu_id}" />
                    <field name="product_number" />
                    <field name="specifications" />
                    <field name="unqualified" />
                    <field name="instruction"  />
                 </group>
                <group>
                        <field name="product_qty"/>
                        <field name="product_qty_fact" />
                        <field name="product_uom"/>
                        <field name="create_date" invisible="1"/>
                        <field name="date"/>
                 </group>
              </group>
            </form>
        </field>
    </record>

If there is no inheritance, can be related.while, inheritance ,it ref the default.I want inherit , What should I do?


Why shouldn't I use GC.Collect()

I am developing an application where I work with CertAdm.dll to make connections to a Certificate Authority. Sometimes I get the error "An attempt was made to open a Certification Authority database session, but there are already too many active sessions. The server may need to be configured to allow additional sessions."

If I configure my connection like the code below, I dont get the error and all works fine.

CERTADMINLib.ICertView2 cv2 = new CERTADMINLib.CCertViewClass();

try
{
    cv2.OpenConnection(srtCAConfig);
}
catch
{
    GC.Collect();
    GC.WaitForPendingFinalizers();
    cv2.OpenConnection(srtCAConfig);
}

Now what I am wondering about is that I have read a lot where people say you shouldn't use GC.Collect(). Why shouldn't I? It solves my problem?

All help is very appreciated.


PHP for loop return single value

I want to make the for loop to return a single value (TRUE/FALSE). But the code returns multiple value. Like TRUETRUETRUE. I understand the code but didn't have any idea to do it.

public function user_activation_check(){
    for($i=1;$i<5;$i++){
        $query = $this->db->query("SELECT group_info.member".$i." FROM `group_info` INNER JOIN `user_student` ON group_info.member$i=user_student.email WHERE user_student.email=group_info.member$i");
        if($query->num_rows()==1){
            //return TRUE;
            echo"true";
        }else {
            //return FALSE;
            echo"false";
        }
    }
}

Help please.

UPDATE:

public function member_activation(){
    if($this->model_users->user_activation_check()){
        $this->load->view('v_confirm_group');
    }else echo "Some members didn't activate their account.";
}


get word before a :- sign in a string with regex

I need to get the amount before a :- sign.
So the string would be: bla bla 120:-

And then store only 120 in a variable


How to open pdf saved locally on windows server through hyperlink present inside a jsp page?

I have tried each and every post on stackoverflow but i am unable to open a pdf file neither in IE nor in mozilla firefox.I am new to JSP and servlets so i will be needing help with the code too.Please tell me a way to how to open pdf file saved locally on windows server through hyperlink present inside a jsp page?Write now the website is hosted using tomcat on windows server and client is that same server.


Dashboard shows close to 100% CPU load, but actual usage is different

During peak hours of our service, I notice the CPU load goes up to 100%. However, when I SSH into the machine and use top or htop, I don't ever see the CPU usage go above 25%. This instance is a dedicated load balancer running HAProxy.

Here is a screenshot of the Dashboard: https://gyazo.com/010715208f81ec97c1bc9b78123fe4d4
Here is a screenshot of top in the instance: https://gyazo.com/afa7098331f7a3f66c018041b9be686d

During these peak times, I noticed there are some latency and this is not caused by database or my other server instances as I checked their loads and were far below threshold. I was wondering if Compute Engine is throttling by mistaking it is at 100% CPU usage or something?

Has anyone had a similar experience?


Error when Compiling Oracle Package Body

The Package Specification succesfully Compiles with the message "SPBomPackage Compiled" But i have two errors when compiling the package body they are as follows, "Error(17,6): PL/SQL: Statement ignored" and "Error(17,17): PLS-00302: component 'ITEM_ID' must be declared" ,
 the package specification, package body, and the three tables im using that this package will use are pasted and formatted nicely for you to view at this link:


How to get all the variables that were added to any constraint in a Solver?

I am using Z3py and trying to get the set of all the variables in any constraint in a Solver. I can call Solver.assertions() to get an ASTVector, then loop over this vector and get objects of type BoolRef, for example, but then I'm stuck. How can I recursively iterate over an assertion, a BoolRef instance for example, to get the individual variables?


iis 7 Error 500 Internal Server Error

I have a php website whose server is iis 7. When the website is on a Server 2008 32-bit platform, the error is thrown. If I move the page to another directory, the error follows. Yet on my developmentserver, a 64 bit machine, with the very same code, there is no error. I am perplexed and looking for solutions.


create graph from data frame in r

I Have data frame representing a grn network.gene in column 1 is connected to gene in column 2 if column3 (link) is set to 1. I run this code but the resulting graph is not correct.

  x <- data.frame("g1" = c(1,1,1,2,2,3), "g2" = c(2,3,4,3,4,4), "link" = c(1,0,1,1,0,0))
  g = graph_from_data_frame(x,x$link==1)
 tkplot(g)

how can get correct corresponding graph from this data frame?


a simple excel command or a program that updates value?

I would like to beg for my stupidity, bear with me, I am very new!

I will try to make it as clear as possible.

I want to create a excel program or possibly just do it with excel, that I can use for my business.

Let's say I have a customer that prepaid $100. He purchased $3 the first day and $8 the next day.

I would have a value of $100. I subtract $3 then the $100 would become $97. Then subtract $8 so it would become $89. So basically, it keeps updates the amount.

I couldn't figure how to do this in excel. Is there a way to allow this in excel? or do I have to make a excel workbook or excel template using commands?

I would love to get help from professionals!


calling C/C++ functions of a library compiled with g++, wthin a program compiled with gcc

I have a set of software library modules which are developed in c++.  So, I use g++ to compile my software.

This has to be used by various existing applications which are written in C and compiled with gcc.

When the other teams used g++ to compile their code, they started getting lot of compiler errors due to strict type checking rules of c++. This broke their applications. Worse still, they are using some 3rd party library code, which cannot be compiled using g++.

if they use gcc, then there are linker errors (unresolved symbols).

so, my question is...
"Is there a way for my library code to be linked with their applications, without changing the respective compilers?  That is, i still have to use g++, since i use classes/objects heavily in my code, and they have no choice of using g++, which will break their application?".

Thank you for kind help.

regards,
Ravindra


Accordion in jQuery

Hi I am working on an accordion I would like to know if there is a cleaner way of toggling the "plus" and "minus" signs. Bellow is the code and a link to a prototype.

jQuery

$(".discount-wrapper h2").on("click", function() {
    $(this).children('.plus-sign').toggle();
    $(this).parent().children(".discount-content-wrapper").toggle('slow');
    $(this).children('.minus-sign').toggle();
});

HTML

<div class="discount-wrapper">
    <h2>Accordion 3<i class="plus-sign">+</i><i class="minus-sign" style="display:none;">-</i></h2>
    <div class="discount-content-wrapper">
        <p>My content is here</p>
    </div>
</div>
<div class="discount-wrapper">
    <h2>Accordion 3<i class="plus-sign">+</i><i class="minus-sign" style="display:none;">-</i></h2>
    <div class="discount-content-wrapper">
        <p>My content is here</p>
    </div>
</div>

http://jsfiddle.net/


Jquery Slide function

I've been a little confused as how I'm supposed to connect my jquery to my page, and I'm still still relatively new to learning javascript/jquery.  When I put the script in the head nothing happens when I click on the  I have set up in my file below.  But on my jfiddle it works fine.

I have a portion of my site where I want to have a mock iphone where people who visit the page can click on it.

I used this jfiddle I found on stack overflow:
how to make div slide from right to left

There's a link that goes to jqueryui and shows the script for the slide effect there.  Am I supposed to use this in the head?

    <link rel="stylesheet" href="//code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css">
  <script src="//code.jquery.com/jquery-1.10.2.js"></script>
  <script src="//code.jquery.com/ui/1.11.4/jquery-ui.js"></script>

This is my jfiddle that I tweaked slightly as to what I'm looking to achieve:
http://jsfiddle.net/tokyothekid/weujtht5/

Here's my current code in the head:

<link rel="stylesheet"href="//code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css">
    <script src="//code.jquery.com/jquery-1.10.2.js"></script>
  <script src="//code.jquery.com/ui/1.11.4/jquery-ui.js"></script>

<script>
$( document ).click(function() {
  $('#iphone-button1').click(function(){

                if ($('#iphone-panel2').is(':hidden')) {

                   $('#iphone-panel2').show('slide',{direction:'right'},1000);
                } else {

                   $('#iphone-panel2').hide('slide',{direction:'right'},1000);
                }
});
    </script>

Here is my html:

    <div id="iphone-panel1">
       logo
       <a id="iphone-button1">start</a>
    </div>
<div id="iphone-panel2">User Area</div>

My CSS:

#iphone-panel1{
    width:200px;
    height:200px;
   position:absolute;
}

a {
    color: #000;
    cursor:pointer;
    display:block;
}
#iphone-panel2 {
    width: 200px;
    height: 200px;
    display: none;
    background: red;
    position:relative;
}

Appreciate all the help


Speed up clojure startup time with nailgun

Every now and then I think it would be nice to use clojure for shell scripts, but a startup time of about 900ms is way too slow. I'd then googlestartpage for "nailgun clojure", but the only results that show up are for special cases like vimclojure. That's when I, pretending not to have time, turn to more awkward languages that start up faster.

So, how can nailgun be used to speed up the startup time of clojure?


Camera Calibration using OpenCV2 and Python 2.7 / cv2.findChessboardCorners

I am trying to do a multipectral camera calibration using Open Cv2 and Python 2.7, and the code is working well with the pictures that I have from the 3 monochrome sensors (RED, NIR, and GRE) and the RGB ones. The only pictures that are not working in the code are the pictures from the REG sensor (Red Green).

The code reads the pictures, converts them to gray and then finds the corners, the SubPixels, and finally producres a camera calibration matrix.

I have built the code with multiple print in each part so that I will know which is the exact part that is not working, so I know that it is not working for the REG case in the cv2.findChessboardCorners line.

    ret, Bords_Trouves = cv2.findChessboardCorners(Images_en_gris, Lignes_et_Collones, None)

So my question is :

What's not working in the code ? Or is it a problem with the REG sensor pictures, I would have to try another approach to convert them to gray ? Or what ?

Here is all the code:

    # -*- coding: utf-8 -*-
import numpy as np
import cv2
import glob
import math
import pickle
import matplotlib.pyplot as plt

critere = (cv2.TERM_CRITERIA_MAX_ITER | cv2.TERM_CRITERIA_COUNT, 10, 0.01)

Lignes = 13
Collones = 13
Collones_et_Lignes = (Collones, Lignes)
Lignes_et_Collones = (Lignes, Collones)

Points_Reels = np.zeros((Lignes*Collones, 3), np.float32)
Points_Reels[:, :2] = np.mgrid[0:Lignes, 0:Collones].T.reshape(-1, 2)

# Préparer deux tableaux pour sauvegarder les points objet et points images de totues les images trouvées.
Tableau_points_reels = []
Tableau_points_imaginaires = []

# Les photos du damier qu'on a pris pour le test
Source = "C:/Users/Mourad/Desktop/Calib1804/REG/"
Mes_Images = glob.glob(Source + '*.TIF')

print "les images ont bien étaient récupérées." if Mes_Images else "PROBLEME: images non récupérés !! "

for leo, fname in enumerate(Mes_Images):
    print("Image : " + fname)
    #if leo > 10:
     # break
    image_originale = cv2.imread(fname)

    Images_en_gris = cv2.cvtColor(image_originale, cv2.COLOR_BGR2GRAY)

    print "les images ont bien étaient transformés en gris." if Images_en_gris.all() else "PROBLEME: images non transformés en gris!! "

    ret, Bords_Trouves = cv2.findChessboardCorners(Images_en_gris, Lignes_et_Collones, None)

    print str(len(Bords_Trouves)) + " Bords trouvés" if ret else "PROBLEME: Bords Non trouvés !!"

    Tableau_points_reels.append(Points_Reels)

    PL = (11, 11)

    Plus_de_precision = cv2.cornerSubPix(Images_en_gris, Bords_Trouves[1], PL, (-1, -1), critere)

    print "Sub pixels trouvées" if Plus_de_precision else "PROBLEME: Pas de sub pixels trouvées"

    Tableau_points_imaginaires.append(Bords_Trouves)

   # far = cv2.drawChessboardCorners(image_originale, Lignes_et_Collones, Bords_Trouves, ret)

    #cv2.imshow("Bords trouvées déssinés sur l'image originale", image_originale)
    #cv2.waitKey(500)
    #()
print "Nombre de points réels trouvés: " + str(len(Tableau_points_reels))
print "Nombres de points imaginaires trouvés: " + str(len(Tableau_points_imaginaires))

h, w = Images_en_gris.shape[:2]

derik, matrice, distortion, vecteur_de_rotation, vecteur_de_translation = cv2.calibrateCamera(Tableau_points_reels, Tableau_points_imaginaires, (w, h), None, None, flags=cv2.CALIB_RATIONAL_MODEL)

print "La matrice de calibration est: "
print matrice
print "La distortion est egale a: "
print distortion
print "Le vecteur de rotation est egal a: "
print vecteur_de_rotation
print "Le vecteur de translation est egal a: "
print vecteur_de_translation

print "\n La matrice de calibration trouvée et données récupérés" if derik else "PROBLEME: Pas de calibration"

newcameramtx, roi = cv2.getOptimalNewCameraMatrix(matrice, distortion, (w, h), 1, (w, h))

# undistortion
Image_calibree = cv2.undistort(image_originale, matrice, distortion, None, newcameramtx)

fgh = cv2.imread("C:/Users/Mourad/Desktop/Calib1804/RGB/IMG_700101_000800_0000_RGB.JPG")

h, w = fgh.shape[:2]

x, y, w, h = roi
Image_calibree = Image_calibree[y:y+h, x:x+w]
cv2.imwrite('Desktop/imagecalibre.png', Image_calibree)

plt.subplot(121), plt.imshow(fgh), plt.title('image originale')
plt.subplot(122), plt.imshow(Image_calibree), plt.title('image calibree')
plt.show()

Erreur_totale = 0
for i in xrange(len(Tableau_points_reels)):
    imgpoints2, _ = cv2.projectPoints(Tableau_points_reels[i], vecteur_de_rotation[i], vecteur_de_translation[i], matrice, distortion)
    Erreur = cv2.norm(Tableau_points_imaginaires[i], imgpoints2, cv2.NORM_L2)/len(imgpoints2)
    Erreur_totale += Erreur
    print "Erreur totale: ", Erreur_totale/len(Tableau_points_reels)

cv2.destroyAllWindows()


XmlSerializer - There was an error reflecting type - error deserializing

I have an error when trying to deserialize an xml
I have a set of classes that are prepared to receive this xml:

<raiz>
    <propiedad1>
        <p1></p1>
        <p2>
            <p21></p21>
            <p22></p22>
        </p2>
    </propiedad1>
</raiz>

But, if my code receives an XML that don't include  tag then I get the following exception: "There was an error reflecting type p2"

this is my code to deserialize:

var obj = new System.Xml.Serialization.XmlSerializer(typeof(Y));

thanks in advance for your help


Finding the most repeated value for each associated attribute

I'm practicing some SQL and I thought about the following problem:

For each pub find the time when more people go.
I have the following tables:

            GOESTO
id_person   id_pub  time
1           1       Daytime
2           2       Night time
3           3       All Day
4           1       Daytime
5           2       Night time
6           1       All Day
7           3       Daytime
8           3       Night time
9           3       Night time
10          1       Night time

         PUB
id_pub  pub_name    cost
1       pub1        123
2       pub2        324
3       pub3        345

What I want to get is something like the following:

pub_name   time

I think I should use MAX and COUNT functions, but I'm not quite sure how should I do it. It should work in an Oracle database.

Thank you!


How can I make rails.js re-apply the same magic to new forms that are loaded dynamically?

For my understanding rails.js do some magic to my forms (that have ":remote => true") to transform them into ajax form once the page is loaded.

When one of these forms is submitted, it is replaced with a new form.

How can I make rails.js re-apply the same magic to this new form?


Run MochaJS before start node server automated

I am new to Mocha.js, but I did some test cases and I would like to run these tests before my server starts automatically.

For example:
npm start
Then all Mocha's tests run and if it passes the server starts, if not the server stops.

I am using Jenkins for automated deploy


.htaccess url rewrite multiple directories to GET parameters

Ok so I have a site that I want to write rewrite rules for. I don't have much experience with rewrites.

My .htaccess is in /foo/, not the root. Here's what I want

Case 1: example.com/foo/bar/ --> example.com/foo/includes/page.php?school=bar&id=

Case 2: example.com/foo/bar/1 --> example.com/foo/includes/page.php?school=bar&id=1

Here is what I have

RewriteEngine on

RewriteRule    ^(bar|baz)/(.*)$    ./includes/pages.php?school=$1&id=$2    [NC,L]

There are only two possible values for school bar and baz. The id can have any number of values.
The above code works in Case 2 but doesn't work in case 1. It seems to externally redirect in case 1 to different urls depending on if there is a trailing slash or not. No idea why. Any help would be greatly appreciated.


Does StringBuilder cache the resulting string upon ToString() call?

Does StringBuilder cache the string upon ToString call? For example, will this create two different in-memory strings, or use just one:

var sb = new StringBuilder();
sb.Append("foo");
sb.Append("bar");

var str1 = sb.ToString();
var str2 = sb.ToString();

Will it cache its own result for consecutive read operations?


Polynomial Support Vector Regression in Accord.Net

I'm trying to learn the framework (Accord) but the documentation often comes with broken pieces of code.

I wanted something similar to this.

I've tried different things and nothing seemed to work. Does anyone have a working non-lineal support vector regression example ?

I also tried the official example which doesn't seem to work either.


Linear Coding question

I am using Java to try to implement a simple linear code, expressed as F=SA where S is a matrix of random coefficients and A is a vector of original fragments (thus f = S multiply A).

I got the original fragments by splitting the file in n pieces and converting each piece to a stream of bytes.

Example:

file = 64 kb

each original fragment = 1024 bytes

How can I multiply the matrix with the vector(k rows, 1 column) of original fragments?

I cannot express the 1024 bytes of the *i*th row for a single integer in the *i*th row.

If I make use of a matrix instead of vector will it remain correct? Thanks in advance.


Comparing number data in each key of a map to another numerial value

I have created a map which takes in as it's key various event numbers. Each event number then stores a series of numerical values (particle masses - DiLept_M) as its data. I want to iterate through each event number and find the particle mass for each key which is closest to another value. e.g

12345: 3098.5  3099.1 8097.3  4356.5

The event number here is 12345 and the following numbers are all the particle masses. I want to store the event number and particle mass which is closet to 3096 in a new map.

 std::map< Int_t, std::vector<Double_t> > MapOfEventsAndMasses;

 for(int i=0; i<tree->GetEntries();i++){ //loop through the data
 tree->GetEntry(i);

 if(MapOfEventsAndMasses.find(event_number) == MapOfEventsAndMasses.end()){

 std::vector<Double_t> tempVec;
 tempVec.push_back(DiLept_M);
 }
 else{
   MapOfEventsAndMasses[event_number].push_back(DiLept_M);
 }

 std::map< Int_t, std::vector<Double_t> >::iterator Iter1;

   Iter1 = MapOfEventsAndMasses.begin();

   std::map< Int_t, std::vector<Double_t> >::iterator Iter1_End;

   Iter1_End = MapOfEventsAndMasses.end();

   for ( ; Iter1 != Iter1_End; Iter1++){

Int_t event_number = Iter1->first;

std::vector<Double_t> DiLept_M = Iter1->second;

          for( int j=0; j < DiLept_M.size(); i++){

    // NOT SURE WHAT TO DO HERE

      }

   }  //Closing for loop


How can you determine installed versions of the glibc (etc.) libraries?

I'm working with an embedded Linux deployment and am using a cross compiler tool chain that doesn't compile I2C library function calls.

How do I determine the precise versions of the libraries on the system so that I may rebuild the tool chain?

I don't intend to replace the libraries deployed, as I do know they work (including I2C), so I believe I need the following:

Binutils version

GCC version

GLIBC

Kernel (for the headers)

I think I can assume from the following that the binutils library is version 2.2.5. The kernel is modded for which I've the source.

root@dev-box />ls /lib/ -al
drwxrwxrwx  3 root root     1024 Apr 27 09:44 .
drwxrwxrwx 14 root root     1024 Jan  1  1970 ..
-rwxrwxrwx  1 root root   105379 Jan  1  1970 ld-2.2.5.so
lrwxrwxrwx  1 root root       16 Jan  1  1970 ld-linux.so.2 -> /lib/ld-2.2.5.so
lrwxrwxrwx  1 root root       16 Jan  1  1970 ld.so.1 -> /lib/ld-2.2.5.so
-rwxrwxrwx  1 root root  1288601 Jan  1  1970 libc.so.6
-rwxrwxrwx  1 root root    25441 Jan  1  1970 libcrypt.so.1
-rwxrwxrwx  1 root root    14303 Jan  1  1970 libdl.so.2
-rwxrwxrwx  1 root root    36800 Jan  1  1970 libgcc_s.so.1
-rwxrwxrwx  1 root root   530401 Jan  1  1970 libm.so.6
-rwxrwxrwx  1 root root    86626 Jan  1  1970 libnsl.so.1
-rwxrwxrwx  1 root root    17533 Jan  1  1970 libnss_dns.so.2
-rwxrwxrwx  1 root root    46324 Jan  1  1970 libnss_files.so.2
-rwxrwxrwx  1 root root    98633 Jan  1  1970 libpthread.so.0
-rwxrwxrwx  1 root root    69966 Jan  1  1970 libresolv.so.2
-rwxrwxrwx  1 root root    12897 Jan  1  1970 libutil.so.1


How to obtain Android Studio 1.5 menu image code as PNG file

I see that menu image file is presented like this

<vector xmlns:android="http://schemas.android.com/apk/res/android"
    android:width="24dp"
    android:height="24dp"
    android:viewportHeight="24.0"
    android:viewportWidth="24.0">
    <path
        android:fillColor="#FF000000"
        android:pathData="M12,12m-3.2,0a3.2,3.2 0,1 1,6.4 0a3.2,3.2 0,1 1,-6.4 0" />
    <path
        android:fillColor="#FF000000"
        android:pathData="M9,2L7.17,4H4c-1.1,0 -2,0.9 -2,2v12c0,1.1 0.9,2 2,2h16c1.1,0 2,-0.9 2,-2V6c0,-1.1 -0.9,-2 -2,-2h-3.17L15,2H9zm3,15c-2.76,0 -5,-2.24 -5,-5s2.24,-5 5,-5 5,2.24 5,5 -2.24,5 -5,5z" />
</vector>

I would like to know if there is any tool to convert PNG file to

 android:pathData="M9,2L7.17,4H4c-1.1,0 -2,0.9 -2,2v12c0,1.1 0.9,2 2,2h16c1.1,0 2,-0.9 2,-2V6c0,-1.1 -0.9,-2 -2,-2h-3.17L15,2H9zm3,15c-2.76,0 -5,-2.24 -5,-5s2.24,-5 5,-5 5,2.24 5,5 -2.24,5 -5,5z" />

and vise versa.


How to check that a stored procedure with no return value has been executed?

I am executing a stored procedure that has no return value. How can I check that it has actually been executed? Here is the code:

this.dbProviderFactory = DalFactory.GetFactory(this.adapterConfiguration);
DbConnection dbConnection = dbProviderFactory.CreateConnection();

dbConnection.ConnectionString = this.adapterConfiguration.DatabaseInformation.ExternalDatabaseInformation.connectionString;
dbConnection.Open();

DbCommand cmd = dbConnection.CreateCommand();
cmd.CommandText = "h_AS_SP_ResetUnfinishedJobs";
cmd.CommandType = CommandType.StoredProcedure;
cmd.ExecuteNonQuery();

And here is the stored procedure:

ALTER PROCEDURE [dbo].[h_AS_SP_ResetUnfinishedJobs]
AS
BEGIN
 -- Delete all unfinished jobs where the force flag has not been set...
 DELETE FROM h_AS_mds_MetaDataStatus
 WHERE mds_status NOT IN (11,12) AND mds_force = 0
END


Can we use the prolog in XML in capital?

I know that XML is case sensitive and when I wrote the prolog in capital it showed error but I want to make sure that I hit the right spot or I am wrong.


looping through json and echo with php

I am working with a airline flight search and get the following output when I echo print_r($result).

Unirest\HttpResponse Object
(
    [code:Unirest\HttpResponse:private] => 200
    [raw_body:Unirest\HttpResponse:private] => {"airTicketListResponse":{"customerSessionId":"1373316267","currency":"USD","routings":[{"key":"Xt4yT/xiADHlJY1rDoGfIW1oqil8CPCWFIlJLLRPgb8^vJwIcDs7qiScjgw^YEk5DvQVRZ1Ge1ut9cq4GDemu8aQQ1r4LqOr3z3asbm/3xcR9G4YzjkKns6CoqNxFEuO8rCrifO9GnKWSQaFrOWE/JRLlKewmNAAGIz41wbgI4BYVBeiWfbPO7v/EDI3y92fKShWVCKarRbMUq4KZ6p^i7ROySEM1S9Kw6pu7OXYgn9NUpIWd1ReV0X^32AROvy^uVtRFCYMKkplFEEEafGVivdQXwii7Be/6Hpmj71D4QKNZsoPzHqH9cehD6123fqhmCkVzSTED3z^B79K/o^3ezOaf73EgLLg8eVB7pqTTk0=","mainAirlineCode":"DL","mainAirlineName":"Delta Airlines","totalPrice":"231.80","adultBasePrice":"196.04","adultTax":"35.76","childBasePrice":"0","childTax":"0","lastTicketDate":"08/05/2013","domesticTicket":true,"duration":"180","tripTime":"180","layover":false,"operatedBy":false,"overnightFlight":false,"overnightStay":false,"publishFare":true,"trips":[{"segments":[{"airlineCode":"DL","airlineName":"Delta Airlines","departureAirportCode":"PHX","departureAirportName":"Sky Harbor International Airport","departureTime":"11/22/2013 06:00","arrivalAirportCode":"LAX","arrivalAirportName":"Los Angeles International Airport","arrivalTime":"11/22/2013 06:35","stop":0,"duration":95,"codeShare":"","cabin":"E","aircraftCode":"Canadair RJ","flightNumber":"4578","departureCity":"Phoenix","departureStateCode":"AZ","departureCountryCode":"US","departureCountryName":"United States","arrivalCity":"Los Angeles","arrivalStateCode":"CA","arrivalCountryCode":"US","arrivalCountryName":"United States","BookingClass":"T","MarriageGroup":"O"}],"duration":"95","tripTime":"95"},{"segments":[{"airlineCode":"DL","airlineName":"Delta Airlines","departureAirportCode":"LAX","departureAirportName":"Los Angeles International Airport","departureTime":"12/22/2013 08:30","arrivalAirportCode":"PHX","arrivalAirportName":"Sky Harbor International Airport","arrivalTime":"12/22/2013 10:55","stop":0,"duration":85,"codeShare":"","cabin":"E","aircraftCode":"Canadair RJ","flightNumber":"4793","departureCity":"Los Angeles","departureStateCode":"CA","departureCountryCode":"US","departureCountryName":"United States","arrivalCity":"Phoenix","arrivalStateCode":"AZ","arrivalCountryCode":"US","arrivalCountryName":"United States","BookingClass":"X","MarriageGroup":"O"}],"duration":"85","tripTime":"85"}]},

How do I loop through this and echo out mainAirlineName and adultBasePrice for each item returned? I dont know if this is an array inside of an array or maybe I messed something up by print_r($result).


How to parse json array without json object title in android?

   [
    {
        "name":           "The Universe & The Earth"
      , "imagename":      "cat1.jpg"
      , "active":         "Y"
      , "createdon":      "1901-01-01"
      , "lastmodifiedon": "1901-01-01 00:00:00"
      , "description":    "Knowledge of Earth location in the universe has been shaped by 400 years of telescopic observations, and has expanded radically in the last century.\n"
      , "id":             "1"
    }
  , {
        "name":           "Life on Earth"
      , "imagename":      "cat2.jpg"
      , "active":         "Y"
      , "createdon":      "1901-01-01"
      , "lastmodifiedon": "1901-01-01 00:00:00"
      , "description":    "Over the last 3.7 billion years or so, living organisms on the Earth have diversified and adapted to almost every environment imaginable."
      , "id":             "2"
    }
]

This is my json values. Now i want to parse and displayed in custom list view how can i
     do this? I followed http://www.androidhive.info/2012/01/android-json-parsing-tutorial/ this is link but can't be achieve. How can i do this? Can anybody tell me? Thanks in advance.


Properly loop through JSON with jQuery

I have the following JSON:

{
  "status" : "success",
  "0": {
    "link"  : "test1",
    "img"   : "test2",
    "title" : "test3"
  },
  "1":{
    "link"  : "test4",
    "img"   : "test5",
    "title" : "test6"
  }
}

Obviously 0 and 1 are objects themselves and I would like a proper way to loop through all data in this object, the 'status', '0', and '1'. What I have right now (and works) is below, I know there has to be a better method to see if the element is just one deep, such as 'status' or if it's an object, such as '0' and '1':

// Prints the link from '0' and '1'
$.each(test, function(){
if(this == '[object Object]')
 alert(this.link);
});


How can I create a process that starts other processes in c#?

I would like to create a process that has no purpose but running other processes. (Which will act as his child processes)
The child processes are "real" application like Notepad++, Adobe Photoshop, etc.

What I am trying to achieve is the ability to hold both processes, child and parent, as objects (System.Diagnostics) while having the flexibility of executing and killing whichever child process I choose to.


Interpolation of a vector in MATLAB depending on changes in another vector

I have two column vectors 'A' and 'B'. The first column in both vectors is time.

A =
35.2985    5.7057
35.2991    5.7098
35.2997    5.6880
35.3004    5.6739
35.3010    5.7140
35.3016    6.0141
35.3022    6.3620
35.3029    6.4793
35.3035    6.4663
35.3041    6.4665
35.3047    6.4646
35.3053    6.4844
35.3060    6.4743
35.3066    6.4865
35.3072    6.4878
35.3078    6.4975
35.3085    6.4952
35.3091    6.4958
35.3097    6.4734
35.3103    6.4082
35.3109    6.3767
35.3116    6.3786
35.3122    6.3796
35.3128    6.5867
35.3134    7.0733
35.3141    7.3427
35.3147    7.3238
35.3153    7.3093
35.3159    7.3188
35.3166    7.3436

B =
35.2985    1.0500
35.3053    1.0600
35.3085    1.0400
35.3166    1.0700

By doing following plot

plotyy(A(:,1),Binter,A(:,1),A(:,2))

It is visible that 'A' has three different levels. For each level of 'A' there is correspond 'B' value. Now I required to get interpolated values of B(:,2) based on time A(:,1). 'Binter' is the column of length 'A'.

Binter= interp1(B(:,1),B(:,2),A(:,1),'linear')
Binter =
NaN
1.0509
1.0518
1.0527
1.0537
1.0546
1.0555
1.0564
1.0573
1.0582
1.0591
1.0597
1.0558
1.0519
1.0481
1.0442
1.0403
1.0421
1.0444
1.0468
1.0491
1.0514
1.0537
1.0560
1.0583
1.0606
1.0629
1.0652
1.0675
1.0698

But I required to start to do only interpolation for the periond in which A(:,2) is changing rapidly [diff(A(:,2))>=0.1]. The rest should not do any interpolation but consider the orginal values. The out put should be something like this

Required_Output =
   NaN
1.0500
1.0500
1.0500
1.0500
1.0525
1.0550
1.0575
1.0600
1.0600
1.0600
1.0600
1.0558
1.0519
1.0481
1.0442
1.0400
1.0400
1.0400
1.0400
1.0400
1.0400
1.0400
1.0475
1.0550
1.0625
1.0700
1.0700
1.0700
1.0700

In the 'Required_Output' there is no interpolation done for corresponding 'A(:,2)' when changes in 'A(:,2)' were smaller or only one point in 'B(:,2)' was available in the different levels of 'A(:,2)'. The single available point in 'B(:,2)'is taken without any interpolation.The interpolation started until changes 'A(:,2)' stays larger than defined or more than one point available in 'B(:,2)' for the different levels in 'A(:,2)'.
Thank you for your suggestion/expertise.


Pulling reports from Microsoft Sql server

I was wondering what is the process to be able to pull reports from a database. The company I work for uses EBIS which is a program for aviation repair stations. It stores everything to its own database on our server but the GUI doesn't really have good means to pull reports. I have some background in computers and have messed around with sql just as a hobby, so my company wants me to be the one to try and get these reports for them. I have access to the server through SSMS and can run queries on it. I just haven't had any experience pulling certain tables and export them to excel or just using SSMS for reporting. Any help would be appreciated.

Thank you


Ajax to retrieve data from mySQL database and create a table

Hello guys and sorry if this is a double post.

I have created a database that contains 4 values FLID, DEPID, ARRID, Distance.
I managed to use an Ajax method to display the data of one of the rows of the database:

<?php
    if( isset($_POST['DEPID']) === true && empty($_POST['DEPID']) ===false){
        require'../db/connect.php';
        $query = mysql_query("
            SELECT `Flights`.`FLID`,`Flights`.`DEPID`,`Flights`.`ARRID`,`Flights`.`Distance`
            FROM `Flights`
            WHERE `Flights`.`DEPID` ='".mysql_real_escape_string(trim($_POST['DEPID'])) ."'");

        echo(mysql_num_rows($query)!== 0) ? mysql_result($query, 0, 'FLID') : 'Departure Airport not found ';
        echo(mysql_num_rows($query)!== 0) ? mysql_result($query, 0, 'DEPID') : 'Departure Airport not found ';
        echo(mysql_num_rows($query)!== 0) ? mysql_result($query, 0, 'ARRID') : 'Departure Airport not found ';
        echo(mysql_num_rows($query)!== 0) ? mysql_result($query, 0, 'Distance') : 'Departure Airport not found ';
    }
?>

My question is how to make this code retrieve all of the rows in the database that has the same DEPID and how to add the results to a table.

I have created the following code in an attempt to solve my problem and I have reached this point:

<?php
if( isset($_POST['DEPID']) === true && empty($_POST['DEPID']) ===false){
    require'../db/connect.php';
    $query = mysql_query("SELECT * FROM Flights WHERE DEPID ='DEPID'");
    $result = mysql_query($mysql_connect,$query) or die ("Error");
    echo "<table><tr><th>Flight ID</th><th>Departure Airport</th><th>Arrival Airport</th><th>Distance</th></tr>";

    while($row = mysql_fetch_array($result)) {
        echo "<tr><td>" . $row['FLID'] . "</td><td>" . $row['DEPID'] . "</td><td>" . $row['ARRID'] . "</td><td>" . $row['Distance'] . "</td></tr>";
    }
    echo "</table>";
}

Now I have the problem that the code fails with this message:

Warning: mysql_query() expects parameter 2 to be resource, boolean given in /home/ak118043/public_html/ajax/name.php on line 9
  Thanks in advance.


Server Control Auto Postback with form has _blank attribute

My case is I have an asp.net page has a form

<form id="form1" runat="server" target="_blank">

and a button redirect to another page and this page will open in a new window because of the target attribute of the form .

<asp:Button ID="button1" runat="server" PostBackUrl="~/kindofpage.aspx" Text="Generate" />

and I have a dropdownlist has auto postback = true to post the past to fill another dropdownlist by selected data .

<asp:dropdownliast id="Make" name="Make" runat="server" autopostback="true"></asp:dropdownlist>

the question is : why when I select item from the auto postbacked dropdown an blank page opened ?

I need a way to post the page by the dropdownlist without openning a blank page ..

Thank you,


Send a digitally signed mail with Joomla Mailer

I want send an email previosly signed with openssl_pkcs7_sign PHP function using the Joomla Mailer class.

Anyone know how can I do this?


Segmentation fault when releasing a string in C

I have a "segmentation fault" error when I try to free the allocated memory of the string pointed from "new_job->jobs_adress" . I've allocated enough memory for my string (even if I allocate far beyond from what I need, I still have this problem), But there is still this error.

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

typedef struct job_t {
    pid_t pid;
    time_t creation_time;
    bool stop;
    bool foreground;
    char * jobs_adress;
} Job;

int main() {

    char * jobs_adress = "string";

    /* creating an object of "Job" Type */
    printf("another try");
    Job * new_job = (Job*)malloc(sizeof(new_job));
    if(!new_job) {
        return;
    }

    /* allocating memory for a new string, and copies the old string
      into the new string*/

    int length2=strlen(jobs_adress);
    char * str2 = malloc(length2+1);
    strcpy(str2,jobs_adress);
    new_job->jobs_adress=str2;

    new_job->pid = 1;
    new_job->creation_time = time(NULL);
    new_job->stop=false;
    new_job->foreground=true;

    free(new_job->jobs_adress);  // <=== the error is here

}


Objective-c Sorting NSArray with alphanumeric strings in correct order

I have an array of strings that contain numbers i.e. Shift 1 RT9909 I sort the array as follows:

NSSet *forms = dataObject.rtForms;

NSSortDescriptor *nameDescriptor = [NSSortDescriptor sortDescriptorWithKey:@"type" ascending:YES];
NSArray *sorted = [forms sortedArrayUsingDescriptors:[NSArray arrayWithObject:nameDescriptor]];

This works fine while the number of elements is under 10. After this point Shift 10 RT9909 is placed in front Shift 2 RT9909.

So my question is how can I sort the array so that Shift 10 RT9909 would follow Shift 9 RT9909


Schemamigration: adding a simple Null field

Okay, so I had an app called locationmanager with a model that looks like this:

class Location(models.Model):
    region = models.ForeignKey(Region)

and I want to change it to this

class Location(models.Model):
    region = models.ForeignKey(Region, blank=True, null=True)

So I ran a schemamigration and received the following:

$ python manage.py schemamigration locationmanager --auto
 ? The field 'Location.region' does not have a default specified, yet is NOT NULL.
 ? Since you are making this field nullable, you MUST specify a default
 ? value to use for existing rows. Would you like to:
 ?  1. Quit now.
 ?  2. Specify a one-off value to use for existing columns now
 ?  3. Disable the backwards migration by raising an exception; you can edit the migration to fix it later
 ? Please select a choice:

This is confusing to me. And yes I have read the south docs.

Firstly, why is it saying 'Location.region' does not have a default specified, yet is NOT NULL. The alterations I made to the field ARE making it the case that it is null, what gives? An explanation would be great.

Why do I need to specify a default? Once I specify this default where does it live? In an SQL table? Does this matter if I have existing data or is this simply for the scheme itself?

3.I sort of understand option 1,2 but what exactly would option 3 do? Why is it useful?

Thank you tremendously.


Sed replace text

I need to replace text with single quotes with sed and I can't get it to work.  Here is my code; can you help me?

I have a text file with this format:

#sometext
$configuration_TEstbk2_bk2_environment12 = 'lalala'
$configuration_TEstbk2_bk2_envoronment12 = 'lalala1'
$configuration_TEstbk2_bk2_staging12 = 'BACKUP 2'
$configuration_waq4faw4f_q4fq4qg4f = 'r234rq43rq4rqr'
$configuration_alice_StagingTEstBk_bk = 'testebk'
$configuration_deployment_overlays_alice_TEStStngDir = 'some'
$configuration_arefgqrqgrq_341q34tq34t = '134t135'

And I need to do something like:

sed s/$configuration_arefgqrqgrq_341q34tq34t   ='134t135'/$configuration_arefgqrqgrq_341q34tq34t = 'NEWVALUE'/g

I have tried with many combinations with sed but I can't find one that works.


Hide datagridview column but still access it value

The below code is using the column that i want to be not visible which is [0]

LoadData();
MessageBox.Show(p.AddNew());
dgpay.DataSource = p.AllData();
p.Move2Last();
ShowData();
for (int i = 0; i < dgpay.Rows.Count; i++)
{
    if (!dgpay.Rows[i].IsNewRow)
    {
        if (dgpay[0, i].Value.ToString() == txtpaymentid.Text)
        {
            dgpay.CurrentCell = dgpay.Rows[i].Cells[0];
            dgpay.Rows[i].Selected = true;
        }
        else
        {
            dgpay.Rows[i].Selected = false;
        }
    }
}

When i tried to make dgpay.Columns[0].Visible = false the above code wont run probably.

How can i hide the column without affecting the code.


Is it possible to get the unique selector from an IWebElement (WebElement) in Selenium using C#

tldr; version here:  I would like to retrieve a unique selector, or create one, from an IWebElement.  Is this possible?

I've got a testing framework where I've created actor classes for various elements such as an input box with a label.  The class is generalized so that a person doesn't need to create a new "click" method each time an input with a label is encountered.

My class has among its properties the IWebDriver and a few By selectors.  Of course, when it needs to take an action, it combines the two into a sensible command. Here is a simple example for my class.

public class InputActorClass
{
    IWebDriver Driver {get; set;}
    By Input {get; set;}
    public InputActorClass(IWebDriver driver, By selector)
    {
        Driver = driver;
        Selector = selector;
    }
    public InputActorClass SelectCheckbox()
    {
        IWebElement actor = Driver.FindElement(Input);
        if (!actor.selected) { actor.click(); }
        return this;
    }
}

As you can see, I just need to call SelectCheckbox and the class already knows the has the By selector object and the IWebDriver object.

However, I have come across a situation where I have to scan a list of input elements to find the one with the correct text.  But the only way I can think to do that at the moment is to do the following:

public void SelectOption(string value)
{
    By itemselectors = new ByChained(container, By.CssSelector("input"));
    foreach (IWebElement el in driver.FindElements(itemselectors))
    {
        if (el.text.Equals(value))
            actor = new InputActorClass(driver, el.???);
    }
    actor.SelectCheckbox();
    // and do other stuff that the InputActorClass may provide.
}

An astute reader might suggest I use XPath to create my selector instead of going through the whole foreach loop. My problem is that these particular input elements are nested in various dynamically created categories and may have the same name between the categories.  And, since it is dynamically created, I'm not guaranteed my desired element is in the same nth-child() location.

Of course, I may just have to break down and use XPath to select the category and the input element. I'm hoping there is a way to do what I'm asking.

Here's some html for example:

<body>
  <div class="checkbox">
    <div>
      <input type="checkbox"/>
      <label>My First Checkbox</label>
    </div>
    <div>
      <input type="checkbox"/>
      <label>My Second Checkbox</label>
    </div>
  </div>
</body>

Here's some C# code that might iterate through the html:

CheckboxActorClass InputActor;
foreach (IWebElement el in driver.FindElements(By.CssSelector(".checkbox label")))
{
    if (el.Text.Equals(textToMatch))
    {
        By selector = el.GetUniqueSelector();  // this line is obviously not right.  What *is* the correct solution?
        InputActor = new CheckboxActorClass(driver, new ByChained(selector, By.XPath("/../input")));
        break;
    }
}
// Do stuff with the InputActor, like InputActor.Select();