答:
If you are able to access the file, you can just read the value directly from Java:

SQLiteDatabase db = SQLiteDatabase.openDatabase(
    "/data/data/com.google.android.gm/databases/mailstore.romapudelca@gmail.com.db",
    null, SQLiteDatabase.OPEN_READONLY);
try {
    Cursor c = db.rawQuery("SELECT bodyCompressed FROM ...", null);
    try {
        if (c.moveToFirst()) {
            byte[] blob = c.getBlob(0);

            // ... decompress the blob ...
        }
    } finally {
        c.close();
    }
} finally {
    db.close();
}
```

Title: deflate zlib from a sqlite android database

Body:
im trying to uncompress the data retrieve from sqlite gmail database to do some triggers. How can i do this?

This is the output from bodyCompressed.

pë☼IìÑ61UX 4×►▒▒ü4`¼┬♠6~ó©DX?┴¯╠ß1╝Q.
Cmhs↓×♥ògS'â%ÅÙÅDR½òÙ%Á┌┐e"Ì↓fÚp§Y7±[±☻¸h"X

You can see on this image

I need to do this in terminal but i dont know what can i do.

EDIT ADDING HEX

789CAD56CB72E246145D8FBFA2C354668524B031D8209478FC20F178ECB19D729C6C522DF59568DCEA96FB6183BF2659669155FE60FC63B92D60603C76D5A4128A424D3FEE3DE7DC731B6297C4914B36365E6DBC5ABD9FBCFC62CCF81D31762660D84869765368E5240B322594EEBF6E753A9D6D18CCBFDD8FB985468271624B5301CB6325D50597FD563525D4594596834149A7C13D6776DCDF6EE1E4E0A5F8754C0CAA93D832824BA6A272D8D86C24312F8B659AB5480D6274366C8CADAD4C3F8A32DE0D0BA50A01CE80CE94B4206D98A932AAB49ACEA2CDEBE3F7873FBD3D85D3B46AC13B3B7DFB70B32F8A8CA9AAB0E9E5E9E4E0FCE4E8846F5EFE3A1E6FFDDC15E2C3F9556F66A6B7EF1F46C1E1F1B4DAFDE117713E34AD8005D00E72FBDA67C6C43C447C4ED7A9663F1E5FC9CB2A9C5405E28E2CF31FFA336654F0027965880E74639DE892638ED803C31FA0BFE5059B2B1BA4CA5A55F67B483C39757047895496E73CA3197FFC5B1206244E93D1D9C90315AABDBBD389A3741DC232FF5727F9F8FB33A75F469FC4948C35E4F38AA02EF7F7F7610AB6CE17828918B5CA042548432710F922495A42D4EEECB67ABD4EAFDDEB767A6F68590DC07C9262CD73CF1987A59D3C1F5494312E8B7EDB7BAEDD45362B72ED1DFC2AB884600CBC18DB7E3BDCDA1AA44A33D081A68C3BD3DFC22D16A6366090294D2D57B22F95846F7859296DA9B40D62511FB0C3C66FA9A0F2A641900C0D0CCD4103E31A32EBB45879D1539F7BB17605AE7D3716433035BDDBE17F10E8DBCDEE228C514E67302C4ACA453DE18C1DFABD3BDDB62FFF6EA7D56A2D168AE1DED1F964FF74343AB93659F7E8E2DDB5CACDE86847F0D1E8EA81EDCEF87923B9024D4E3F794AC938A22F78F80B0FB5B7BFF0909F7A62A2E7FBFB9968AD65456ABBF527488DE7B34559FDEE3EB7B89435924363812C2423D813580C5E70A69ABE1F4A2A415302D34C38C3EF689350621CAE60388905D45C9119A91CE0DEF985810A70992B5D2E9A0A6773CE40669C0ADC6ADC042CC5262006320D78CDE1DD928341B1A86892CCCD3C823B278AC579A908267BFC8354A04B6E39A3042D45042502662139C40CD4288F754C534C8E4EE229C2F7A756BCFC11D05AE9261E235A15B45486DC3AA859D6701176894E44524D4C6A885088BD7492E32E52AF203D9CD21A30B840C36AC4C73385296B600AB5910ED3A260D47AC61EFFCC13CC0061D7CA81E0252A57AFA198E6F12F9FC51F45465E4447C5ADE34884A9CC217C5488B289AB9F8294DC942A247B86D7A39ACD1C65B6645407E28882A76E91265315A7441167B9E00FABDB6E5DA226515F9BBFB9DA45EB8CB9F32364972335812562CD79D1A4273FF6F5A0E669D9A8C639060283959557A5CEC56AFC27671F0E50395CBC38C07173E13098E0CF124213CA9FC44A8F71B0175E84FBE159B866D702AF2087FE5E950D7C8F939826DE9BDFAF5D19BE43C3676EE9FFABBBFE45F7AE055CFC3824B1DF937CFC93BC057BE97791CDB0D5EEC5513DFF59647CFA3F13388C236C20FCCBF20FFDA7054B

EDITED WITH JAVA CODE TRYING THIS

private String getTextMail(){
String mail="";
Process sh = null;
try {
    sh = Runtime.getRuntime().exec("su", null,null);
} catch (IOException e) {
    e.printStackTrace();
}

OutputStream os = sh.getOutputStream();
try {
    os.write(("sqlite3 /data/data/com.google.android.gm/databases/mailstore.romapudelca@gmail.com.db \"SELECT bodyCompressed FROM MESSAGES WHERE dateSentMs=(SELECT max(dateSentMs) from messages)\"").getBytes("ASCII"));
    os.flush();
    os.close();
    InputStream is=sh.getInputStream();
    ByteArrayOutputStream buffer = new ByteArrayOutputStream();

    int nRead;
    byte[] data = new byte[16384];

    while ((nRead = is.read(data, 0, data.length)) != -1) {
        buffer.write(data, 0, nRead);
    }
    Inflater decompresser = new Inflater(true);
    decompresser.setInput(buffer.toByteArray());
    byte[] result = new byte[4096];
    int resultLength = decompresser.inflate(result);
    decompresser.end();
    sh.waitFor();
    mail=new String(result);
} catch (InterruptedException e) {
    e.printStackTrace();
} catch (IOException e) {
    e.printStackTrace();
} catch (DataFormatException e) {
    e.printStackTrace();
}

return mail;
}

Java code return me this:

W/System.err: java.util.zip.DataFormatException: invalid stored block lengths
W/System.err:     at java.util.zip.Inflater.inflateImpl(Native Method)
W/System.err:     at java.util.zip.Inflater.inflate(Inflater.java:237)
W/System.err:     at java.util.zip.Inflater.inflate(Inflater.java:214)
W/System.err:     at cpc.cpc_dectect.MainActivity$telegramTask$override.getTextMail(MainActivity.java:229)
W/System.err:     at cpc.cpc_dectect.MainActivity$telegramTask$override.doInBackground(MainActivity.java:249)
W/System.err:     at cpc.cpc_dectect.MainActivity$telegramTask$override.access$dispatch(MainActivity.java)
W/System.err:     at cpc.cpc_dectect.MainActivity$telegramTask.doInBackground(MainActivity.java:0)
W/System.err:     at cpc.cpc_dectect.MainActivity$telegramTask.doInBackground(MainActivity.java:196)
W/System.err:     at android.os.AsyncTask$2.call(AsyncTask.java:307)
W/System.err:     at java.util.concurrent.FutureTask.run(FutureTask.java:237)
W/System.err:     at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1113)
W/System.err:     at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:588)
W/System.err:     at java.lang.Thread.run(Thread.java:833)

ERROR USING PRINTF MODE

\x08\x00\x00\x00\x00\x00" |cat - fich.gz| gzip -d                                   <

bla bla bla bl abl abla

<d
iv>

Links:

┬á 1. <a href="https://arpo.com/2asajshkdashjkashdjka0a gzip: failed gz
close

If i use -dc params in gzip the system returns:

-dc: No such file or directory
sush: cat: <stdout>: Broken pipe


来源: stackexchange

问:
double android.location.Location.getLatitude()' on a null object reference
the only reason i'm asking this again, is because i've tried all the answers and its not working for me i'm trying to get the current user location but it's not working so this is what i've been trying to do, btw i already setted up all the permissions neeeded and i keep getting the double android location.getlatitude on a null object reference error and fatal execption main , pleaaase help me
this my GPSTRACKER Java class code : </p>

```<code>package com.example.nefissa.androidtest;

 import android.*;
 import android.Manifest;
 import android.app.Service;
 import android.content.Context;
 import android.content.Intent;
 import android.content.pm.PackageManager;
 import android.location.Location;
 import android.location.LocationListener;
 import android.location.LocationManager;
 import android.os.Bundle;
 import android.os.IBinder;
 import android.support.annotation.Nullable;
 import android.support.v4.content.ContextCompat;

public class GPSTracker extends Service implements LocationListener{

private final Context context;

boolean isGPSEnabled =false;
boolean isNetworkEnabled =false;
boolean canGetLocation =false;

Location location;
protected LocationManager locationManager;

  public GPSTracker(Context context){
   this.context=context;
  }

// create a GetLocation Method //

public Location getLocation(){

    try{
        locationManager=(LocationManager) context.getSystemService(LOCATION_SERVICE);
        isGPSEnabled = locationManager.isProviderEnabled(locationManager.GPS_PROVIDER);
        isNetworkEnabled=locationManager.isProviderEnabled(locationManager.NETWORK_PROVIDER);

        if(ContextCompat.checkSelfPermission(context, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED
        || ContextCompat.checkSelfPermission(context, Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED ){

            if(isGPSEnabled){
                if(location==null){
                    locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,100000,10,this);
                    if(locationManager!=null){
                          location=locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
                    }
                  }
            }
               // if location is not found from GPS then it will found from network //
            if(location==null){
                if(isNetworkEnabled){
                           locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER,100000,10,this);
                        if(locationManager!=null){
                              location=locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
                        }
                    }

            }
        }

    }catch(Exception e){

    }
    return location;
}

@Nullable
@Override
public IBinder onBind(Intent intent) {
    return null;
}

@Override
public void onLocationChanged(Location location) {

}

@Override
public void onStatusChanged(String provider, int status, Bundle extras) {

}

@Override
public void onProviderEnabled(String provider) {

}

@Override
public void onProviderDisabled(String provider) {

}
}
</code>```

<p>and My Main Activity code : </p>

```<code>package com.example.nefissa.androidtest;

 import android.location.Location;
 import android.support.v4.app.FragmentActivity;
  import android.os.Bundle;

 import com.google.android.gms.maps.CameraUpdateFactory;
 import com.google.android.gms.maps.GoogleMap;
  import com.google.android.gms.maps.OnMapReadyCallback;
   import com.google.android.gms.maps.SupportMapFragment;
   import com.google.android.gms.maps.model.LatLng;
 import com.google.android.gms.maps.model.MarkerOptions;

 public class MapsActivity extends FragmentActivity implements     OnMapReadyCallback {

private GoogleMap mMap;
private GPSTracker gpsTracker;
private Location mLocation;
double latitude;
double longitude;

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

    gpsTracker= new GPSTracker(getApplicationContext());
    mLocation=gpsTracker.getLocation();
    latitude= mLocation.getLatitude();
    longitude= mLocation.getLongitude();

    // Obtain the SupportMapFragment and get notified when the map is ready to be used.
    SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
            .findFragmentById(R.id.map);
    mapFragment.getMapAsync(this);
}

/**
 * Manipulates the map once available.
 * This callback is triggered when the map is ready to be used.
 * This is where we can add markers or lines, add listeners or move the camera. In this case,
 * we just add a marker near Sydney, Australia.
 * If Google Play services is not installed on the device, the user will be prompted to install
 * it inside the SupportMapFragment. This method will only be triggered once the user has
 * installed Google Play services and returned to the app.
 */
@Override
public void onMapReady(GoogleMap googleMap) {
    mMap = googleMap;

    // Add a marker in Sydney and move the camera
    LatLng sydney = new LatLng(latitude,longitude);
    mMap.addMarker(new MarkerOptions().position(sydney).title("you are here"));
    mMap.moveCamera(CameraUpdateFactory.newLatLng(sydney));
  }
 }
</code>```

答:
After onMapReady is called, you'd better to initialize gpsTracker.

```<code>   gpsTracker= new GPSTracker(getApplicationContext());

   if(gpsTracker!=null){
       mLocation=gpsTracker.getLocation();
       latitude= mLocation.getLatitude();
       longitude= mLocation.getLongitude();
   }
</code>```

And I think gpsTracker.getLocation have to change to logic.
please read a android gps guide.

ContentLicense: CC BY-SA 3.0

Body:
the only reason i'm asking this again, is because i've tried all the answers and its not working for me i'm trying to get the current user location but it's not working so this is what i've been trying to do, btw i already setted up all the permissions neeeded and i keep getting the double android location.getlatitude on a null object reference error and fatal execption main , pleaaase help me
this my GPSTRACKER Java class code :

package com.example.nefissa.androidtest;

 import android.*;
 import android.Manifest;
 import android.app.Service;
 import android.content.Context;
 import android.content.Intent;
 import android.content.pm.PackageManager;
 import android.location.Location;
 import android.location.LocationListener;
 import android.location.LocationManager;
 import android.os.Bundle;
 import android.os.IBinder;
 import android.support.annotation.Nullable;
 import android.support.v4.content.ContextCompat;

public class GPSTracker extends Service implements LocationListener{

private final Context context;

boolean isGPSEnabled =false;
boolean isNetworkEnabled =false;
boolean canGetLocation =false;

Location location;
protected LocationManager locationManager;

  public GPSTracker(Context context){
   this.context=context;
  }

// create a GetLocation Method //

public Location getLocation(){

    try{
        locationManager=(LocationManager) context.getSystemService(LOCATION_SERVICE);
        isGPSEnabled = locationManager.isProviderEnabled(locationManager.GPS_PROVIDER);
        isNetworkEnabled=locationManager.isProviderEnabled(locationManager.NETWORK_PROVIDER);

        if(ContextCompat.checkSelfPermission(context, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED
        || ContextCompat.checkSelfPermission(context, Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED ){

            if(isGPSEnabled){
                if(location==null){
                    locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,100000,10,this);
                    if(locationManager!=null){
                          location=locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
                    }
                  }
            }
               // if location is not found from GPS then it will found from network //
            if(location==null){
                if(isNetworkEnabled){
                           locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER,100000,10,this);
                        if(locationManager!=null){
                              location=locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
                        }
                    }

            }
        }

    }catch(Exception e){

    }
    return location;
}

@Nullable
@Override
public IBinder onBind(Intent intent) {
    return null;
}

@Override
public void onLocationChanged(Location location) {

}

@Override
public void onStatusChanged(String provider, int status, Bundle extras) {

}

@Override
public void onProviderEnabled(String provider) {

}

@Override
public void onProviderDisabled(String provider) {

}
}

and My Main Activity code :

package com.example.nefissa.androidtest;

 import android.location.Location;
 import android.support.v4.app.FragmentActivity;
  import android.os.Bundle;

 import com.google.android.gms.maps.CameraUpdateFactory;
 import com.google.android.gms.maps.GoogleMap;
  import com.google.android.gms.maps.OnMapReadyCallback;
   import com.google.android.gms.maps.SupportMapFragment;
   import com.google.android.gms.maps.model.LatLng;
 import com.google.android.gms.maps.model.MarkerOptions;

 public class MapsActivity extends FragmentActivity implements     OnMapReadyCallback {

private GoogleMap mMap;
private GPSTracker gpsTracker;
private Location mLocation;
double latitude;
double longitude;

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

    gpsTracker= new GPSTracker(getApplicationContext());
    mLocation=gpsTracker.getLocation();
    latitude= mLocation.getLatitude();
    longitude= mLocation.getLongitude();

    // Obtain the SupportMapFragment and get notified when the map is ready to be used.
    SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
            .findFragmentById(R.id.map);
    mapFragment.getMapAsync(this);
}

/**
 * Manipulates the map once available.
 * This callback is triggered when the map is ready to be used.
 * This is where we can add markers or lines, add listeners or move the camera. In this case,
 * we just add a marker near Sydney, Australia.
 * If Google Play services is not installed on the device, the user will be prompted to install
 * it inside the SupportMapFragment. This method will only be triggered once the user has
 * installed Google Play services and returned to the app.
 */
@Override
public void onMapReady(GoogleMap googleMap) {
    mMap = googleMap;

    // Add a marker in Sydney and move the camera
    LatLng sydney = new LatLng(latitude,longitude);
    mMap.addMarker(new MarkerOptions().position(sydney).title("you are here"));
    mMap.moveCamera(CameraUpdateFactory.newLatLng(sydney));
  }
 }

Body:
After onMapReady is called, you'd better to initialize gpsTracker.

   gpsTracker= new GPSTracker(getApplicationContext());

   if(gpsTracker!=null){
       mLocation=gpsTracker.getLocation();
       latitude= mLocation.getLatitude();
       longitude= mLocation.getLongitude();
   }

And I think gpsTracker.getLocation have to change to logic.
please read a android gps guide.


问:
HTTP Internal error 500 on Tomcat during load testing
Our team is performing load testing on our Tomcat based application (Spring Core + JSF + Oracle) which uses a Apache web server for forwarding requests. The load testing tool (WAPT) is trying to simulate 3 users accessing a single search page with the same parameters being searched. However it results in a failure with an HTTP Internal Error 500 for most runs. When the same test is done manually, this issue doesn't happen.
So is there any  additional resources that the tool may be blocking? The server logs do not disclose much in terms of the specific issue there might be in the code, not even a stack trace. But is there some way to retrieve that?
Any help on this is appreciated.</p>

答: This turned out to be an issue on the Database side. Certain DB parameters were not configured in the newer environment due to which there high parsing & executions on the SQL side. </p>


问:
Why would anyone use best fit memory allocation?
I'm reading Modern Operating Systems by Andrew Tanenbaum, and he writes that best fit is a widely used memory allocation algorithm.
He also writes that it's slower than first fit/next fit since it have to search the entire list of allocated memory. And that it tends to waste more memory since it leaves behind a lot of small useless gaps in memory.

Why is it then widely used? Is it some obvious advantage i have overlooked?

答:
Space efficiency and versatility is really the answer.  Large blocks can fit unknown future needs better than small blocks, so a best-fit algorithm tries to use the smallest blocks first.

First-fit and next-fit algorithms (that can also cut up blocks) may end up using pieces of the larger block first, which increases the risk that a large malloc() will fail.  This is essentially harm from large blocks of external fragmentation.

A best-fit algorithm will often find fits that are only a few bytes larger, leading to fragmentation that is only a few bytes, while also saving the large blocks for when they're needed.  Also, leaving the large blocks untouched as long as possible helps cache locality and minimizes the load on the MMU, minimizing costly page faults and and saving memory pages for other programs.

A good best-fit algorithm will properly maintain its speed even when it's managing a large number of small fragments, by increasing internal fragmentation (which is hard to reclaim) and/or by using good lookup tables and search trees.

First-fit and next-fit still also face their own searching problems.  Without good size indexing in these algorithms, they still have to spend time searching through blocks for one that fits.  Since their "standards are lower," they may find a fit faster using a straightforward search, but as soon as you add intelligent indexing, the speeds between all algorithms becomes much closer.

The one I've been using and tweaking for the last 6 years can find the best fit block in O(1) time for >90% of all allocs.  It utilizes a handful of strategies to jump straight to the right block, or start very close so searching is minimized.  It has, on more than one occasion, replaced existing block-pool or first-fit algorithms due to it's performance and ability to pack allocations more efficiently.


问:
Unable to run parallel tests using maven surefire plugin and EasyMock
I've trying to run my JUnit classes in parallel, every time I run my tests I'm getting different errors. Some times a ClassA fails, some times the ClassB fails, sometimes nothing fails.

I'm using maven-surefire-plugin (version 2.19.1) and JUnit 4.8. What I noticed is the exception I'm getting is an Assertion Error from EasyMock. The problem seems to be when I have a class that creates an instance of Logger class (log4j), internally calls "RepositorySelector.getLoggerRepository()" to get the Logger given a "classname". When it runs in parallel, more than one class creates an instance of the Logger and EasyMock is detecting that "RepositorySelector.getLoggerRepository()" is being called more than the expected calls.

here an example:

```<code>public class ClassA{
    private static final Logger LOGGER = Logger.getLogger(ClassA.class);
    public void someMethod(){
        LOGGER.info("SomeMethod");
    }
}

public class ClassB{
    private static final Logger LOGGER = Logger.getLogger(ClassB.class);
    public void someMethodB(){
        LOGGER.info("SomeMethodB");
    }
}

public class ClassATest{
    private ClassA classUnderTest;
    @Before
    public void setUp(){
        classUnderTest = new ClassA();
    }

    @Test
    public void testSomeMethod(){
        classUnderTest.someMethod();
    }
}

public class ClassBTest{
    private ClassB classUnderTest;
    @Before
    public void setUp(){
        classUnderTest = new ClassB();
    }

    @Test
    public void testSomeMethodB(){
        classUnderTest.someMethodB();
    }
}
</code>```

And I have this configuration on my pom.xml

```<code><plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-surefire-plugin</artifactId>
    <version>2.19.1</version>
    <configuration>
        <forkMode>once</forkMode>
        <!-- Parallel classes -->
        <parallel>classes</parallel>
        <threadCountClasses>2</threadCountClasses>
    </configuration>
</plugin>
</code>```

To me, seems like when two tests ran at the same time, and each test executes the @Before method (setUp method) and calls the constructor of ClassA or B and it creates a new instance of the Logger class and EasyMock for some reason is trying to verify the number of times and there is where I get the Assertion Error. Is that something I'm missing? or is something that EasyMock cannot handle?

My original project has like a hundred of JUnit tests, almost all of them are logging some information. If I disabled the "parallel" option, everything works.
Some times I got the assertion error, others I got a NullPointerException like the @Before method never gets executed and it tries to execute a @Test method and throws the NPE cause it wasn't initialized before. (That happens few times).

Any thoughts? am I missing something here?

Java version: jdk1.7.0_55
Maven: apache-maven-3.2.5
Junit: 4.8.2
Maven Surefire plugin: 2.19.1
EasyMock: 3.2  (easymockclassextension)

答:
If you run in parallel, your tests must agree with the Java Memory Model. That seems to be your main problem.

First, from what you are saying RepositorySelector is a mock that seem shared by all your tests. So it might be called twice in parallel I guess. You can set EasyMock expectations to match that (andStubReturn instead of andReturn).

Then, the NPE are probably unrelated to EasyMock. Again, I don't have enough information to be definitive on my answer but it looks like publication issues. One thread set an attribute which is not volatile so the other thread doesn't see it. I don't know if the instance creation and the @Before are occurring in the same thread. That can explain the problem. You can confirm that by doing System.out.println(Thread.currentThread()) in the constructor and in the @Before. Or you can set everything volatile and it might solve your problem.

I would also suggest to update EasyMock to 3.4 and JUnit to 4.12 as there might be some concurrency fixes in both.

Finally, EasyMock supports multithreading. So there should not be any problem on that side unless there is a bug.

Body:
I've trying to run my JUnit classes in parallel, every time I run my tests I'm getting different errors. Some times a ClassA fails, some times the ClassB fails, sometimes nothing fails.

I'm using maven-surefire-plugin (version 2.19.1) and JUnit 4.8. What I noticed is the exception I'm getting is an Assertion Error from EasyMock. The problem seems to be when I have a class that creates an instance of Logger class (log4j), internally calls "RepositorySelector.getLoggerRepository()" to get the Logger given a "classname". When it runs in parallel, more than one class creates an instance of the Logger and EasyMock is detecting that "RepositorySelector.getLoggerRepository()" is being called more than the expected calls.

here an example:

public class ClassA{
    private static final Logger LOGGER = Logger.getLogger(ClassA.class);
    public void someMethod(){
        LOGGER.info("SomeMethod");
    }
}

public class ClassB{
    private static final Logger LOGGER = Logger.getLogger(ClassB.class);
    public void someMethodB(){
        LOGGER.info("SomeMethodB");
    }
}

public class ClassATest{
    private ClassA classUnderTest;
    @Before
    public void setUp(){
        classUnderTest = new ClassA();
    }

    @Test
    public void testSomeMethod(){
        classUnderTest.someMethod();
    }
}

public class ClassBTest{
    private ClassB classUnderTest;
    @Before
    public void setUp(){
        classUnderTest = new ClassB();
    }

    @Test
    public void testSomeMethodB(){
        classUnderTest.someMethodB();
    }
}

And I have this configuration on my pom.xml

<plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-surefire-plugin</artifactId>
    <version>2.19.1</version>
    <configuration>
        <forkMode>once</forkMode>

        <parallel>classes</parallel>
        <threadCountClasses>2</threadCountClasses>
    </configuration>
</plugin>

To me, seems like when two tests ran at the same time, and each test executes the @Before method (setUp method) and calls the constructor of ClassA or B and it creates a new instance of the Logger class and EasyMock for some reason is trying to verify the number of times and there is where I get the Assertion Error. Is that something I'm missing? or is something that EasyMock cannot handle?

My original project has like a hundred of JUnit tests, almost all of them are logging some information. If I disabled the "parallel" option, everything works.
Some times I got the assertion error, others I got a NullPointerException like the @Before method never gets executed and it tries to execute a @Test method and throws the NPE cause it wasn't initialized before. (That happens few times).

Any thoughts? am I missing something here?

Java version: jdk1.7.0_55
Maven: apache-maven-3.2.5
Junit: 4.8.2
Maven Surefire plugin: 2.19.1
EasyMock: 3.2  (easymockclassextension)


问:
What are the chronological steps in building a cross browser compatible site?
I am working on my first project that requires me to worry about cross browser compatibility.  Since this is my first time doing so, I dont know how to go about completing the project.  I am specifically worried about IE.  Should I complete my project in a more graceful browser then hack it to work in IE, or should I simultaneously build my program up in both environments?</p>

答:
I develop for Firefox first, and then work out the IE buggery. Rarely do I "hack" it, rather find something that works in both, or at worst use IE conditional comments. Just one coder's preference. Always a good idea to test with Safari, too.

Two big advantages of Firefox are: the Error Console, and the Firebug plugin.

ContentLicense: CC BY-SA 2.5


问:
Parse date with split seconds using read_delim
Using the read_delim function from the readr package I would like to parse a csv file including a date time column in the format 2016-12-29 09:00:18.456, explicitly stating the format.

From the following sources (https://stat.ethz.ch/R-manual/R-devel/library/base/html/strptime.html , https://www.rdocumentation.org/packages/readr/versions/1.0.0/topics/parse_datetime), I understand that I should use this: "%Y-%m-%d %H:%M:%OS" as part of the code:

```<code>a <- read_delim("file.csv", col_names = TRUE, delim = ";",
                locale = locale(decimal_mark = ","), col_types = cols(
                'Start time' = col_datetime("%Y-%m-%d %H:%M:%OS")))
</code>```

However, I get the following error:

```<code>Warning: * parsing failures.
row        col                     expected                  actual
  1 Start time date like %Y-%m-%d %H:%M:%OS 2016-12-29 09:00:18.456
</code>```

Here is a short reproducible example of the problem:

```<code>parse_datetime("2016-12-29 09:00:18.456", "%Y-%m-%d H%:M%:%OS")
</code>```

What am I doing wrong?

答:
a <- read_delim("file.csv", col_names = TRUE, delim = ",", locale = locale(decimal_mark = "."), col_types = cols( 'Start time' = col_datetime("%Y-%m-%d %H:%M:%OS")))

Just need to change your delimiter and decimal mark.

ContentLicense: CC BY-SA 4.0

Body:
Using the read_delim function from the readr package I would like to parse a csv file including a date time column in the format 2016-12-29 09:00:18.456, explicitly stating the format.

From the following sources (https://stat.ethz.ch/R-manual/R-devel/library/base/html/strptime.html , https://www.rdocumentation.org/packages/readr/versions/1.0.0/topics/parse_datetime), I understand that I should use this: "%Y-%m-%d %H:%M:%OS" as part of the code:

a <- read_delim("file.csv", col_names = TRUE, delim = ";",
                locale = locale(decimal_mark = ","), col_types = cols(
                'Start time' = col_datetime("%Y-%m-%d %H:%M:%OS")))

However, I get the following error:

Warning: * parsing failures.
row        col                     expected                  actual
  1 Start time date like %Y-%m-%d %H:%M:%OS 2016-12-29 09:00:18.456

Here is a short reproducible example of the problem:

parse_datetime("2016-12-29 09:00:18.456", "%Y-%m-%d H%:M%:%OS")

What am I doing wrong?


问:
How can we add a UIGestureRecognizer to Outlet Collection?
I'm trying to add a tap gesture to an outlet collection of labels [UILabel], like this:

```<code>@IBOutlet var subLabels: [UILabel]!

    override func viewDidLoad() {
            super.viewDidLoad()

            let tap = UITapGestureRecognizer(target: self, action: #selector(HomePageViewController.selectSubLabel(tap:)))
            tap.numberOfTapsRequired = 1
            tap.cancelsTouchesInView = false

            for i in (0..<(subLabels.count)) {
                subLabels[i].addGestureRecognizer(tap)
            }
    }

    func selectSubLabel(tap: UITapGestureRecognizer) {
            print("Gesture Is WORKING!")
        }
</code>```

and i tried to add it on a single label in storyboard; but NONE are working.

答:
Firstly, you need to allow user interaction on a label (it is turned off by default):

```<code>for i in (0..<(subLabels.count)) {
    subLabels[i].isUserInteractionEnabled = true
    subLabels[i].addGestureRecognizer(tap)
}
</code>```

but gesture recognizer can observe for gestures only in one view.
So, there are two options:

I. Dedicated gesture recognizer for every label

```<code>for i in (0..<(labels.count)) {
    let tap = UITapGestureRecognizer(target: self, action: #selector(selectSubLabel(tap:)))
    labels[i].isUserInteractionEnabled = true
    labels[i].addGestureRecognizer(tap)
}
</code>```

II. One gesture recognizer for the parent view of the labels

```<code>override func viewDidLoad() {
    super.viewDidLoad()

    for i in (0..<(labels.count)) {
        subLabels[i].isUserInteractionEnabled = true
    }

    let tap = UITapGestureRecognizer(target: self, action: #selector(selectSubLabel(tap:)))
    view.addGestureRecognizer(tap)
}

func selectSubLabel(tap: UITapGestureRecognizer) {
    let touchPoint = tap.location(in: view)
    guard let label = subLabels.first(where: { $0.frame.contains(touchPoint) }) else { return }

    // Do your stuff with the label
}
</code>```

Body:
I'm trying to add a tap gesture to an outlet collection of labels [UILabel], like this:

@IBOutlet var subLabels: [UILabel]!

    override func viewDidLoad() {
            super.viewDidLoad()

            let tap = UITapGestureRecognizer(target: self, action: #selector(HomePageViewController.selectSubLabel(tap:)))
            tap.numberOfTapsRequired = 1
            tap.cancelsTouchesInView = false

            for i in (0..<(subLabels.count)) {
                subLabels[i].addGestureRecognizer(tap)
            }
    }

    func selectSubLabel(tap: UITapGestureRecognizer) {
            print("Gesture Is WORKING!")
        }

and i tried to add it on a single label in storyboard; but NONE are working.

Body:
Firstly, you need to allow user interaction on a label (it is turned off by default):

for i in (0..<(subLabels.count)) {
    subLabels[i].isUserInteractionEnabled = true
    subLabels[i].addGestureRecognizer(tap)
}

but gesture recognizer can observe for gestures only in one view.
So, there are two options:

I. Dedicated gesture recognizer for every label

for i in (0..<(labels.count)) {
    let tap = UITapGestureRecognizer(target: self, action: #selector(selectSubLabel(tap:)))
    labels[i].isUserInteractionEnabled = true
    labels[i].addGestureRecognizer(tap)
}

II. One gesture recognizer for the parent view of the labels

override func viewDidLoad() {
    super.viewDidLoad()

    for i in (0..<(labels.count)) {
        subLabels[i].isUserInteractionEnabled = true
    }

    let tap = UITapGestureRecognizer(target: self, action: #selector(selectSubLabel(tap:)))
    view.addGestureRecognizer(tap)
}

func selectSubLabel(tap: UITapGestureRecognizer) {
    let touchPoint = tap.location(in: view)
    guard let label = subLabels.first(where: { $0.frame.contains(touchPoint) }) else { return }

    // Do your stuff with the label
}


问:
How to read text from a file, identify adjacent duplicated words, and report their location in the text file?
I am trying to read a quote from a text file and find any duplicated words that appear next to each other. The following is the quote:

```<code>"He that would make his own liberty liberty secure,

must guard even his enemy from oppression;

for for if he violates this duty, he

he establishes a precedent that will reach to himself."
-- Thomas Paine
</code>```

The output should be the following:

Found word: "Liberty" on line 1

Found word: "for" on line 3

Found word: "he" on line 4

I have written the code to read the text from the file but I am having trouble with the code to identify the duplicates. I have tried enumerating each word in the file and checking if the word at one index is equal to the the word at the following index. However, I am getting an index error because the loop continues outside of the index range. Here's what I've come up with so far:

```<code>import string
file_str = input("Enter file name: ")
input_file = open(file_str, 'r')

word_list = []
duplicates = []

for line in input_file:
    line_list = line_str.split()
    for word in line_list:
        if word != "--":
            word_list.append(word)

for idx, word in enumerate(word_list):
    print(idx, word)
    if word_list[idx] == word_list[idx + 1]:
        duplicates.append(word)
</code>```

Any help with the current method I'm trying would be appreciated, or suggestions for another method.

答:
When you record the word_list you are losing information about which line the word is on.

Perhaps better would be to determine duplicates as you read the lines.

```<code>line_number = 1
for line in input_file:
    line_list = line_str.split()
    previous_word = None
    for word in line_list:
        if word != "--":
            word_list.append(word)
        if word == previous_word:
            duplicates.append([word, line_number])
        previous_word = word
    line_number += 1
</code>```

Body:
I am trying to read a quote from a text file and find any duplicated words that appear next to each other. The following is the quote:

"He that would make his own liberty liberty secure,

must guard even his enemy from oppression;

for for if he violates this duty, he

he establishes a precedent that will reach to himself."
-- Thomas Paine

The output should be the following:

Found word: "Liberty" on line 1

Found word: "for" on line 3

Found word: "he" on line 4

I have written the code to read the text from the file but I am having trouble with the code to identify the duplicates. I have tried enumerating each word in the file and checking if the word at one index is equal to the the word at the following index. However, I am getting an index error because the loop continues outside of the index range. Here's what I've come up with so far:

import string
file_str = input("Enter file name: ")
input_file = open(file_str, 'r')

word_list = []
duplicates = []

for line in input_file:
    line_list = line_str.split()
    for word in line_list:
        if word != "--":
            word_list.append(word)

for idx, word in enumerate(word_list):
    print(idx, word)
    if word_list[idx] == word_list[idx + 1]:
        duplicates.append(word)

Any help with the current method I'm trying would be appreciated, or suggestions for another method.

Body:
When you record the word_list you are losing information about which line the word is on.

Perhaps better would be to determine duplicates as you read the lines.

line_number = 1
for line in input_file:
    line_list = line_str.split()
    previous_word = None
    for word in line_list:
        if word != "--":
            word_list.append(word)
        if word == previous_word:
            duplicates.append([word, line_number])
        previous_word = word
    line_number += 1


问:
T-SQL round special cases
I need a way to round in T-SQL (SQL Server 2005).

```<code>0.0041 -> 0.005
0.0049 -> 0.005
0.0040 -> 0.004
</code>```

I have tried the following select with ROUND():

```<code>SELECT ROUND(0.004, 3,1) + .001
</code>```

The problem is: it doesn't work with 0.0040 -> 0.004

Title: T-SQL round special cases

Body:
I need a way to round in T-SQL (SQL Server 2005).

0.0041 -> 0.005
0.0049 -> 0.005
0.0040 -> 0.004

I have tried the following select with ROUND():

SELECT ROUND(0.004, 3,1) + .001

The problem is: it doesn't work with 0.0040 -> 0.004

Body:
This:

SELECT CEILING(1000 * 0.0041) / 1000.0

produces:

0.005

whereas this:

SELECT CEILING(1000 * 0.004) / 1000.0

produces:

0.004


问:
highchart is not displaying in django twitter bootstrap
I am having problem with displaying highchart in django. I am using twitter bootstrap.Chart is not showing in chart.html. Can anyone help me what I am doing wrong here?Please find below version of django

Django==1.8.7

django-highcharts==0.1.7

base.html:

```<code><!DOCTYPE html>
{% load staticfiles %}
<html>
<head>
  {% block title %}<title>mbr page </title>{% endblock %}
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <link href="{% static "mbr/css/boostrap-fluid-adj.css" %}" rel="stylesheet">
  <link href="{% static "mbr/css/bootstrap.min.css" %}" rel="stylesheet" media="screen">
  <link href="{% static "mbr/css/bootstrap-responsive.css" %}" rel="stylesheet">

  <style>
  body {
    padding-top: 50px;
  }
  @media (max-width: 980px) {
    body {
      padding-top: 0;
    }
  }
</style>
</head

<body>
<div class="navbar navbar-inverse navbar-fixed-top">
   <div class="navbar-inner">
       <div class="container-fluid">
           <button type="button" class="btn btn-navbar" data-toggle="collapse" data-target=".nav-collapse">
               <span class="icon-bar"></span>
               <span class="icon-bar"></span>
               <span class="icon-bar"></span>
           </button>

           <div class="nav-collapse collapse">
               <ul class="nav pull-right">
                    <li><a href="/admin/">Login</a></li>
               </ul>
               <ul class="nav navbar-nav">
                    <li class="active"><a href="/mbr/">Home</a></li>
                    <li><a href="{% url 'search_form' %}">Search s</a></li>
                    <li><a href="{% url 'results_list' %}">Results History</a></li>
                    <li><a href="{% url 'chart_test' %}">Statistics</a></li>
               </ul>
           </div>
       </div>
   </div>
</div>
<div class="container-fluid">
    <div class="row-fluid">
        <div class="span3">
             <div class="well sidebar-nav">
              <h3> Name</h3>
              <p class="active"><a href="/mbr/4/">TEST1</a></p>
              <p><a href="/mbr/3/">TEST2</a></p>
              <p><a href="/mbr/2/">TEST3</a></p>
              <p><a href="/mbr/1/">TEST4</a></p>
             </div>
        </div>
        <div class="span9">
            {% block content %}
            {% endblock %}
        </div>
    </div>
</div>

<hr>
<script src="{% static 'mbr/js/jquery-3.2.0.js' %}"></script>
<script src="{% static 'mbr/js/bootstrap.min.js' %}"></script>
</body>
</html>
</code>```

chart_test.html:

```<code>{% extends "base.html" %}
{% load staticfiles %}
{% block content %}
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
<script src="http://code.highcharts.com/highcharts.js"></script>
<!--<script src="{% static "js/jquery.min.js" %}"></script>-->
<!--<script src="{% static "js/highcharts.js" %}"></script>-->
</head>
<body>
<script type="text/javascript">
$(function () {
$('#chart_container').highcharts({
chart: {
type: 'bar'
},
title: {
text: 'Monthly Sales'
},
xAxis: {
categories: ['Jan','Feb','Mar','Apr']
},
yAxis: {
title: {
text: 'numbers'
}
},
series: [{
name: 'John',
data: [1, 0, 4]
}, {
name: 'King',
data: [5, 7, 3]
}]
});
});
</script>
<div id="chart_container" style="height: 300px"></div>
</body>
</html>
{% endblock %}
</code>```

view:

```<code>def chart_test(request):
     return render(request,'mbr/chart_test.html')
</code>```

答:
It solved by placing line jquery-3.2.0.js beginning  of base.html file</p>

```<code><!DOCTYPE html>
{% load staticfiles %}
<html>
<head>
  {% block title %}<title>mbr page </title>{% endblock %}
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <link href="{% static "mbr/css/boostrap-fluid-adj.css" %}" rel="stylesheet">
  <link href="{% static "mbr/css/bootstrap.min.css" %}" rel="stylesheet" media="screen">
  <link href="{% static "mbr/css/bootstrap-responsive.css" %}" rel="stylesheet">
 <script src="{% static 'mbr/js/jquery-3.2.0.js' %}"></script>

  <style>
  body {
    padding-top: 50px;
  }
  @media (max-width: 980px) {
    body {
      padding-top: 0;
    }
  }
</style>
</head

<body>
<div class="navbar navbar-inverse navbar-fixed-top">
   <div class="navbar-inner">
       <div class="container-fluid">
           <button type="button" class="btn btn-navbar" data-toggle="collapse" data-target=".nav-collapse">
               <span class="icon-bar"></span>
               <span class="icon-bar"></span>
               <span class="icon-bar"></span>
           </button>

           <div class="nav-collapse collapse">
               <ul class="nav pull-right">
                    <li><a href="/admin/">Login</a></li>
               </ul>
               <ul class="nav navbar-nav">
                    <li class="active"><a href="/mbr/">Home</a></li>
                    <li><a href="{% url 'search_form' %}">Search s</a></li>
                    <li><a href="{% url 'results_list' %}">Results History</a></li>
                    <li><a href="{% url 'chart_test' %}">Statistics</a></li>
               </ul>
           </div>
       </div>
   </div>
</div>
<div class="container-fluid">
    <div class="row-fluid">
        <div class="span3">
             <div class="well sidebar-nav">
              <h3> Name</h3>
              <p class="active"><a href="/mbr/4/">TEST1</a></p>
              <p><a href="/mbr/3/">TEST2</a></p>
              <p><a href="/mbr/2/">TEST3</a></p>
              <p><a href="/mbr/1/">TEST4</a></p>
             </div>
        </div>
        <div class="span9">
            {% block content %}
            {% endblock %}
        </div>
    </div>
</div>

<hr>
<script src="{% static 'mbr/js/bootstrap.min.js' %}"></script>
</body>
</html>
</code>```

Body:
I am having problem with displaying highchart in django. I am using twitter bootstrap.Chart is not showing in chart.html. Can anyone help me what I am doing wrong here?Please find below version of django

Django==1.8.7

django-highcharts==0.1.7

base.html:

<!DOCTYPE html>
{% load staticfiles %}

  {% block title %}<title>mbr page </title>{% endblock %}
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <link href="{% static "mbr/css/boostrap-fluid-adj.css" %}" rel="stylesheet">
  <link href="{% static "mbr/css/bootstrap.min.css" %}" rel="stylesheet" media="screen">
  <link href="{% static "mbr/css/bootstrap-responsive.css" %}" rel="stylesheet">

</head

           <button type="button" class="btn btn-navbar" data-toggle="collapse" data-target=".nav-collapse">

           </button>

Login

Home

Search s

Results History

Statistics

 Name

TEST1

TEST2

TEST3

TEST4

            {% block content %}
            {% endblock %}

chart_test.html:

{% extends "base.html" %}
{% load staticfiles %}
{% block content %}

{% endblock %}

view:

def chart_test(request):
     return render(request,'mbr/chart_test.html')

Body:
It solved by placing line jquery-3.2.0.js beginning  of base.html file

<!DOCTYPE html>
{% load staticfiles %}
<html>
<head>
  {% block title %}<title>mbr page </title>{% endblock %}
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <link href="{% static "mbr/css/boostrap-fluid-adj.css" %}" rel="stylesheet">
  <link href="{% static "mbr/css/bootstrap.min.css" %}" rel="stylesheet" media="screen">
  <link href="{% static "mbr/css/bootstrap-responsive.css" %}" rel="stylesheet">
 <script src="{% static 'mbr/js/jquery-3.2.0.js' %}"></script>

  <style>
  body {
    padding-top: 50px;
  }
  @media (max-width: 980px) {
    body {
      padding-top: 0;
    }
  }
</style>
</head

<body>
<div class="navbar navbar-inverse navbar-fixed-top">
   <div class="navbar-inner">
       <div class="container-fluid">
           <button type="button" class="btn btn-navbar" data-toggle="collapse" data-target=".nav-collapse">
               <span class="icon-bar"></span>
               <span class="icon-bar"></span>
               <span class="icon-bar"></span>
           </button>

           <div class="nav-collapse collapse">
               <ul class="nav pull-right">
                    <li><a href="/admin/">Login</a></li>
               </ul>
               <ul class="nav navbar-nav">
                    <li class="active"><a href="/mbr/">Home</a></li>
                    <li><a href="{% url 'search_form' %}">Search s</a></li>
                    <li><a href="{% url 'results_list' %}">Results History</a></li>
                    <li><a href="{% url 'chart_test' %}">Statistics</a></li>
               </ul>
           </div>
       </div>
   </div>
</div>
<div class="container-fluid">
    <div class="row-fluid">
        <div class="span3">
             <div class="well sidebar-nav">
              <h3> Name</h3>
              <p class="active"><a href="/mbr/4/">TEST1</a></p>
              <p><a href="/mbr/3/">TEST2</a></p>
              <p><a href="/mbr/2/">TEST3</a></p>
              <p><a href="/mbr/1/">TEST4</a></p>
             </div>
        </div>
        <div class="span9">
            {% block content %}
            {% endblock %}
        </div>
    </div>
</div>

<hr>
<script src="{% static 'mbr/js/bootstrap.min.js' %}"></script>
</body>
</html>


问:
What could be the reason for the error? Please see detail showing image of error

I am keep getting this error while uploading..I have no idea what this error are and how to resolve them...my build was successful(there are some warnings) my application is tested on iOS 4.1...any help is highly appreciated.
Thanks

答:
I had this issue as well and was able to get around it by using Fink.
Basically, the issue was that Application Loader.app was expecting to find servlet.jar in my classpath & by not finding it, was throwing a Java error.  I tried with both the iOS 4.1 version of Xcode & Application Loader.app and the iOS 4.2 versions.

Solution:

Download fink & install.

fire up Terminal.app

fink install jakarta-servletapi

quit Terminal.app & relaunch it (it should automatically update your shell)

cd /Developer/Applications/Utilities/Application Loader.app/Contents/MacOS/ (assuming you have installed the dev tools to the standard location)

./Application\ Loader

smile

This is what worked for me, hope it helps?  You can probably achieve the same thing using other tools (such as DarwinPorts?), but I have chosen Fink given that's what I first picked years ago...  :)


问:
How to set null if relations doesn't exist?
In Model I have:

```<code>public function publisher()
{
    return $this->belongsTo('App\User', 'user_id', 'id');
}
</code>```

In template blade I try to show data User:

```<code>@foreach($announcement->offers as $key => $item)
    <img src="{{url($item->publisher->photo)}}">
@endforeach
</code>```

The Problem is that if there is no data in the User table, the program crashes because I can not get the property $item->publisher->photo.

How to fix it?

答:
You can do something like this:</p>

```<code>@if (empty($item->publisher))
    It's empty
@else
    <img src="{{ url($item->publisher->photo) }}">
@endif
</code>```

Body:
In Model I have:

public function publisher()
{
    return $this->belongsTo('App\User', 'user_id', 'id');
}

In template blade I try to show data User:

@foreach($announcement->offers as $key => $item)
    publisher->photo)}}">
@endforeach

The Problem is that if there is no data in the User table, the program crashes because I can not get the property $item->publisher->photo.

How to fix it?

Body:
You can do something like this:

@if (empty($item->publisher))
    It's empty
@else
    <img src="{{ url($item->publisher->photo) }}">
@endif


问:
c# ListView cross thread, delegate not working
Trying to make a cross thread log to ListView

```<code>private enum LogType {Info, Error, Warning};
private delegate void AddItemCallback(string line, LogType lt);

private void LogAddInfo(string line, LogType lt)
{

    if (lvLog.InvokeRequired)
    {
        AddItemCallback d = new AddItemCallback(LogAddInfo);
        this.Invoke(d, new { line, lt }); // <-- here is the problem
    }
    else
    {
        // code that adds item to listView (in this case $o)
        lvLog.Items.Add(new ListViewItem(DateTime.Now.ToString(" HH:mm:ss ") + line, (int)lt));
    }

}
</code>```

This will give a parameter count mismatch. How to declare the new object properly?
Thank you in advance,

答:
You need to change this line:

```<code>this.Invoke(d, new { line, lt }); // <-- here is the problem
</code>```

To:

```<code>this.Invoke(d, new object[] { line, lt });

// or

this.Invoke(d, line, lt);
</code>```

Your version will create an anonymous class with 2 properties and will be passed as one parameter. Thats why the parameter mismatch.

You'll have to pass it as an array of objects or two separated parameters.

A usefull tip. Cross-threading modifying controls (with invoke) could slack up your thread code. The problem is, that foreach callback an invoke is made. A better way is to store the info in a queue and use a timer to process the queue.

For example:

```<code>private class LogMessage
{
    public DateTime CreatedOn {get;} = DateTime.Now;
    public string Line {get;set;}
    public LogType LogType {get; set;}
}

private List<LogMessage> _logQueue = new List<LogMessage>();

private void LogAddInfo(string line, LogType lt)
{
    lock(_logQueue)
        _logQueue.Add(new LogMessage { Line = line, LogType = lt });
}

private void Timer1_tick(object sender, EventArgs e)
{
    LogMessage[] messages;

    lock(_logQueue)
    {
        messages = _logQueue.ToArray();
        _logQueue.Clear();
    }

    foreach(var msg in messages)
    {
        // add to listview
    }
}
</code>```

It will run much better due to less hui updates.

Body:
Trying to make a cross thread log to ListView

private enum LogType {Info, Error, Warning};
private delegate void AddItemCallback(string line, LogType lt);

private void LogAddInfo(string line, LogType lt)
{

    if (lvLog.InvokeRequired)
    {
        AddItemCallback d = new AddItemCallback(LogAddInfo);
        this.Invoke(d, new { line, lt }); // <-- here is the problem
    }
    else
    {
        // code that adds item to listView (in this case $o)
        lvLog.Items.Add(new ListViewItem(DateTime.Now.ToString(" HH:mm:ss ") + line, (int)lt));
    }

}

This will give a parameter count mismatch. How to declare the new object properly?
Thank you in advance,

Body:
You need to change this line:

this.Invoke(d, new { line, lt }); // <-- here is the problem

To:

this.Invoke(d, new object[] { line, lt });

// or

this.Invoke(d, line, lt);

Your version will create an anonymous class with 2 properties and will be passed as one parameter. Thats why the parameter mismatch.

You'll have to pass it as an array of objects or two separated parameters.

A usefull tip. Cross-threading modifying controls (with invoke) could slack up your thread code. The problem is, that foreach callback an invoke is made. A better way is to store the info in a queue and use a timer to process the queue.

For example:

private class LogMessage
{
    public DateTime CreatedOn {get;} = DateTime.Now;
    public string Line {get;set;}
    public LogType LogType {get; set;}
}

private List<LogMessage> _logQueue = new List<LogMessage>();

private void LogAddInfo(string line, LogType lt)
{
    lock(_logQueue)
        _logQueue.Add(new LogMessage { Line = line, LogType = lt });
}

private void Timer1_tick(object sender, EventArgs e)
{
    LogMessage[] messages;

    lock(_logQueue)
    {
        messages = _logQueue.ToArray();
        _logQueue.Clear();
    }

    foreach(var msg in messages)
    {
        // add to listview
    }
}

It will run much better due to less hui updates.


问:
Mongodb - search by Date only using c#
m using poco like this

```<code>public class Log
    {
        public ObjectId Id { get; set; }
        [BsonDateTimeOptions(Kind = DateTimeKind.Local)]
        public DateTime DateTime { get; set; }
        public LogLevel Level { get; set; }
        [BsonIgnoreIfNull]
        public TraceLogEntity Exception { get; set; }
    }
</code>```

and then to get values from Mongo m using

```<code>var filter = Builders<Log>.Filter.Empty;
 filter &= Builders<Log>.Filter.Where(l => l.DateTime.Equals(DateTime.Now.ToShortDateString()));
var collection = _context.Log.Find(filter).Limit(100).ToList();
</code>```

i dont know why i get object reference not to set to instance of an object
if i comment datetime check then every thing works

can some one help me how to fix the issue

Stack Trace

```<code>at MongoDB.Bson.Serialization.IBsonSerializerExtensions.Serialize(IBsonSerializer serializer, BsonSerializationContext context, Object value)
   at MongoDB.Bson.Serialization.IBsonSerializerExtensions.ToBsonValue(IBsonSerializer serializer, Object value)
   at MongoDB.Driver.Linq.Translators.PredicateTranslator.TranslateComparison(Expression variableExpression, ExpressionType operatorType, ConstantExpression constantExpression)
   at MongoDB.Driver.Linq.Translators.PredicateTranslator.TranslateEquals(MethodCallExpression methodCallExpression)
   at MongoDB.Driver.Linq.Translators.PredicateTranslator.TranslateMethodCall(MethodCallExpression methodCallExpression)
   at MongoDB.Driver.Linq.Translators.PredicateTranslator.Translate(Expression node)
   at MongoDB.Driver.Linq.Translators.PredicateTranslator.Translate(Expression node, IBsonSerializerRegistry serializerRegistry)
   at MongoDB.Driver.Linq.Translators.PredicateTranslator.Translate[TDocument](Expression`1 predicate, IBsonSerializer`1 parameterSerializer, IBsonSerializerRegistry serializerRegistry)
   at MongoDB.Driver.ExpressionFilterDefinition`1.Render(IBsonSerializer`1 documentSerializer, IBsonSerializerRegistry serializerRegistry)
   at MongoDB.Driver.MongoCollectionImpl`1.CreateFindOperation[TProjection](FilterDefinition`1 filter, FindOptions`2 options)
   at MongoDB.Driver.MongoCollectionImpl`1.FindSync[TProjection](FilterDefinition`1 filter, FindOptions`2 options, CancellationToken cancellationToken)
   at MongoDB.Driver.FindFluent`2.ToCursor(CancellationToken cancellationToken)
   at MongoDB.Driver.IAsyncCursorSourceExtensions.ToList[TDocument](IAsyncCursorSource`1 source, CancellationToken cancellationToken)
</code>```

value saved in DB

答:
There seems to be bug around implicit casting and null reference in 2.4.2. Both the bugs are fixed in 2.4.3

https://jira.mongodb.org/browse/CSHARP-1922 & https://jira.mongodb.org/browse/CSHARP-1894

Btw I should note you are trying to compare string date with date type which is valid in expression and C# driver takes care of casting it to date.

You've couple of options.

Upgrade to 2.4.3

Other option is to use date types. Both variants below should work fine in 2.4.2.

```<code>filter &= Builders<Log>.Filter.Where(l => l.DateTime.Equals(DateTime.Now));

filter &= Builders<Log>.Filter.Eq(l => l.DateTime, DateTime.Now);
</code>```

Title: Mongodb - search by Date only using c#

Body:
m using poco like this

public class Log
    {
        public ObjectId Id { get; set; }
        [BsonDateTimeOptions(Kind = DateTimeKind.Local)]
        public DateTime DateTime { get; set; }
        public LogLevel Level { get; set; }
        [BsonIgnoreIfNull]
        public TraceLogEntity Exception { get; set; }
    }

and then to get values from Mongo m using

var filter = Builders<Log>.Filter.Empty;
 filter &= Builders<Log>.Filter.Where(l => l.DateTime.Equals(DateTime.Now.ToShortDateString()));
var collection = _context.Log.Find(filter).Limit(100).ToList();

i dont know why i get object reference not to set to instance of an object
if i comment datetime check then every thing works

can some one help me how to fix the issue

Stack Trace

at MongoDB.Bson.Serialization.IBsonSerializerExtensions.Serialize(IBsonSerializer serializer, BsonSerializationContext context, Object value)
   at MongoDB.Bson.Serialization.IBsonSerializerExtensions.ToBsonValue(IBsonSerializer serializer, Object value)
   at MongoDB.Driver.Linq.Translators.PredicateTranslator.TranslateComparison(Expression variableExpression, ExpressionType operatorType, ConstantExpression constantExpression)
   at MongoDB.Driver.Linq.Translators.PredicateTranslator.TranslateEquals(MethodCallExpression methodCallExpression)
   at MongoDB.Driver.Linq.Translators.PredicateTranslator.TranslateMethodCall(MethodCallExpression methodCallExpression)
   at MongoDB.Driver.Linq.Translators.PredicateTranslator.Translate(Expression node)
   at MongoDB.Driver.Linq.Translators.PredicateTranslator.Translate(Expression node, IBsonSerializerRegistry serializerRegistry)
   at MongoDB.Driver.Linq.Translators.PredicateTranslator.Translate[TDocument](Expression`1 predicate, IBsonSerializer`1 parameterSerializer, IBsonSerializerRegistry serializerRegistry)
   at MongoDB.Driver.ExpressionFilterDefinition`1.Render(IBsonSerializer`1 documentSerializer, IBsonSerializerRegistry serializerRegistry)
   at MongoDB.Driver.MongoCollectionImpl`1.CreateFindOperation[TProjection](FilterDefinition`1 filter, FindOptions`2 options)
   at MongoDB.Driver.MongoCollectionImpl`1.FindSync[TProjection](FilterDefinition`1 filter, FindOptions`2 options, CancellationToken cancellationToken)
   at MongoDB.Driver.FindFluent`2.ToCursor(CancellationToken cancellationToken)
   at MongoDB.Driver.IAsyncCursorSourceExtensions.ToList[TDocument](IAsyncCursorSource`1 source, CancellationToken cancellationToken)

value saved in DB

Body:
There seems to be bug around implicit casting and null reference in 2.4.2. Both the bugs are fixed in 2.4.3

https://jira.mongodb.org/browse/CSHARP-1922 & https://jira.mongodb.org/browse/CSHARP-1894

Btw I should note you are trying to compare string date with date type which is valid in expression and C# driver takes care of casting it to date.

You've couple of options.

Upgrade to 2.4.3

Other option is to use date types. Both variants below should work fine in 2.4.2.

filter &= Builders<Log>.Filter.Where(l => l.DateTime.Equals(DateTime.Now));

filter &= Builders<Log>.Filter.Eq(l => l.DateTime, DateTime.Now);


问:
Remove Dollar Sign from Entire Python Pandas Dataframe
I'm looking to remove dollar signs from an entire python pandas dataframe. It's similar to this post:

Remove Entire Character

However, I'm looking to remove the dollar sign which is not working. I believe it's because regex sees the dollar sign as the end of the string, but I'm not sure what to do about it. Here is what I have created so far:

```<code>dftest = pd.DataFrame({'A':[1,2,3],
                       'B':[4,5,6],
                       'C':['f;','$d:','sda%;sd$'],
                       'D':['s%','d;','d;p$'],
                       'E':[5,3,6],
                       'F':[7,4,3]})
</code>```

Which gives the output:

```<code>In [155]: dftest
Out[155]:
   A  B         C     D  E  F
0  1  4        f;    s%  5  7
1  2  5       $d:    d;  3  4
2  3  6  sda%;sd$  d;p$  6  3
</code>```

I then try to remove the dollar signs as follows:

```<code>colstocheck = dftest.columns

dftest[colstocheck] = dftest[colstocheck].replace({'$':''}, regex = True)
</code>```

That does not remove the dollar signs but this code does remove the percent signs:

```<code>dftest[colstocheck] = dftest[colstocheck].replace({'%':''}, regex = True)
</code>```

So I'm not sure how to replace the dollar signs.

答:
You need escape $ by \:

```<code>dftest[colstocheck] = dftest[colstocheck].replace({'\$':''}, regex = True)
print (dftest)
   A  B        C    D  E  F
0  1  4       f;   s%  5  7
1  2  5       d:   d;  3  4
2  3  6  sda%;sd  d;p  6  3
</code>```

Body:
I'm looking to remove dollar signs from an entire python pandas dataframe. It's similar to this post:

Remove Entire Character

However, I'm looking to remove the dollar sign which is not working. I believe it's because regex sees the dollar sign as the end of the string, but I'm not sure what to do about it. Here is what I have created so far:

dftest = pd.DataFrame({'A':[1,2,3],
                       'B':[4,5,6],
                       'C':['f;','$d:','sda%;sd$'],
                       'D':['s%','d;','d;p$'],
                       'E':[5,3,6],
                       'F':[7,4,3]})

Which gives the output:

In [155]: dftest
Out[155]:
   A  B         C     D  E  F
0  1  4        f;    s%  5  7
1  2  5       $d:    d;  3  4
2  3  6  sda%;sd$  d;p$  6  3

I then try to remove the dollar signs as follows:

colstocheck = dftest.columns

dftest[colstocheck] = dftest[colstocheck].replace({'$':''}, regex = True)

That does not remove the dollar signs but this code does remove the percent signs:

dftest[colstocheck] = dftest[colstocheck].replace({'%':''}, regex = True)

So I'm not sure how to replace the dollar signs.

Body:
You need escape $ by \:

dftest[colstocheck] = dftest[colstocheck].replace({'\$':''}, regex = True)
print (dftest)
   A  B        C    D  E  F
0  1  4       f;   s%  5  7
1  2  5       d:   d;  3  4
2  3  6  sda%;sd  d;p  6  3


问:
I am stuck at practice python exercise 4
```<code>number = int(raw_input("Enter a number :"))
div = range(0, number)
list = []
while div <= number:
    if number % div == 0:
        list.append(div)
        div =+ 1

    print list
</code>```

this is my code which I made for this exercise :
 http://www.practicepython.org/exercise/2014/02/26/04-divisors.html
 I am new to programming so i dont know what is wrong with my code but its not giving any output.

答:
I guess this answer is simple enough, and looking from the down-votes people think this too. However... one only learns by asking!

There are three essential mistakes in the code that you propose, and a number of ways to make it more Pythonic.

First, and foremost, dividing by zero is not possible! So you'd want to check numbers in the range (1-number).

Based on the indentation list is printed many times, instead of only at the end of completing the while loop.

You want to avoid using list as a variable because it is a Python keyword.

Then, to make it more Pythonic my proposition is the following:

```<code>number = int(input("Enter a number :"))
output = []

for i in range(1,number+1):
  if not number%i:
    output.append(i)

print(output)
</code>```

Note that raw_input no longer exists in Python 3.x. Also note that this way we avoid the while loop, that from experience, can easily lead to mistakes. In stead it has been replaced by automatically looping through the entries in the list generated by range(1,number).

Finally a note on range but probably also on semantics. I consider number also to be a divisor of number. To do so I have used range(1,number+1). Because, for example range(5) returns a list up to 5: [0,1,2,3,4]. I.e. it does not include 5.

Body:
number = int(raw_input("Enter a number :"))
div = range(0, number)
list = []
while div <= number:
    if number % div == 0:
        list.append(div)
        div =+ 1

    print list

this is my code which I made for this exercise :
 http://www.practicepython.org/exercise/2014/02/26/04-divisors.html
 I am new to programming so i dont know what is wrong with my code but its not giving any output.

Body:
I guess this answer is simple enough, and looking from the down-votes people think this too. However... one only learns by asking!

There are three essential mistakes in the code that you propose, and a number of ways to make it more Pythonic.

First, and foremost, dividing by zero is not possible! So you'd want to check numbers in the range (1-number).

Based on the indentation list is printed many times, instead of only at the end of completing the while loop.

You want to avoid using list as a variable because it is a Python keyword.

Then, to make it more Pythonic my proposition is the following:

number = int(input("Enter a number :"))
output = []

for i in range(1,number+1):
  if not number%i:
    output.append(i)

print(output)

Note that raw_input no longer exists in Python 3.x. Also note that this way we avoid the while loop, that from experience, can easily lead to mistakes. In stead it has been replaced by automatically looping through the entries in the list generated by range(1,number).

Finally a note on range but probably also on semantics. I consider number also to be a divisor of number. To do so I have used range(1,number+1). Because, for example range(5) returns a list up to 5: [0,1,2,3,4]. I.e. it does not include 5.


问:
Replacing an string on a field via MySQL
I have the following field (which is a string) of one of my tables:

```<code>'[{"id":"6","value":["http://www.google.com","http://www.google.com","new"]},
  {"id":"7","value":"Reuters"},
  {"id":"20","value":"2017/03/17"}]'`
</code>```

As you can see, the last part, the one with id=20 has a date on it, 2017/03/17.

Can someone tell me how can I update that field so I can get the output 2017-03-17?

My desired output after the update would be:

```<code>'[{"id":"6","value":["http://www.google.com","http://www.google.com","new"]},
 {"id":"7","value":"Reuters"},
 {"id":"20","value":"2017-03-17"}]'`
</code>```

If I use:

```<code>UPDATE mytable
SET myfield = replace(myfield , '/', '-');
</code>```

It removes the / of the links, and I want to mantain them.

PS: The ids of the fields are always the same (the one for the date is always 20 for example) the only thing that changes are the values.

答:
Maybe there is a better way, But you can :

split the string into rows using { as separator

find the row with "ID=20"

do the replace

join all rows back together using GROUP_CONCAT

DEMO

```<code>SELECT
  SUBSTRING_INDEX(SUBSTRING_INDEX(T.json, '{', numbers.n), '{', -1) name,

  CASE WHEN INSTR(SUBSTRING_INDEX(SUBSTRING_INDEX(T.json, '{', numbers.n), '{', -1), '"id":"20"') > 0
       THEN REPLACE(SUBSTRING_INDEX(SUBSTRING_INDEX(T.json, '{', numbers.n), '{', -1), '/', '-')
       ELSE SUBSTRING_INDEX(SUBSTRING_INDEX(T.json, '{', numbers.n), '{', -1)
  END as result

FROM
  (select 1 n union all
   select 2 union all select 3 union all
   select 4 union all select 5) numbers
JOIN (
        SELECT '[{"id":"6","value":["http://www.google.com","http://www.google.com","new"]},
          {"id":"7","value":"Reuters"},
          {"id":"20","value":"2017/03/17"}]' as json
    ) T
  on CHAR_LENGTH(T.json)
     -CHAR_LENGTH(REPLACE(T.json, '{', ''))>=numbers.n-1
order by
  n
</code>```

OUTPUT

OPTION 2

```<code>SELECT SUBSTRING(json, 1, pos_begin - 1 ) as side_left,
       REPLACE(SUBSTRING(json, pos_begin, pos_end - pos_begin + 1), '/', '-') as side_middle,
       SUBSTRING(json, pos_end + 1, LENGTH(json)) as side_end

FROM (
        SELECT LOCATE('{"id":"20"', json) as pos_begin,
               LOCATE('}', json, LOCATE('{"id":"20"', json)) as pos_end,
               T.json
        FROM   (
                SELECT '[{"id":"6","value":["http://www.google.com","http://www.google.com","new"]},
                  {"id":"7","value":"Reuters"},
                  {"id":"20","value":"2017/03/17"}]' as json
            ) T
    ) S
;
</code>```

OUTPUT

Body:
I have the following field (which is a string) of one of my tables:

'[{"id":"6","value":["http://www.google.com","http://www.google.com","new"]},
  {"id":"7","value":"Reuters"},
  {"id":"20","value":"2017/03/17"}]'`

As you can see, the last part, the one with id=20 has a date on it, 2017/03/17.

Can someone tell me how can I update that field so I can get the output 2017-03-17?

My desired output after the update would be:

'[{"id":"6","value":["http://www.google.com","http://www.google.com","new"]},
 {"id":"7","value":"Reuters"},
 {"id":"20","value":"2017-03-17"}]'`

If I use:

UPDATE mytable
SET myfield = replace(myfield , '/', '-');

It removes the / of the links, and I want to mantain them.

PS: The ids of the fields are always the same (the one for the date is always 20 for example) the only thing that changes are the values.

Body:
Maybe there is a better way, But you can :

split the string into rows using { as separator

find the row with "ID=20"

do the replace

join all rows back together using GROUP_CONCAT

DEMO

SELECT
  SUBSTRING_INDEX(SUBSTRING_INDEX(T.json, '{', numbers.n), '{', -1) name,

  CASE WHEN INSTR(SUBSTRING_INDEX(SUBSTRING_INDEX(T.json, '{', numbers.n), '{', -1), '"id":"20"') > 0
       THEN REPLACE(SUBSTRING_INDEX(SUBSTRING_INDEX(T.json, '{', numbers.n), '{', -1), '/', '-')
       ELSE SUBSTRING_INDEX(SUBSTRING_INDEX(T.json, '{', numbers.n), '{', -1)
  END as result

FROM
  (select 1 n union all
   select 2 union all select 3 union all
   select 4 union all select 5) numbers
JOIN (
        SELECT '[{"id":"6","value":["http://www.google.com","http://www.google.com","new"]},
          {"id":"7","value":"Reuters"},
          {"id":"20","value":"2017/03/17"}]' as json
    ) T
  on CHAR_LENGTH(T.json)
     -CHAR_LENGTH(REPLACE(T.json, '{', ''))>=numbers.n-1
order by
  n

OUTPUT

OPTION 2

SELECT SUBSTRING(json, 1, pos_begin - 1 ) as side_left,
       REPLACE(SUBSTRING(json, pos_begin, pos_end - pos_begin + 1), '/', '-') as side_middle,
       SUBSTRING(json, pos_end + 1, LENGTH(json)) as side_end

FROM (
        SELECT LOCATE('{"id":"20"', json) as pos_begin,
               LOCATE('}', json, LOCATE('{"id":"20"', json)) as pos_end,
               T.json
        FROM   (
                SELECT '[{"id":"6","value":["http://www.google.com","http://www.google.com","new"]},
                  {"id":"7","value":"Reuters"},
                  {"id":"20","value":"2017/03/17"}]' as json
            ) T
    ) S
;

OUTPUT


问:
Loading Selenium Page Objects Based on Browser Window Size
We are building a web application that has expandable workspaces on the sides of the page that expand and contract based on page size. when the workplace is contracted the page objects of the expanded list are not visible to be initialized when the class is called as the site is being developed in Angular 2.0

We are also building an automated test framework with Selenium with C# bindings and using the Page Object Model to run our automation. Is it possible load objects based on the window into a single page class like this

```<code>public class PageObjectClass
{
    public PageObjectClass(IwebDriver driver)
    {
        PageFactory.InitElements(driver, this)
    }

    private IWebElement anObjectVisibleWhenContracted
    //load an object that is not visible based on window size
}
</code>```

Or do I need to get the size of the window when I call the class and have separate classes based on window width in the test scripts like this?

```<code>if (driver.Manage().Window.Size.Width < 1280)
{
    someVar = new PageObjectClass(driver):
}
else
{
    someOtherVar = new exp[andedPageObjects
}
//do stuff here
</code>```

答:
If you don't want to face issues when an element is displayed but Selenium doesn't interact with it a good practice is to maximize your browser's window on setUp.

Still if you don't want to do this, Selenium scrolls to an element when you interact with it.

So, answering your question - you don't need to change the window size. When you use PageObject in C# like you shown then each element will be initialized when you address to it (click, sendKeys, etc.). Each time you address to an element it will be initialized again and Selenium must scroll to this element.

But there are some bugs that appears in some cases when an element is displayed at the edge of the page and Selenium can not scroll to it correctly. Why this happens I don't know but luckily it happens very rarely.

Body:
We are building a web application that has expandable workspaces on the sides of the page that expand and contract based on page size. when the workplace is contracted the page objects of the expanded list are not visible to be initialized when the class is called as the site is being developed in Angular 2.0

We are also building an automated test framework with Selenium with C# bindings and using the Page Object Model to run our automation. Is it possible load objects based on the window into a single page class like this

public class PageObjectClass
{
    public PageObjectClass(IwebDriver driver)
    {
        PageFactory.InitElements(driver, this)
    }

    private IWebElement anObjectVisibleWhenContracted
    //load an object that is not visible based on window size
}

Or do I need to get the size of the window when I call the class and have separate classes based on window width in the test scripts like this?

if (driver.Manage().Window.Size.Width < 1280)
{
    someVar = new PageObjectClass(driver):
}
else
{
    someOtherVar = new exp[andedPageObjects
}
//do stuff here


问:
Calling a method async does not work anymore after refactoring
In order to separate my GUI from the logic (which fetches data from a REST service), I refactored some logic into a controller.

Now, only part of the logic seems to work.

The GUI component looks like this after refactoring (I am using the JUCE framework)

```<code>#pragma once
#include "../../JuceLibraryCode/JuceHeader.h"
#include "../../GUI.Controller/includes/ProjectEntryListController.h"
#include "ProjectEntryListComponent.h"
#include "LocalProjectEntryComponent.h"

class ProjectBrowserTabComponent : public TabbedComponent
{
public:
    ProjectBrowserTabComponent();
    ~ProjectBrowserTabComponent();

private:
    ProjectEntryListComponent m_remote_proj;
    ProjectEntryListComponent m_local_proj;
    ProjectEntryListController *pelccont = new ProjectEntryListController(&m_remote_proj);
    ProjectEntryListController *pelccont2 = new ProjectEntryListController(&m_local_proj);
};
</code>```

The GUI controller looks like this:

```<code>#define BOOST_THREAD_PROVIDES_FUTURE
#include "../includes/ProjectEntryListController.h"

template<typename R>
bool isReady(std::future<R> const& f)
{
    Logger::writeToLog("check future");
    return f.wait_for(std::chrono::seconds(-1)) == std::future_status::ready;
}

ProjectEntryListController::ProjectEntryListController(ProjectEntryListComponent *comp) {
    m_comp = comp;
    requestProjects();
}

void ProjectEntryListController::requestProjects()
{
    Logger::writeToLog("requesting projects");
    projectsFuture = std::async(std::launch::async, &ProjectsController::getProjects, &pc);
    Logger::writeToLog("requested projects");
}

void ProjectEntryListController::backgroundCheckFuture()
{
    timer = new boost::asio::deadline_timer(io_service, boost::posix_time::seconds(interval_secs));
    timer->async_wait(boost::bind(&ProjectEntryListController::fetchData, this, boost::asio::placeholders::error, timer));
    ioSvcFuture = std::async(std::launch::async, static_cast<size_t(boost::asio::io_service::*)()>(&boost::asio::io_service::run), &io_service);
}

void ProjectEntryListController::initData() {
    requestProjects();
    backgroundCheckFuture();
}

void ProjectEntryListController::fetchData(const boost::system::error_code& /*e*/,
    boost::asio::deadline_timer* tmr) {
    if (isReady(projectsFuture)) {
        projects = projectsFuture.get();
        for (auto project : projects)
        {
            ProjectEntryComponent *pec = new ProjectEntryComponent(std::to_string(project.getId()), "222");
            m_comp->addListEntry(pec);
            m_comp->repaint();
        }
        Logger::writeToLog("got projs");
    }
    else {
        tmr->expires_at(tmr->expires_at() + boost::posix_time::seconds(interval_secs));
        tmr->async_wait(boost::bind(&ProjectEntryListController::fetchData, this, boost::asio::placeholders::error, tmr));
    }
}
</code>```

The requestProjects method's log messages are appearing in my console, but not the log message of the getProjects method I am calling asynchronously:

```<code>std::vector<Project> ProjectsController::getProjects() {
    std::vector<Project> result;
    if(serviceClient != nullptr) {
        try
        {
            std::this_thread::sleep_for(std::chrono::seconds());
            std::cout << "controller requested projs\n";
            result = serviceClient->getAvailableProjects();
        }
        catch (const std::exception&)
        {

        }
    }

    return result;
}
</code>```

However, when I debug into the code, the debugger (using VS 2015) also is able to step to the log message.

What am I doing wrong?

答:
Actually I solved this now.

1.) I was calling the wrong method requestProjects instead of initData

2.) I couldn't see the result because the implementation of ProjectEntryComponent::ProjectEntryComponent(std::string name, std::string version) was missing

Body:
In order to separate my GUI from the logic (which fetches data from a REST service), I refactored some logic into a controller.

Now, only part of the logic seems to work.

The GUI component looks like this after refactoring (I am using the JUCE framework)

#pragma once
#include "../../JuceLibraryCode/JuceHeader.h"
#include "../../GUI.Controller/includes/ProjectEntryListController.h"
#include "ProjectEntryListComponent.h"
#include "LocalProjectEntryComponent.h"

class ProjectBrowserTabComponent : public TabbedComponent
{
public:
    ProjectBrowserTabComponent();
    ~ProjectBrowserTabComponent();

private:
    ProjectEntryListComponent m_remote_proj;
    ProjectEntryListComponent m_local_proj;
    ProjectEntryListController *pelccont = new ProjectEntryListController(&m_remote_proj);
    ProjectEntryListController *pelccont2 = new ProjectEntryListController(&m_local_proj);
};

The GUI controller looks like this:

#define BOOST_THREAD_PROVIDES_FUTURE
#include "../includes/ProjectEntryListController.h"

template<typename R>
bool isReady(std::future<R> const& f)
{
    Logger::writeToLog("check future");
    return f.wait_for(std::chrono::seconds(-1)) == std::future_status::ready;
}

ProjectEntryListController::ProjectEntryListController(ProjectEntryListComponent *comp) {
    m_comp = comp;
    requestProjects();
}

void ProjectEntryListController::requestProjects()
{
    Logger::writeToLog("requesting projects");
    projectsFuture = std::async(std::launch::async, &ProjectsController::getProjects, &pc);
    Logger::writeToLog("requested projects");
}

void ProjectEntryListController::backgroundCheckFuture()
{
    timer = new boost::asio::deadline_timer(io_service, boost::posix_time::seconds(interval_secs));
    timer->async_wait(boost::bind(&ProjectEntryListController::fetchData, this, boost::asio::placeholders::error, timer));
    ioSvcFuture = std::async(std::launch::async, static_cast<size_t(boost::asio::io_service::*)()>(&boost::asio::io_service::run), &io_service);
}

void ProjectEntryListController::initData() {
    requestProjects();
    backgroundCheckFuture();
}

void ProjectEntryListController::fetchData(const boost::system::error_code& /*e*/,
    boost::asio::deadline_timer* tmr) {
    if (isReady(projectsFuture)) {
        projects = projectsFuture.get();
        for (auto project : projects)
        {
            ProjectEntryComponent *pec = new ProjectEntryComponent(std::to_string(project.getId()), "222");
            m_comp->addListEntry(pec);
            m_comp->repaint();
        }
        Logger::writeToLog("got projs");
    }
    else {
        tmr->expires_at(tmr->expires_at() + boost::posix_time::seconds(interval_secs));
        tmr->async_wait(boost::bind(&ProjectEntryListController::fetchData, this, boost::asio::placeholders::error, tmr));
    }
}

The requestProjects method's log messages are appearing in my console, but not the log message of the getProjects method I am calling asynchronously:

std::vector<Project> ProjectsController::getProjects() {
    std::vector<Project> result;
    if(serviceClient != nullptr) {
        try
        {
            std::this_thread::sleep_for(std::chrono::seconds());
            std::cout << "controller requested projs\n";
            result = serviceClient->getAvailableProjects();
        }
        catch (const std::exception&)
        {

        }
    }

    return result;
}

However, when I debug into the code, the debugger (using VS 2015) also is able to step to the log message.

What am I doing wrong?


问:
How to get HTML code as String from a HTML file in java?
I need to get HTML code as String from an existing HTML file? How can I do that in Java?

I tried the following, but the result was something that is not html syntax.

```<code>        File htmlFile = new File(filePath);
        StringBuilder contentBuilder = new StringBuilder();
        String str;
        try {
            BufferedReader in = new BufferedReader(new FileReader(htmlFile));
            while ((str = in.readLine()) != null) {
                contentBuilder.append(str);
            }
            in.close();
        } catch (IOException e) {
        }
        String htmlCodeAsString = contentBuilder.toString();
</code>```

答:
You can try this :</p>

```<code>StringBuilder bldr = new StringBuilder();
String str;

BufferedReader in = new BufferedReader(new FileReader("filename.html"));
while((str = in.readLine())!=null)
      bldr.append(str);

in.close();

String content = bldr.toString();
</code>```

Body:
I need to get HTML code as String from an existing HTML file? How can I do that in Java?

I tried the following, but the result was something that is not html syntax.

        File htmlFile = new File(filePath);
        StringBuilder contentBuilder = new StringBuilder();
        String str;
        try {
            BufferedReader in = new BufferedReader(new FileReader(htmlFile));
            while ((str = in.readLine()) != null) {
                contentBuilder.append(str);
            }
            in.close();
        } catch (IOException e) {
        }
        String htmlCodeAsString = contentBuilder.toString();

Body:
You can try this :

StringBuilder bldr = new StringBuilder();
String str;

BufferedReader in = new BufferedReader(new FileReader("filename.html"));
while((str = in.readLine())!=null)
      bldr.append(str);

in.close();

String content = bldr.toString();