text:
Q: Visual Studio 2015 application not running on another computer I have installed the .NET framework 4.5.2 (which my application targets). But still, the application does not run on any other computer.
When I double click, nothing happens. It runs perfectly fine on my computer.
When I click the Application Manifest file on the other computer, it says that

"DEPLOYMENT AND APPLICATION DO NOT HAVE MATCHING SECURITY ZONES".

I have followed many steps online before asking the question here, to no avail. Here are the error details:
PLATFORM VERSION INFO
Windows             : 6.2.9200.0 (Win32NT)
Common Language Runtime     : 4.0.30319.34209
System.Deployment.dll       : 4.0.30319.33440 built by: FX45W81RTMREL
clr.dll             : 4.0.30319.34209 built by: FX452RTMGDR
dfdll.dll           : 4.0.30319.33440 built by: FX45W81RTMREL
dfshim.dll          : 6.3.9600.16384 (winblue_rtm.130821-1623)

SOURCES
Deployment url          : file:///C:/Users/VAIO/Downloads/Atlas%20Booking%20Manager%20(ABM)_1_0_0_8/Atlas%20Booking%20Manager%20(ABM).application

IDENTITIES
Deployment Identity     : Atlas Booking Manager (ABM).application, Version=1.0.0.8, Culture=neutral, PublicKeyToken=1084140fe0278529, processorArchitecture=msil

APPLICATION SUMMARY
* Installable application.

ERROR SUMMARY
Below is a summary of the errors, details of these errors are listed later in the log.
* Activation of C:\Users\VAIO\Downloads\Atlas Booking Manager (ABM)_1_0_0_8\Atlas Booking Manager (ABM).application resulted in exception. Following failure messages were detected:
    + Deployment and application do not have matching security zones.

COMPONENT STORE TRANSACTION FAILURE SUMMARY
No transaction error was detected.

WARNINGS
There were no warnings during this operation.

OPERATION PROGRESS STATUS
* [4/29/2016 1:36:22 AM] : Activation of C:\Users\VAIO\Downloads\Atlas Booking Manager (ABM)_1_0_0_8\Atlas Booking Manager (ABM).application has started.
* [4/29/2016 1:36:22 AM] : Processing of deployment manifest has successfully completed.
* [4/29/2016 1:36:22 AM] : Installation of the application has started.

ERROR DETAILS
Following errors were detected during this operation.
* [4/29/2016 1:36:22 AM] System.Deployment.Application.InvalidDeploymentException (Zone)
    - Deployment and application do not have matching security zones.
    - Source: System.Deployment
    - Stack trace:
        at                     System.Deployment.Application.DownloadManager.DownloadApplicationManifest(AssemblyManifest deploymentManifest, String targetDir, Uri deploymentUri, IDownloadNotification notification, DownloadOptions options, Uri& appSourceUri, String& appManifestPath)
        at System.Deployment.Application.DownloadManager.DownloadApplicationManifest(AssemblyManifest deploymentManifest, String targetDir, Uri deploymentUri, Uri& appSourceUri, String& appManifestPath)
        at System.Deployment.Application.ApplicationActivator.DownloadApplication(SubscriptionState subState, ActivationDescription actDesc, Int64 transactionId, TempDirectory& downloadTemp)
        at System.Deployment.Application.ApplicationActivator.InstallApplication(SubscriptionState& subState, ActivationDescription actDesc)
        at System.Deployment.Application.ApplicationActivator.PerformDeploymentActivation(Uri activationUri, Boolean isShortcut, String textualSubId, String deploymentProviderUrlFromExtension, BrowserSettings browserSettings, String& errorPageUrl)
        at System.Deployment.Application.ApplicationActivator.ActivateDeploymentWorker(Object state)

COMPONENT STORE TRANSACTION DETAILS
No transaction information is available.

I am using OneClick, and have:
1) under publish, checked 'this app is available offline'
2) under security, this is a full trust app
3) under signing, checked "sign the ClickOnce manifests" and 'sign the assembley'
What am I missing? On my development computer it works fine.

A: Your file is probably blocked because you downloaded the files from the internet. Go to file properties and in the bottom of the properties screen you can unblock the file (exe) and the execute the files on your system.
MSDN blog: unblocking downloaded file

A: I found the solution. It turns out that my software was pointing to a directory which does not exist on the new computer. Silly me! I thought the directory would be created by itself. Well, thanks for your time and help guys. I hope people seeing this could get help with their project too! You can go to Event Viewer in Windows to see exactly what happened.


text:
Q: Getting the button text in Protractor I have created a custom locator to find an element with the ng-click method used. I have used it to get a reference to a button in my DOM.
this.button = element(by.ngClick('login()'));

i want to get the text that is on the button from the reference. For example if the button has "Click to Login" as the text, how can i extract that from the button reference?

A: You can call getText() on the element selector, but keep in mind it returns a promise. The promise could be fed to expect though, it would resolve it and perform the comparision:
expect(this.button.getText()).toBe('Click to Login');

If you need to use the text for anything else in your code you'll have to resolve the promise yourself:
this.button.getText().then(function (text) {
    console.log(text);
});

redpajama_set_name: RedPajamaStackExchange


text:
Q: Connection refused for SSH on Server via Docker container I have a server which is running a Docker container, and inside that container is a jupyter notebook, which has been run with the following command:
jupyter notebook --ip=0.0.0.0 --port=8882 --no-browser --allow-root

I would like to access the notebook from my laptop, but am getting some errors which I have never received before (this has worked in the past)
I initiate an SSH on my laptop by running:
ssh -N -L localhost:8888:localhost:8882 mrrecon@137.xxx.xxx.xx.

I then navigate on my laptop to localhost:8888 and it does not connect. If I look at the error messages, (using verbose -v command), I get:

A: Solved. The issue was that the the docker was engaged on a specific port and thus I needed to use that port, now the 8882 port that I was using.


text:
Q: does the following code in c produce a memory leak? I want to know if the following piece of code will produce a memory leak:
m = malloc(5);
m = NULL;

A: Yes, there is a memory leak. The 5 allocated bytes are no longer accessible as you don't have a pointer to them.
If you save the pointer, you can still use, and free, the resources
unsigned char *m = malloc(5);
if (m) {
    unsigned char *p = m;
    m = NULL; // can no longer access the memory through m
    p[2] = 1; // but p is ok
    free(p);  // p is ok to free
} else {
    fprintf(stderr, "Problem! malloc failed!\n");
    exit(EXIT_FAILURE);
}


text:
Q: maybe stupid question: If a single java app on a separate server is causing 23Gigs of Binlogs to be sent to the db replica does this mean there is 23gb of traffic (or more ) moving between the Java app (server) and the master Mysql server?
this has been bugging me.
The reason why I ask is because we have one server that is dedicated to our App.  Nothing else connects to the DB.  Our Binlogs on the master average about 23gigs per day.
does this make sense?

A: If nothing else connects to the DB look at Bytes_received from a mysql show status; query 24 hours apart.


text:
Q: What is this encoding and how do I make it readable? What is this ampersand stuff and, using C#, how do I make it readable?
"Votre message a été envoyé. Un représentant du Service &agrave";

A: That is HTML Encoded text. You can use the HttpUtility.HtmlDecode to decode the text back to its original form:
string decoded = HttpUtility.HtmlDecode(encodedString);

decoded should contain:

Votre message a été envoyé. Un
  représentant du Service à

A: See symbols.  In your particular case you have a lot of
é

entries.  It means an accented E:  É.
I'd use HtmlUtility.Decode to decode it.

A: The confusing part are HTML entities.  Basically, they start with an ampersand (&) and go to a semicolon(;).  Between them can either be text or a number.  They are used to represent characters that don't appear in the standard 7-bit ASCII character set.
If it's a text entity, like your "é", it should be easy enough to figure out.  "é" means "acute-accented e", while "à" is "grave-accented a".  Similarly, "&" is ampersand (which I had to manually insert to make this display right.)


text:
Q: settting in code a timer to run prgram. I have an application which I am running using windows scheduler every 30 minutes, I also have a config file which is a datatable called config.  I am going through each of the rows, which has a schedule column and if the time is in the 30 minute window the program should run the whole program. The time windows are 12:00:00 and 12:30:00 and so on, as can be seen I'm checking the current time and the row time as can be seen blow, how  would I make it run?
I tried the if statement below to see if it runs are the current time only and it doesn't work any ideas why this would be
TimeSpan time = DateTime.Now.TimeOfDay;

TimeSpan runningTime = DateTime.Parse(dr["scheduledTime"].ToString()).TimeOfDay;

if (time == runningTime)

A: If the time isn't exactly on the hour or half past the hour, the code in your if statement won't run, try this instead:
TimeSpan time = DateTime.Now.TimeOfDay;

TimeSpan runningTime = DateTime.Parse(dr["scheduledTime"].ToString()).TimeOfDay;

if (time >= runningTime && time <= (runningTime + new TimeSpan(0, 30, 0)))

When your program runs, DateTime.Now.TimeOfDay will contain something similar to 13:27:37, which obviously won't be equal to 13:00:00. So all you do is check that the current time is within the 30 minute window. We achieve that by checking that the current time elapsed since midnight (which is what .TimeOfDay on a DateTime gives you) is greater than or equal to the time elapsed since midnight of the TimeSpan you retrieve from your DataTable, and that it is also less than or equal to that same time slot plus 30 minutes.


text:
Q: Why the values are unable to set on edittexts in the onConfigurationChanged()? There are two different xml files in layout and layout-land for the respective modes. As I want to set the values back  in the edittexts even when orientation changed, I am using android:configChanges="orientation|keyboardHidden" in manifest file. This deactivates the execution of onCreate() method again and the present activity is not destroyed.
I have two frames in my app. First frame contains 25 edittexts and second contains 10 buttons. So in portrait mode, these frames are one after the other and in landscape mode one next to the other. To get this view according to modes, I wrote setContentView(R.layout.main); in the onConfigurationChanged() method. But my problem here is I am able to store the values that entered already in the editTexts in onConfigurationChanged(). But I am unable to set the values back to the edittexts after setting to the respective layout. Because I am getting respective layout, but with empty edittexts. The following code snippet gives overview of my problem.
public void onCreate()
{
setContentView(R.layout.main);
gridView = (GridView) findViewById(R.id.gridView1);
gridView.setAdapter(new EditTextAdapter(this)); //This creates 25 edittexts in the gridview which is in first frame.

}

public void getEditTexts()//getting the edittext objects here in the activity class
{
editText1=gridView.getChildAt(k);
...........
...........
}

public void onConfigurationChanged()
{
String s1=editText1.getText().toString();//Here I am using technique to store the values.

setContentView(R.layout.main);
gridView.setAdapter(new EditTextAdapter(this));
getEditTexts();
editText1.setText(s1);    //here is my problem. I am unable to set values back in the editText.

}

Where I am going wrong? How to set the values back like this in 25 edittexts in the present mode if they are set in previous mode. Please suggest. Here I guess the values are set in the old edittext objects itself even though the mode is changed. How to set the values in the new edittext objects? How come the values are set in old edittext objects if they are not present in the current layout? Or there is another reason for this problem?

A: I have created an alternative application for your requirement. I have not used grid view still I can add as many views as I want without XML's. The code checks the device configuration and the view size and add that many rows and columns to the layout. This is a basic example you can modify it for your requirement.
Here is a link to the code
Feel free to discuss in case there is any doubt.


text:
Q: Jquery sortable fails because it's based on cursor position I am trying to create a sortable list with jquery ui:

$( "#sortable" ).sortable({
    axis: 'Y',
    containment: 'parent',
    handle: 'span'
});
 #sortable {
     list-style-type: none;
     margin: 0;
     padding: 0;
     width: 60%;
 }
 #sortable li {
     margin-bottom: 3px;
     padding: 0.4em;
     padding-left: 1.5em;
     font-size: 1.4em;
     height: 18px;
    position: relative;
 }
 #sortable li span {
     position: absolute;
     top: 0;
     margin-left: -1.3em;
 }
<link href="//ajax.googleapis.com/ajax/libs/jqueryui/1.9.2/themes/smoothness/jquery-ui.css" rel="stylesheet"/>

Try dragging any item to the bottom. To drag an item grab arrow on it.

Item 1

Item 2

Item 3

Item 4

Unfortunately, it is not possible to drag any item to the bottom.
I believe jquery waits until the cursor that's holding the sortable item is at least half way across another item before it switches their order.
Is there a way to make this exchange of items happen only when the item being dragged is a certain percentage across another item, rather than basing it off of the cursor position?

A: $("#sortable").sortable({
    tolerance: 'pointer'
});


text:
Q: How can I pass a method name to another method and call it via a delegate variable? I have a method that contains a delegate variable that points at another class.
I want to call a method in that class via this delegate, but pass the name of the method as a string to the method containing the delegate.
How can this be done? Using reflection? Func<T>?
Edit:
I understand now that reflection may not be the best solution.
This is what I have:
private static void MethodContainingDelegate(string methodNameInOtherClassAsString)
{
        _listOfSub.ForEach(delegate(Callback callback)
        {
            //Here the first works, but I want the method to be general and
            //  therefore pass the method name as a string, not specfify it.
            callback.MethodNameInOtherClass();
            //This below is what I am trying to get to work.
             callback.MethodNameInOtherClassAsString();
          }
     });
}

So, basically, I am looking for a way to make my callback delegate "recognize" that my methodNameInOtherClassAsString is actually a method to execute in the other class.
Thanks!

A: It's very simple:
public delegate void DelegateTypeWithParam(object param);
public delegate void DelegateTypeWithoutParam();

public void MethodWithCallbackParam(DelegateTypeWithParam callback, DelegateTypeWithoutParam callback2)
{
    callback(new object());
    Console.WriteLine(callback.Method.Name);
    callback2();
    Console.WriteLine(callback2.Method.Name);
}

// must conform to the delegate spec
public void MethodWithParam(object param) { }
public void MethodWithoutParam() { }

public void PassCallback()
{
   MethodWithCallbackParam(MethodWithParam, MethodWithoutParam);
}

It doesn't matter, what class does the delegate variable point to. It can be defined in another class -- there's not much difference.
I think you could even query the name of the original method from the delegate variable itself without reflection. Every delegate has a property called Method exactly for that.

A: You can do something like this:
var mi = typeof(Foo).GetMethods().Single(x => x.Name == "Bar");
mi.Invoke(foo, null);

Where Foo is your target class, Bar is the method you want to call.
But you should note that reflection will have a great impact on your program's performance. Consider using strongly typed delegates instead.

A: Assuming you have string representation of the method name:
var methodInfo = myObject.GetType().GetMethod(myString); //<- this can throw or return null
methodInfo.Invoke(myObject, new object[n]{parm1, pram2,...paramn});

you need to add some error checking to this obviously, and should use a more specific version of GetMethod if you can.


text:
Q: SQL exception preparing query with ORMLite I am using an ORM (ORMlite) and all my calls are going well until I get the following error.

Exception in thread "main" org.h2.jdbc.JdbcSQLException: Syntax error in SQL statement "
      SELECT * FROM ""STORIES"" WHERE ""TITLE"" = 'Deepcut case leads 'NOT FOLLOWED[*]''  "; SQL statement:
      SELECT * FROM Stories WHERE title = 'Deepcut case leads 'not followed''  [42000-152]
          at org.h2.message.DbException.getJdbcSQLException(DbException.java:327)
          at org.h2.message.DbException.get(DbException.java:167)
          at org.h2.message.DbException.get(DbException.java:144)
          at org.h2.message.DbException.getSyntaxError(DbException.java:179)
          at org.h2.command.Parser.getSyntaxError(Parser.java:480)
          at org.h2.command.Parser.prepareCommand(Parser.java:229)
          at org.h2.engine.Session.prepareLocal(Session.java:426)
          at org.h2.engine.Session.prepareCommand(Session.java:374)
          at org.h2.jdbc.JdbcConnection.prepareCommand(JdbcConnection.java:1093)
          at org.h2.jdbc.JdbcPreparedStatement.(JdbcPreparedStatement.java:71)
          at org.h2.jdbc.JdbcConnection.prepareStatement(JdbcConnection.java:601)
          at com.j256.ormlite.jdbc.JdbcDatabaseConnection.compileStatement(JdbcDatabaseConnection.java:83)
          at com.j256.ormlite.stmt.mapped.MappedPreparedStmt.compile(MappedPreparedStmt.java:44)
          at com.j256.ormlite.stmt.StatementExecutor.buildIterator(StatementExecutor.java:169)
          at com.j256.ormlite.stmt.StatementExecutor.query(StatementExecutor.java:119)
          at com.j256.ormlite.dao.BaseDaoImpl.query(BaseDaoImpl.java:189)

I'm confused as to whats going wrong. I am calling the search from these lines:
// get our query builder from the DAO
QueryBuilder<Story, Integer> queryBuilder = StoryDao.queryBuilder();
// the 'title' field must be equal to title (a variable)
queryBuilder.where().eq(Story.TITLE_FIELD_NAME, title);
// prepare our sql statement
PreparedQuery<Story> preparedQuery = queryBuilder.prepare();
// query for all stories that have that title
List<Story> accountList = StoryDao.query(preparedQuery);

A:
Syntax error in SQL statement " SELECT * FROM ""STORIES"" WHERE ""TITLE""...

@bemace is correct that there seem to be quotes in the title that is screwing up the escaping of strings generated by the query.
In ORMLite, you should use the SelectArg feature which will generate a query with SQL ? arguments and then pass the string to the prepared statement directly.
See the documentation on the SelectArg.  With it, you'd do something like:
QueryBuilder<Story, Integer> queryBuilder = StoryDao.queryBuilder();
SelectArg titleArg = new SelectArg();
queryBuilder.where().eq(Story.TITLE_FIELD_NAME, titleArg);
PreparedQuery<Story> preparedQuery = queryBuilder.prepare();
titleArg.setValue(title);
List<Story> accountList = StoryDao.query(preparedQuery);

A: I'm kind of guessing but it looks like there's a problem with the value in the title field, maybe an unescaped quote mark?
I'm not familiar with ORMLite but title = 'Deepcut case leads 'not followed'' doesn't look right.  Should probably be "Deepcut case leads 'not followed'" or 'Deepcut case leads \'not followed\'' or some such.

A: The correct syntax for the statement would be:

SELECT * FROM Stories WHERE title = 'Deepcut case leads ''not followed'' ';

Note the duplicated single quotes inside the string literal.
You will need to tell your ORM layer to follow the ANSI SQL rules for literals.

A: The exception says that there is some syntactical problem with your generated SELECT statement. Can you print out the generated query? Doing that might help you pin down the exact issue here.
EDIT: Looking closely at your trace shows that string escaping is not handled properly here. Is this your own QueryBuilder? Also, as per this link, are you using SelectArg or directly setting the title?


text:
Q: Xamarin forms - How to read data from built in credit card reader in Android POS device? I'm developing an Android application using Xamarin-forms. The application must run on point of sale devices which have a built in magnetic card reader. So, how can I read data from the card and set the value in entry field?

A: Check with the manufacturer of the device to see if they or the card-reader manufacturer have an SDK you can use to get this data out.

A: If the device is based on NFC ,maybe you can try using NFC reader to read the data.
Here is a Android sample , you can try:
https://github.com/poz1/NFCForms
And here are some discussions about NFC Reader:
https://forums.xamarin.com/discussions/tagged/nfc-reader/p1


text:
Q: how to combine result of two queries in one resultset I have a table named 'rating'
it has two fields 'cab_id' and 'rating' which stores id for cabs and its rating as either 1 or 0.
I want to retrieve values as up or down as sum of counts as 1 or 0.
I used two queries as
      (SELECT count(rating) as up FROM

     `rating` WHERE cab_id=101 and rating=1 )

and
     (SELECT count(rating) as down FROM

     `rating` WHERE cab_id=101 and rating=0 )

I want to retrieve in the format of one result .
         ----------
      up          down

         ----------

       1             2

        ----------

Please lend a help here !

A: SELECT
    SUM(IF(rating=1,1,0)) up,
    SUM(IF(rating=0,1,0)) down
FROM rating
WHERE cab_id=101


text:
Q: What is the limit of a closed surface integral as the volume enclosed by the surface approaches zero? For the sake of argument, suppose we have some closed surface $S$ in a vector field $\vec{F}(x, y, z)$. Since $S$ is a closed surface, it forms the boundary of some 3D region $D$, where $D$ has some finite but non-zero volume. If we compute the surface integral of $\vec{F}$ across $S$ (dotting with the surface's normal vectors), we get the flux of $\vec{F}$ across the surface $S$.
Now, let's pick an arbitrary point, $P$, such that $P{\in}D$. Suppose that we perform a kind of uniform compression of $S$ such that all points on $S$ have their distance to $P$ reduced by a certain scaling factor $\lambda$. That is, if $P_S$ represents some general point on $S$, and $\tilde{P}_S$ represents that point after this transformation, then $\text{dist}(\tilde{P_S},P)=\frac{\text{dist}(P_S,P)}{\lambda}$. The question then is what happens to the surface integral as we let $\lambda\rightarrow\infty$. It seems reasonable to me that this limit should approach $(\nabla\cdot\vec{F})(P)$, but I cannot even figure out how one would rigorously write this limit of a scaling transformation down, notwithstanding how to go about solving it.
EDIT: I think I figured out a way to at least rigorously define the transformation I am talking about. The definition I came up with is that $T_\lambda(S)=\{\tilde{P_S}\in\mathbb{R}^3\mid{}\exists\space{}P_S\in{}S\mid{}\tilde{P_S}=\frac{1}{\lambda}P_S+\frac{\lambda-1}{\lambda}P\}$, where $P$ is a point in the region enclosed by $S$. The limit as $\lambda\rightarrow\infty$ is $P$, which makes sense. I am still working on the problem of applying the limit of this transformation to the surface integral though.


text:
Q: FFmpeg: output.mp4 which combined 4 mp4 videos cannot maintain the original frame rate Combining all 4 mp4 videos at 25fps will output 24.15fps mp4.
Even if you specify 25 with -r, it will be 24.15fps.
This is a problem because it causes a black scene to appear at the beginning of the video for a moment.
Command I used
ffmpeg -i audio.mp3 -safe 0 -f concat -i video_list.txt -vcodec copy -y -strict -2 output.mp4

Contents of video_list.txt
video_list.txt
Now, the output.mp4 is set to 25fps by using the following command.
However, this is not practical because it takes too much time to process.
ffmpeg -y -i output.mp4 -r 25 output2.mp4

I am doing it with python. Please tell me the solution to maintain the frame rate.
log
ffmpeg version 2.8.17-0ubuntu0.1 Copyright (c) 2000-2020 the FFmpeg developers
  built with gcc 5.4.0 (Ubuntu 5.4.0-6ubuntu1~16.04.12) 20160609
  configuration: --prefix=/usr --extra-version=0ubuntu0.1 --build-suffix=-ffmpeg --toolchain=hardened --libdir=/usr/lib/x86_64-linux-gnu --incdir=/usr/include/x86_64-linux-gnu --cc=cc --cxx=g++ --enable-gpl --enable-shared --disable-stripping --disable-decoder=libopenjpeg --disable-decoder=libschroedinger --enable-avresample --enable-avisynth --enable-gnutls --enable-ladspa --enable-libass --enable-libbluray --enable-libbs2b --enable-libcaca --enable-libcdio --enable-libflite --enable-libfontconfig --enable-libfreetype --enable-libfribidi --enable-libgme --enable-libgsm --enable-libmodplug --enable-libmp3lame --enable-libopenjpeg --enable-libopus --enable-libpulse --enable-librtmp --enable-libschroedinger --enable-libshine --enable-libsnappy --enable-libsoxr --enable-libspeex --enable-libssh --enable-libtheora --enable-libtwolame --enable-libvorbis --enable-libvpx --enable-libwavpack --enable-libwebp --enable-libx265 --enable-libxvid --enable-libzvbi --enable-openal --enable-opengl --enable-x11grab --enable-libdc1394 --enable-libiec61883 --enable-libzmq --enable-frei0r --enable-libx264 --enable-libopencv
  libavutil      54. 31.100 / 54. 31.100
  libavcodec     56. 60.100 / 56. 60.100
  libavformat    56. 40.101 / 56. 40.101
  libavdevice    56.  4.100 / 56.  4.100
  libavfilter     5. 40.101 /  5. 40.101
  libavresample   2.  1.  0 /  2.  1.  0
  libswscale      3.  1.101 /  3.  1.101
  libswresample   1.  2.101 /  1.  2.101
  libpostproc    53.  3.100 / 53.  3.100
Input #0, mov,mp4,m4a,3gp,3g2,mj2, from '/tmp/.../unit0000.mp4':
  Metadata:
    major_brand     : isom
    minor_version   : 512
    compatible_brands: isomiso2avc1mp41
    encoder         : Lavf58.45.100
  Duration: 00:00:00.81, start: 0.021333, bitrate: 3154 kb/s
    Stream #0:0(und): Video: h264 (High) (avc1 / 0x31637661), yuv420p, 1920x1080 [SAR 1:1 DAR 16:9], 3184 kb/s, 25 fps, 25 tbr, 12800 tbn, 50 tbc (default)
    Metadata:
      handler_name    : VideoHandler
    Stream #0:1(und): Audio: aac (LC) (mp4a / 0x6134706D), 48000 Hz, stereo, fltp, 151 kb/s (default)
    Metadata:
      handler_name    : SoundHandler
Input #1, mov,mp4,m4a,3gp,3g2,mj2, from '/tmp/.../unit0001.mp4':
  Metadata:
    major_brand     : isom
    minor_version   : 512
    compatible_brands: isomiso2avc1mp41
    encoder         : Lavf58.45.100
  Duration: 00:00:00.79, start: 0.021333, bitrate: 3034 kb/s
    Stream #1:0(und): Video: h264 (High) (avc1 / 0x31637661), yuv420p, 1920x1080 [SAR 1:1 DAR 16:9], 3004 kb/s, 25 fps, 25 tbr, 12800 tbn, 50 tbc (default)
    Metadata:
      handler_name    : VideoHandler
    Stream #1:1(und): Audio: aac (LC) (mp4a / 0x6134706D), 48000 Hz, stereo, fltp, 123 kb/s (default)
    Metadata:
      handler_name    : SoundHandler
Input #2, mov,mp4,m4a,3gp,3g2,mj2, from '/tmp/.../unit0002.mp4':
  Metadata:
    major_brand     : isom
    minor_version   : 512
    compatible_brands: isomiso2avc1mp41
    encoder         : Lavf58.45.100
  Duration: 00:00:00.90, start: 0.021333, bitrate: 4811 kb/s
    Stream #2:0(und): Video: h264 (High) (avc1 / 0x31637661), yuv420p, 1920x1080 [SAR 1:1 DAR 16:9], 4750 kb/s, 25 fps, 25 tbr, 12800 tbn, 50 tbc (default)
    Metadata:
      handler_name    : VideoHandler
    Stream #2:1(und): Audio: aac (LC) (mp4a / 0x6134706D), 48000 Hz, stereo, fltp, 127 kb/s (default)
    Metadata:
      handler_name    : SoundHandler
Input #3, mov,mp4,m4a,3gp,3g2,mj2, from '/tmp/.../unit0003.mp4':
  Metadata:
    major_brand     : isom
    minor_version   : 512
    compatible_brands: isomiso2avc1mp41
    encoder         : Lavf58.45.100
  Duration: 00:00:00.64, start: 0.021333, bitrate: 4550 kb/s
    Stream #3:0(und): Video: h264 (High) (avc1 / 0x31637661), yuv420p, 1920x1080 [SAR 1:1 DAR 16:9], 4405 kb/s, 25 fps, 25 tbr, 12800 tbn, 50 tbc (default)
    Metadata:
      handler_name    : VideoHandler
    Stream #3:1(und): Audio: aac (LC) (mp4a / 0x6134706D), 48000 Hz, stereo, fltp, 126 kb/s (default)
    Metadata:
      handler_name    : SoundHandler
At least one output file must be specified

A: Frame rate changes slightly when combining videos including audio.
ANS
muted video + audio -> combine


text:
Q: In xmonad, how to remap CapsLock to Ctrl? I'm new to xmonad, and trying to remap CapsLock to Ctrl.
I think I can do this by adding a ~/.xmonad/xmonad.hs file as suggested at this xmonad setup tutorial, and it seems that the xmonad.hs file should look something like the example given at the xmonad FAQ page.
import XMonad

main = xmonad defaultConfig
         { modMask = mod4Mask
         , terminal = "urxvt"
         }

I'm not sure exactly how the various fields there modMask, mod4Mask, terminal, and "urxvt" represent keyboard keys, or what field to use to represent my CapsLock and Ctrl keys.
How exactly do I remap my CapsLock to Ctrl?
Is there documentation somewhere describing the field associated with each key, CapsLock, Ctrl, etc.?
P.S. As a side-note this mailing list item also says something about xmonad keymay rebinding, but it does not appear to be haskell.

A: @melpomene's comment led me to seek something other than xmonad for performing the keybinding remap.
Instead I used xmodmap following the instructions described at this blog, Changing your caps lock into Ctrl in X.


text:
Q: CF.NET Smooth-Scrolling Panel -- bitblt is coming up blank I'm trying to write a panel in CF.NET that allows me to scroll the contents inside without flickering.  I thought I'd try having a WrapperPanel class that contains another panel with the actual contents.  Then I'd bitblt the contents of the interior panel to the wrapper based on the scrolling position.
But the bitblt isn't working for me.  It's just leaving the destination surface as it was, with no visible change.
Here's the relevant code:
protected override void OnPaint(PaintEventArgs e)
{
    //Generate a proper-sized bitmap
    using (Bitmap bmp = new Bitmap(ClientSize.Width, ClientSize.Height))
    {
        using (Graphics bgr = Graphics.FromImage(bmp))
        {
            //bitblt from interior panel to that bitmap
            var srcDC = GetDC(_interiorPanel.Handle);
            var bmDC = bgr.GetHdc();
            var res = BitBlt(bmDC, 0, YOffSet, Width, Height, srcDC, 0, 0, 0x00CC0020);
            System.Diagnostics.Debug.WriteLine(res);
            ReleaseDC(_interiorPanel.Handle, srcDC);
            bgr.ReleaseHdc(bmDC);
        }
        //Draw that bitmap to this panel
        e.Graphics.DrawImage(bmp, 0, 0);
    }

    base.OnPaint(e);
}

Both the GetDC() and GetHdc() calls return a value, so at least they aren't failing.  But that's about the extent of my troubleshooting knowledge with GDI+.  Can someone see what I'm doing wrong?

A: Is the interior panel invisible? off screen? or what? The only way you'll get relevant data from it's HDC is when it's been painted via the normal message pump, which is not gonna happen if it's hidden or off screen, or if you manually paint it, which you obviously aren't doing.
This is a great resource for learning about flicker free Win32: http://www.catch22.net/tuts/flicker


text:
Q: Capacitor 3 React App mediaDevices is undefined, iOS 14.5 I have a React web app that I am wrapping with Capacitor. Most things work fine, but I can't get navigator.mediaDevices or navigator.getUserMedia to be anything other than undefined. I get no popup requesting the user's permission either.
I have pulled and built the example app at https://github.com/geckse/ionic-capacitor-webrtc-camera-example, and it works on my iOS 14.5 iPhone sim - hooray! Except on closer inspection, it uses Capacitor 2 and now depreciated functionality to request camera permissions. I tried using the same (depreciated) code in my Capacitor 3 app, but even that doesn't seem to do anything. I can't seem to find any information on how to request camera access properly for the Capacitor Webview in Capacitor 3.
I have the following in my Info.plist
<dict>
  ...
  <key>NSCameraUsageDescription</key>
  <string>To scan barcodes</string>
</dict>

I have been round and round message boards and forums, combing through loads of similar but not identical issues. The common thing seems to be that none of the example apps use Capacitor 3. I'm now at a loss, hence the stack overflow question. Any help would be greatly appreciated.

A: Alrighty - I finally fixed it. Such a simple solution too, so here it is for anyone with the same issue as me:
Turns out you have to have the microphone permission description in your Info.plist as well, otherwise mediaDevices is just undefined. Presumably this is because webRTC doesn't separate access to camera and microphone, so you can't have access to either without permission for both.
I now have the following in my Info.plist and it works perfectly:
<dict>
    ...
  <key>NSCameraUsageDescription</key>
  <string>To scan barcodes</string>
  <key>NSMicrophoneUsageDescription</key>
  <string>To allow camera access for barcode scanning</string>
</dict>


text:
Q: Android SearchView disable/hide QuickSearchBox/Suggestion I don't know what i'm doing wrong.
I've already read some post here on stackoverflow and around the web, i've read the official documentation, but i can't figure out how to hide or prevent the box to expand under the searchview when i tap on it.
Look the image for a better explanation.
For the implementation i've:
searchable.xml
<searchable xmlns:android="http://schemas.android.com/apk/res/android"
android:label="@string/app_name"
android:hint="@string/search_hint"
android:includeInGlobalSearch="false"
android:searchSuggestSelection="null"/>

search_menu.xml
<menu xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:android="http://schemas.android.com/apk/res/android">
<item
    android:id="@+id/search"
    android:title="@string/search_title"
    android:icon="@drawable/ic_search"
    app:showAsAction="ifRoom|collapseActionView"
    app:actionViewClass="android.support.v7.widget.SearchView" /></menu>

AndroidManifest.xml
<meta-data
            android:name="android.app.searchable"
            android:resource="@xml/searchable">
        </meta-data>
<intent-filter
    ...
    <action android:name="android.intent.action.SEARCH" />
</intent-filter>

and the implementation of onCreateOptionsMenu like this
MenuInflater inflater = getMenuInflater();
    inflater.inflate(R.menu.search_menu, menu);
    // Associate searchable configuration with the SearchView
    SearchManager searchManager = (SearchManager) getSystemService(Context.SEARCH_SERVICE);
    final SearchView searchView = (SearchView) menu.findItem(R.id.search).getActionView();
    searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
        @Override
        public boolean onQueryTextSubmit(String query) {
            // perform query here
            query = Uri.encode(query);
            // workaround to avoid issues with some emulators and keyboard devices firing twice if a keyboard enter is used
            // see https://code.google.com/p/android/issues/detail?id=24599
            searchView.clearFocus();

            return true;
        }

        @Override
        public boolean onQueryTextChange(String newText) {
            return true;
        }
    });
    return super.onCreateOptionsMenu(menu);


text:
Q: How to follow links using chai-http I have an API that accepts an image file as input, uploads it, and returns a permanent link to the uploaded image.
Sample of returned JSON:
{ "url": "localhost:3000/public/uploads/1471759901731.jpg" }

My test, using mocha and chai-http:
it('should upload single valid picture on /pictures POST', function(done) {
  chai.request(app)
    .post('/pictures')
    .attach('picture', fs.readFileSync('test/test_data/banana.png'), 'banana.png')
    .end(function(err, res) {
      res.should.have.status(200);
      res.should.be.json;
      res.body.should.be.a('object');
      res.body.should.have.property('url');
      // should follow the url, ensure status 200
      // follow res.body.url
      done();
  });
});

How can I follow the url to ensure it is valid and returns status 200?

A: With some trial and error, I got this to work.
it('should upload single valid picture on /pictures POST', function(done) {
  chai.request(app)
    .post('/pictures')
    .attach('picture', fs.readFileSync('test/test_data/banana.png'), 'banana.png')
    .end(function(err, res) {
      res.should.have.status(200);
      res.should.be.json;
      res.body.should.be.a('object');
      res.body.should.have.property('url');

      // remove hostname from url
      var pic_url = res.body.url;
      pic_url = pic_url.split('/');
      pic_url = '/' + pic_url.splice(1).join('/');

      // follow the link
      chai.request(app)
        .get(pic_url)
        .end(function(err, res) {
          res.should.have.status(200);
          content_type = res.header['content-type'].split('/')[0];
          (content_type).should.equal('image');
          done();
        });
    });
});

But it doesn't seem to be the most elegant solution. I could not find anyone else nesting a chai.request(app) inside a chai.request(app).


text:
Q: Javascript object and getAttribute show different value Im attempting to get the value of the data-dropped attribute here. I want it to be true upon me clicking the hello text. Im logging the object and calling getAttribute() to check the value of data-dropped when the text is clicked.
The object shows the attribute as true,
whilst the getAttribute function shows it as false
Just wondered why this is?
HTML:

Hello

untitled.js:
let el = document.querySelectorAll('[data-dropped]');

el.forEach(function (item, index) {
    item.addEventListener('click', function (e) {
        console.dir(this);
        console.log(this.getAttribute('data-dropped'));
    });
});

setdroppedval.js:
let ele = document.querySelectorAll('[data-dropped]');

ele.forEach(function (item, index) {
    item.addEventListener('click', function () {
         this.setAttribute('data-dropped', 'true');
    });
});

Ive already tried changing the order of the scripts and setting the attribute in one JS file instead of separating it. Both of these solutions work.
However, i want to retain my layout of code and get the value that is actually correct in the object.
Any advice or info on why this occurs and if theres a solution would be great


text:
Q: Vite css response configuration When i'm asking a css-file this way
let xhr = new XMLHttpRequest();
xhr.open('GET', 'http://localhost:8080/test/data/tst.css?', false);
xhr.setRequestHeader("Accept","text/css,*/*")
xhr.send();
console.log(xhr.response);

Everything is ok.
#ggg{font-size: 50px;}

But when this way
let xhr = new XMLHttpRequest();
xhr.open('GET', 'http://localhost:8080/test/data/tst.css?', false);
xhr.setRequestHeader("Accept","*/*")
xhr.send();
console.log(xhr.response);

The response looks like
import { createHotContext as __vite__createHotContext } from "/@vite/client";import.meta.hot = __vite__createHotContext("/test/data/tst.css");import { updateStyle as __vite__updateStyle, removeStyle as __vite__removeStyle } from "/@vite/client"
const __vite__id = "/home/user/dev/project/front/test/data/tst.css"
const __vite__css = "#ggg{font-size: 50px;}"
__vite__updateStyle(__vite__id, __vite__css)
import.meta.hot.accept()
export default __vite__css
import.meta.hot.prune(() => __vite__removeStyle(__vite__id))

Is there a way to configure vite to respond in the second example like in the first example?

A: Because vite has two strategies on css:

*

*if a css request include text/css header, vite will inject css style code into  directly, so you get the first result.

*otherwise, vite will add a .js extension to css file, and treat it as a js, so you will see the second result.

if you want to know more details, please see source code


text:
Q: connect to mongoDB with node.js I don't get any errors but I can't connect to my local server
i used robo3T v 1.4
const mongodb = require('mongodb')
const MongoClient = mongodb.MongoClient

const connectionURL = 'mongodb://127.0.0.1:27017'
const databaseName = 'task-manager'

MongoClient.connect(connectionURL, { useNewUrlParser: true }, (error, client) => {
    if (error) {
        return console.log('Unable to connect to database!')
    }

    const db = client.db(databaseName)

    db.collection('users').insertOne({
        name: 'soheil',
        age: 27
    })
})


text:
Q: Two.js webgl is too slow for many objects I use Two.js + Vue.js to display my svg in webgl to optimize its rendering, but the render function takes longer than calling svg via Vue
I tried to use Pixi, but it doesn't have rounding at the paths
Two has this but in webgl mode because of the abundance of objects it draws for a long time and also has limitations for the clip
var two = new Two({
  type: Two.Types.webgl,
  width: 1024,
  height: 1024
})

var morph = (first, second, range) => {
  return first + (second - first) * range
}

var animate = () => {

  // elem getting from code

  // anchors1 and anchors2 are arrays for interpolation with content [{ anchors: ..., x: ..., y: ... }, ...]

  var verts = elem.vertices;

  for (var i = 0, len = verts.length; i < len; i++) {
    v = verts[i];

    v.x += morph(anchors1[i].x, anchors2[i].x, range) - v.x;
    v.y += morph(anchors1[i].y, anchors2[i].y, range) - v.y;

    c1 = anchors1[i].controls;
    c2 = anchors2[i].controls;

    v.controls.left.x += morph(c1.left.x, c2.left.x, range) - v.controls.left.x;
    v.controls.left.y += morph(c1.left.y, c2.left.y, range) - v.controls.left.y;

    v.controls.right.x += morph(c1.right.x, c2.right.x, range) - v.controls.right.x;
    v.controls.right.y += morph(c1.right.y, c2.right.y, range) - v.controls.right.y;
  }
}

// Maximum canvas size ~800px

two.appendTo(document.getElementById("testCanvas"));
two.bind('update', animate).play();

Vue.js (do not look at big functions (animate, hair and etc.), this is fixed)

Two.js


text:
Q: Installed using ClickOnce but want to uninstall so I can use another installer I have been using ClickOnce to install and update mysoftware for the past few years. I decided to switch installers to NSIS.
It isn't feasible for individual users of the software to uninstall the software and then re-install(with the NSIS installer).
I thought about adding some code in my NSIS script to delete the registry key for the application before installing the software but Microsoft highly recommends to use the Windows Installer service for uninstalls.
My questions are 1.What is the danger of installing without uninstalling the previous version? and 2.is there a way(using NSIS or through another means) to programatically uninstall the previously installed version before installing the current version?

A: The typical consequence of not removing the per-user click once installation(s) is that the user might be confused by two versions of the program.  For example this could be two different office addins active.
I did some searching on the silent uninstall question and I'm not sure if ClickOnce ever supported this or not.  I did find some open source projects that reported to being able to do this.  Implementing them into an ActiveSetup style pattern to get it to run in each user context would seem to handle getting rid of the old versions.


text:
Q: SQLKata - Nested queries - How can i write the code for my query in using sqlkata for sqlserver in c#? How can i write the code for the below query in using sqlkata for sqlserver in c#?
SELECT [t0].Region
FROM ((select * from [dbo].Demo_ReportData )) AS [t0]
GROUP BY [t0].Region
ORDER BY [t0].Region ASC
offset 0 rows fetch next 50 rows only;

A: To use the offset fetch syntax you have to set the UseLegacyPagination to false on the SqlServerCompiler.
var compiler = new SqlServerCompiler { UseLegacyPagination = false };

var innerQuery = new Query("Demo_ReportData");
var query = new Query().From(innerQuery.As("t0"))
    .GroupBy("Region")
    .OrderBy("Region")
    .Take(50);

var result = compiler.Compile(query);
var sql = result.Sql;
var bindings = result.Bindings;


text:
Q: node.js http.connections I am looking over node.js code and can't understand some of it.  Please help me with it.
var http = require("http"),
server = http.createServer(function(req,res) {});
......
if(MaxUserCheck <1 ){
server.watcher.stop();
logmsg(level1, server.connections);
}

For the above code,
what is "watcher" and how to use it?
"server.connections"   - what is this? and how to use it?
I have seen using server module as
server.on('request', function (req,res){};
...
server.listen(52273, function(){};

and I can understand as above, but using as "server.connections" can't understand and haven't seen it use like that.
I looked up on node.js manual but doesn't explain it.(http://nodejs.org/api/)
It seems that "server.connections" returns how many clients connected to our server..(Server uses Fugue for multi clients)
where can I find the usage of "server.connections" and "server.watcher"
Thank you.

A: These two syntaxes might have been used/required in other directories.  If I export this module to a different file and say require('watcher') there , it will work.however I'm not sure what watcher is used but it could be webwatcher module.


text:
Q: put together a function pointer and a object I try to give a reference to a member function (func) to a function (Multiprotocol) and call it with an object (z) of this class.
But i have problems with the line
result = z.*f(std::forward<Args>(args)...));

I tried things like
z.(*f) (std::forward<Args>(args)...))

and
z.(*(&f)(std::forward<Args>(args)...));

But i don't knwow how to this. Can anybody help me?
class test
{
   public:
        static int func()
        {
            std::cout << "in func";
        }
 };

class MultiProtocol
{
   public:

      template<typename Function, typename... Args>
      bool functionImpl(Function f, Args&&... args)
      {
         int result = 0;
         result = z.*f(std::forward<Args>(args)...));
         return result;
      }

      private:
      test z;
};

Main is:
int main()
{
MultiProtocol rr;
rr.functionImpl(&test::func);

}

A: Nearly, it is:
(z.*f)(std::forward<Args>(args)...)

Cannot be

*

*z.(*f) (std::forward<Args>(args)...))

*z.(*(&f)(std::forward<Args>(args)...));
as we should use operator .* (or ->*).
z.*f(std::forward<Args>(args)...) would be valid if f(args...) would return int test::* (pointer on member) as it is actually z .* (f(std::forward<Args>(args)...)).


text: Q: The principle of springboot directly accessing static resources such as pictures through url Recently, it has been implemented through springboot configuration, which directly accesses static resources through url, but I have always been curious that there is a difference between this way of accessing static resources and the way of returning the stream to the front page to generate static resources. Can someone please explain?


text:
Q: This jquery plugin detects the $window scroll position, how do I tell this plugin to use an element's scroll position instead? I'm using a jQuery plugin called hcsticky it detects a window's scroll position and then applies a position:fixed to an element.
My problem is that I have an position:absolute container that scrolls instead of the window. This means that my plugin doesn't apply the fixed position to my element.
This only happens on tablets as larger dimensions use a different stylesheet and the window itself scrolls.
Right now I have the plugin setup like this:
$('#imageContent').hcSticky({
    innerSticker: $('#textContent'),
    stickTo: $('#textContent'),
    bottomEnd: -60,
    top: 60
});

Right now this detects whether the scrollTop has has reached the top of #textContent and will apply fixed to #imageContent for the height of #textContent. None of this is triggered because, I believe, the function is measuring the $window scrollTop and not the #scroller scrollTop.
Am I missing something, is there something in this plugin's options that enables this that I'm missing? here


text:
Q: Awk? Append an incremental number to each line containing a symbol I have a file of sequences.
>seqA
lakjdsflakjsdlkjals;dkjfal;kdjsfl;aksdjf;lakjsdfl;kjalsdkjf
alsdkjfalskdjf;alsdfj;alkdjsf;lakjsdf;lkajsd
>seqB
fjal;kdjsfla;kdjsflkajdslkjfaghal;sdkjg
>seqC
a;lksdjl;akjsdg;lkjsdfl;kajdsl;kgj;alkdjsg;lkajsdgl
lsdkfja;lksdjf;lakdjsf;lkajsdfl;kjal;sdkfjal;skdjak
sdkjfal;ksdjflk;ahdglkahsdl;kghalk

I'd like to add an increasing incremental number after each ">"
For example:
Output file:
>1seqA
lakjdsflakjsdlkjals;dkjfal;kdjsfl;aksdjf;lakjsdfl;kjalsdkjf
alsdkjfalskdjf;alsdfj;alkdjsf;lakjsdf;lkajsd
>2seqB
fjal;kdjsfla;kdjsflkajdslkjfaghal;sdkjg
>3seqC
a;lksdjl;akjsdg;lkjsdfl;kajdsl;kgj;alkdjsg;lkajsdgl
lsdkfja;lksdjf;lakdjsf;lkajsdfl;kjal;sdkfjal;skdjak
sdkjfal;ksdjflk;ahdglkahsdl;kghalk

So far after scouring the internet I've tried:
awk -F "i=1" '{if (/>/){print $0i++} else print}'

and it didn't do anything. What am I doing wrong?
Thanks!

A: Try:
awk '/>/{$0 = ">" ++i substr($0, 2)} 1'

For example:
$ awk '/>/{$0 = ">" ++i substr($0, 2)} 1' file
>1seqA
lakjdsflakjsdlkjals;dkjfal;kdjsfl;aksdjf;lakjsdfl;kjalsdkjf
alsdkjfalskdjf;alsdfj;alkdjsf;lakjsdf;lkajsd
>2seqB
fjal;kdjsfla;kdjsflkajdslkjfaghal;sdkjg
>3seqC
a;lksdjl;akjsdg;lkjsdfl;kajdsl;kgj;alkdjsg;lkajsdgl
lsdkfja;lksdjf;lakdjsf;lkajsdfl;kjal;sdkfjal;skdjak
sdkjfal;ksdjflk;ahdglkahsdl;kghalk

How it works

*

*/>/{$0 = ">" ++i substr($0, 2)}
This selects lines that contain >.  For those lines, we replace the line $0 with > followed by ++i (which is the value of the variable i after it has been incremented) followed by the current line starting at its second character.

*1
This is awk's shorthand for print-the-line.

A: You can try
awk '/^>/{sub(/^>/,">"++i)}1' infile

A: A slight variation:
awk -F'>' -v OFS='>' 'NF == 2 {$2 = ++count $2} 1' file

That uses ">" as the field separator, and uses the number of fields as the condition.


text:
Q: How to globally change the default date format in Python I'm coding a Python script, in which I currently use strftime when I want to display a date according to a specific format. However, the format I use is consistently always the same throughout the script, thus it feels a waste of time and a violation of the DRY principle having to explicitly call strftime(myFormat) in every print.
I'm looking for a way to define only once what the date string format used in the script is, for all strings.
I tried this:
from datetime import datetime

def format_string(self):
    return "%02d-%02d-%02d" % (self._day, self._month, self._year)
datetime.date.__str__ = format_string

which doesn't work because __str__ is read-only.

A: Say __str__ was not readonly, how would your solution work when importing datetime in all modules? You would have to define the __str__ in the beginning of each module.
To resolve that, you will probably create a base module, say "mydatetime.py", define __str__ in that module, and then do from mydatetime import datetime in all modules where you"ll print
So if we are going to have our own base module, why not just create our own class
mydatetime.py
from datetime import datetime as system_datetime, date as system_date

class date(system_date):
     def __str__(self):. # similarly for __repr__
           return "%02d-%02d-%02d" % (self._day, self._month, self._year)

class datetime(system_datetime):
     def __str__(self):. # similarly for __repr__
           return "%02d-%02d-%02d" % (self._day, self._month, self._year)

     def date(self):
           return date(self.year, self.month, self.day)

and then you can replace all from datetime import datetime with from mydatetime import datetime

A: You could define a method pretty_format_date() that you import across your codebase, and that method would contain the strftime(myFormat) to be reused.


text:
Q: Materialized view for different oracle schema results in ORA-1208 I want to create on commit materialized oracle view pointing to table from different schema within same database instance.
schema (BATCH):
CREATE TABLE "BATCH"."BATCH_CONFIG"
   (    "KEY" VARCHAR2(100 BYTE),
    "VALUE" VARCHAR2(4000 BYTE),
    "COMMENTS" VARCHAR2(4000 BYTE),
    "UPDATED_BY" VARCHAR2(25 BYTE),
    "UPDATED" TIMESTAMP (6),
     CONSTRAINT "PK_BATCH_CONFIG" PRIMARY KEY ("KEY")
   );

create materialized view log on batch_config;
grant all on batch_config to profile;

schema (PROFILE):
create materialized view mv_batch_config REFRESH FAST ON COMMIT
        as select * from BATCH.batch_config;

Got Error:
SQL Error: ORA-12018: following error encountered during code generation for "PROFILE"."MV_BATCH_CONFIG"
ORA-00942: table or view does not exist
12018. 0000 -  "following error encountered during code generation for \"%s\".\"%s\""
*Cause:    The refresh operations for the indicated materialized view could
           not be regenerated due to errors.
*Action:   Correct the problem indicated in the following error messages and
           repeat the operation.

What is the issue with ? I am able to view query by (from profile schema) select * from BATCH.batch_config

A: OK finally I got the solution.
I have to grant select on mview log also.
GRANT SELECT ON MLOG$_BATCH_CONFIG TO PROFILE;


text:
Q: Can I limit setText to within the scope of an individual fragment? In my app, I have multiple instances of the same fragment, ActivityFragment. In each fragment, there is an activity_text textview. When the fragment is added to the layout, I want to set the activity_text textview within that fragment during onCreate. However, when I try to do this, every ActivityFragment onscreen will have their activity_text textview changed.
Is there any way that I can limit setText to within the scope of an individual fragment without using unique Tags or IDs for each fragment?
Here is my ActivityFragment class:
public static class ActivityFragment extends Fragment {
    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable final ViewGroup container, Bundle savedInstanceState) {
        final View fragment1 = inflater.inflate(R.layout.activity_fragment, container, false);

        final TextView activityText = (TextView) fragment1.findViewById(R.id.activity_text);
        //Calling setText changes the activityText Textview in every fragment onscreen
        activityText.setText(text);

        return fragment1;
    }
}

Here is my MainActivity class:
public class MainActivity extends FragmentActivity {
    Static String text;

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

        for (int i = 0; i != 5; i++) {
            //This ensures each fragment receives a unique String
            text = "success" + i;
            ActivityFragment myFragment = new ActivityFragment();
            getFragmentManager().beginTransaction()
                    .add(R.id.fragment_container, myFragment).commit();
        }
    }
}

A: It looks like there's two problems with your code.
The first is that you're using a static String text to transmit information from your Activity to your Fragments. In general, this is not a good idea; if you need to "pass" something from your Activity to your Fragment at the time it's constructed, you should use Fragment.setArguments(Bundle) to do that.
The second is that you seem to have a misconception about the timing of FragmentTransactions. Your for loop changes the value of text and then .commit()s a new fragment five times. But these transactions are asynchronous, and the fragment lifecycle has its own timeline. So your onCreateView() will actually wind up being called after your activity onCreate() has finished, and so each of your five fragments gets the same value from text.
Here's how I'd solve it:
public class MainActivity extends AppCompatActivity {

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

        for (int i = 0; i != 5; i++) {
            Bundle args = new Bundle();
            args.putString("text", "success" + i);

            ActivityFragment myFragment = new ActivityFragment();
            myFragment.setArguments(args);

            getFragmentManager().beginTransaction()
                                .add(R.id.fragment_container, myFragment).commit();
        }
    }

    public static class ActivityFragment extends Fragment {
        @Nullable
        @Override
        public View onCreateView(LayoutInflater inflater, @Nullable final ViewGroup container, Bundle savedInstanceState) {
            final View fragment1 = inflater.inflate(R.layout.activity_fragment, container, false);

            final TextView activityText = (TextView) fragment1.findViewById(R.id.activity_text);
            String text = getArguments().getString("text");
            activityText.setText(text);

            return fragment1;
        }
    }
}

A: Your issue have nothing to do with the scope of the textview.
Each fragment is individually setting the textView to text, as you instructed them to do so. That happens because onCreateView gets called much latter, after all the fragment transactions happened.
On your code you put the comment: //This ensures each fragment receives a unique String, actually, there's nothing there ensuring that fragments are receiving anything. I recommend you reading what a static means in Java. On that for-loop you change the value of text 5 times in a row and the last value is "success4".
The correct way to pass parameters to a fragment is via a Bundle added calling the methong setArguments(Bundle)
I searched and this answer here https://stackoverflow.com/a/35737232/906362 shows very well explained how to do that. The gist is something like this:
    for (int i = 0; i != 5; i++) {
        ActivityFragment myFragment = new ActivityFragment();
        Bundle b = new Bundle();
        // This really ensures each fragment receives a unique String
        b.putString("text", "success" + i)
        myFragment.setArguments(b);
        getFragmentManager().beginTransaction()
                .add(R.id.fragment_container, myFragment).commit();
    }

and then to get this value on the fragment:
  TextView activityText = (TextView) fragment1.findViewById(R.id.activity_text);
  activityText.setText(getArguments().getString("text");


text:
Q: Turn OFF/ON condition related on variable I have variable ,@UseClarifiedChangeType  INT = ISNULL(CAST([Config].[fn_Configuration_Get]('LCSP_ExecChanges_UseClarifiedChangeType') AS INT), 0)
And in middle of sql I have condition AND ISNULL(CHT.ClarifiedChangeType, ECH.ChangeType) IN ('Joining', 'Promotion', 'Internal Move')
I need to use it only if @UseClarifiedChangeType is 1
How I can do this?

A: Negate the boolean
AND (
   @UseClarifiedChangeType != 1
   OR ISNULL(CHT.ClarifiedChangeType, ECH.ChangeType) IN ('Joining', 'Promotion', 'Internal Move')
)

This test will pass if either

*

*@UseClarifiedChangeType is 1 and your ISNULL(...) part is true

*@UseClarifiedChangeType is something other than 1 (in which case the IsNULL(...) part is never run)


text:
Q: apply XSL template dynamically . Template is in external xslt file and included into main xslt I have one main xslt which is cdcatalog.xsl and linked to xml file cdcatalog.xml.
I am trying to apply-templates dynamically based on the value in country. Some of the actual templates are external .xsl files.
cdcatalog.xsl
    <?xml version="1.0" encoding="UTF-8"?>
    <xsl:stylesheet version="1.0"
    xmlns:xsl="http://www.w3.org/1999/XSL/Transform">

    <xsl:include href="cdcatalog_in.xsl"/>
    <xsl:include href="cdcatalog_usa.xsl"/>
    <xsl:include href="cdcatalog_uk.xsl"/>
    <xsl:template match="/">

My CD Collection

    <xsl:apply-templates />

    </xsl:template>

    <xsl:template match="cd">

    <xsl:apply-templates select="title"/>
    <xsl:apply-templates select="artist"/>

    </xsl:template>

    <xsl:template match="title">
    Title:
    <xsl:value-of select="."/>

   </xsl:template>

   <xsl:template match="artist">
    Artist:
   <xsl:value-of select="."/>

   </xsl:template>

   </xsl:stylesheet>

cdcatalog.xml contents are as below:
    <?xml version="1.0" encoding="UTF-8"?>
    <?xml-stylesheet type="text/xsl" href="cdcatalog.xsl"?>
    <catalog>
     <cd>
       <title>Empire Burlesque</title>
       <artist>Bob Dylan</artist>
       <country>USA</country>
       <company>Columbia</company>
       <price>10.90</price>
       <year>1985</year>
    </cd>
    <cd>
       <title>Hide your heart</title>
       <artist>Bonnie Tyler</artist>
       <country>UK</country>
       <company>CBS Records</company>
       <price>9.90</price>
       <year>1988</year>
    </cd>
    <cd>
       <title>Greatest Hits</title>
       <artist>Dolly Parton</artist>
       <country>USA</country>
       <company>RCA</company>
       <price>9.90</price>
       <year>1982</year>
    </cd>
    <cd>
       <title>Still got the blues</title>
       <artist>Gary Moore</artist>
       <country>IN</country>
       <company>Virgin records</company>
       <price>10.20</price>
       <year>1990</year>
    </cd>
    </catalog>

cdcatalog_in.xsl content are as below:
 <?xml version="1.0" encoding="UTF-8"?>
 <xsl:stylesheet version="1.0"
 xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
 <xsl:template match="cd[country='IN']" name="IN" >

Country: India

 </xsl:template>
 </xsl:stylesheet>

cdcatalog_usa.xsl content are as below:
 <?xml version="1.0" encoding="UTF-8"?>
 <xsl:stylesheet version="1.0"
 xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
 <xsl:template match="cd[country='USA']" name="USA" >

Country: United States of America

 </xsl:template>
 </xsl:stylesheet>

cdcatalog_uk.xsl content are as below:
 <?xml version="1.0" encoding="UTF-8"?>
 <xsl:stylesheet version="1.0"
 xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
 <xsl:template match="cd[country='UK']" name="UK" >

Country: United Kingdom

 </xsl:template>
 </xsl:stylesheet>

Expected Output
Title : Empire Burlesque
Artist: Bob Dylan
Country: United States of America

Title : Hide your heart
Artist: Bonnie Tyler
Country: United Kingdom

Title : Greatest Hits
Artist: Dolly Parton
Country: United States of America

Title : Still got the blues
Artist: Gary Moore
Country: India

Getting below output which is incorrect
My CD Collection

Country: United States of America 2

Country: United Kingdom

Country: United States of America 2

Country: India

Thanks in Advance.
Srini

A: Problem: you have two templates matching the same node and you need to apply both.
Solution: Instead of including the external stylesheets, import them. Then use xsl:apply-imports within the local template to apply the imported one.
No modification of the external styleshets is necessary.
XSLT 1.0
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">

<xsl:import href="cdcatalog_in.xsl"/>
<xsl:import href="cdcatalog_usa.xsl"/>
<xsl:import href="cdcatalog_uk.xsl"/>

<xsl:template match="/">

My CD Collection

            <xsl:apply-templates/>

</xsl:template>

<xsl:template match="cd">

        <xsl:apply-imports />
        <xsl:apply-templates select="title"/>
        <xsl:apply-templates select="artist"/>

</xsl:template>

<xsl:template match="title">
    Title:
    <xsl:value-of select="."/>

   </xsl:template>

<xsl:template match="artist">
    Artist:
   <xsl:value-of select="."/>

</xsl:template>

</xsl:stylesheet>

Alernatively, you could use modes - but still without modifying the external stylesheets:
XSLT 1.0
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">

<xsl:include href="cdcatalog_in.xsl"/>
<xsl:include href="cdcatalog_usa.xsl"/>
<xsl:include href="cdcatalog_uk.xsl"/>

<xsl:template match="/">

My CD Collection

            <xsl:apply-templates mode="first"/>

</xsl:template>

<xsl:template match="cd" mode="first" >

        <xsl:apply-templates select="." />
        <xsl:apply-templates select="title"/>
        <xsl:apply-templates select="artist"/>

</xsl:template>

<xsl:template match="title">
    Title:
    <xsl:value-of select="."/>

   </xsl:template>

<xsl:template match="artist">
    Artist:
   <xsl:value-of select="."/>

</xsl:template>

</xsl:stylesheet>

A: Modes can be useful here. Change your included template rules to be like:
 <xsl:stylesheet version="1.0"
     xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
   <xsl:template match="cd[country='IN']" mode="country-name">

Country: India

   </xsl:template>
 </xsl:stylesheet>

and change the generic template rule to:
<xsl:template match="cd">
  <xsl:apply-templates select="." mode="country-name"/>

    <xsl:apply-templates select="title"/>
    <xsl:apply-templates select="artist"/>

</xsl:template>

A: Do you have the opportunity to change the included xslt files? If so, you could change them to match on country instead of cd. For example the cdcatalog_in.xsl file would look like this:
 <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
   <xsl:template match="cd/country[.='IN']">

Country: India

   </xsl:template>
 </xsl:stylesheet>

Then, in your main XSLT file, the template matching cd would look like this
<xsl:template match="cd">

   <xsl:apply-templates select="country"/>
   <xsl:apply-templates select="title"/>
   <xsl:apply-templates select="artist"/>

</xsl:template>

You could even add a template matching just matching country in the main XSLT too, to capture "unknown" cases
<xsl:template match="country">

Country: UNKOWN

</xsl:template>

A: In stead of using multiple xsl files for each count, all the cd elements can be  done in single xsl using template.
Here is the modified single style sheet: cdcatalog.xsl
<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">

    <xsl:template match="/">

My CD Collection

                <xsl:apply-templates />

    </xsl:template>

    <xsl:template match="cd">

            Title:
            <xsl:value-of select="./title"/>

            Artist:
            <xsl:value-of select="./artist"/>

            Country:
            <xsl:choose>
                <xsl:when test="./country = 'IN'">
                    India
                </xsl:when>
                <xsl:when test="./country = 'UK'">
                    United Kingdom
                </xsl:when>
                <xsl:when test="./country = 'USA'">
                    United States of America
                </xsl:when>
                <xsl:otherwise>
                    <xsl:value-of select="./country"/>
                </xsl:otherwise>
            </xsl:choose>

    </xsl:template>

</xsl:stylesheet>

And here is the output:

Hope this works for your need.


text:
Q: How to write Swift Protocol methods in Objective C I have a file Slider.swift  and there is protocol defined with Class Parameter. i want to write that methods in Objective C in header file. how to Pass class as parameter in Protocols.
Please help
public protocol SliderDelegate: class {
    func slider(slider: Slider, textWithValue value: Double) -> String

    func sliderDidTap(slider: Slider)
    func slider(slider: Slider, didChangeValue value: Double)
    func slider(slider: Slider, didUpdateFocusInContext context: UIFocusUpdateContext, withAnimationCoordinator coordinator: UIFocusAnimationCoordinator) }

public extension SliderDelegate {
    func slider(slider: Slider, textWithValue value: Double) -> String { return "\(Int(value))" }

    func sliderDidTap(slider: Slider) {}
    func slider(slider: Slider, didChangeValue value: Double) {}
    func slider(slider: Slider, didUpdateFocusInContext context: UIFocusUpdateContext, withAnimationCoordinator coordinator: UIFocusAnimationCoordinator) {} }

@IBDesignable public class Slider: UIView {

}


text:
Q: how to change Add operator to custom function op2 in solve function of sympy? Update:
>>> solve([A(x)*A(y) + A(-1), A(x) + A(-2)], x, y)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 12, in __mul__
TypeError: unbound method __multiplyFunction__() must be called with A instance
as first argument (got Symbol instance instead)

class A:
    @staticmethod
    def __additionFunction__(a1, a2):
        return a1*a2 #Put what you want instead of this
    def __multiplyFunction__(a1, a2):
        return a1*a2+a1 #Put what you want instead of this
    def __init__(self, value):
        self.value = value
    def __add__(self, other):
        return self.__class__.__additionFunction__(self.value, other.value)
    def __mul__(self, other):
        return self.__class__.__multiplyFunction__(self.value, other.value)

solve([A(x)*A(y) + A(-1), A(x) + A(-2)], x, y)

update2:
>>> ss([x*y + -1, x-2], x, y)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: solve instance has no __call__ method

 class AA:
    @staticmethod
    def __additionFunction__(a1, a2):
        return a1*a2 #Put what you want instead of this
    def __multiplyFunction__(a1, a2):
        return a1*a2+a1 #Put what you want instead of this
    def __init__(self, value):
        self.value = value
    def __add__(self, other):
        return self.__class__.__additionFunction__(self.value, other.value)
    def __mul__(self, other):
        return self.__class__.__multiplyFunction__(self.value, other.value)

ss = solve(AA)
ss([x*y + -1, x-2], x, y)

would like to change Add operator to custom function op2 in solve function
and then this solve([x*y - 1, x + 2], x, y)
during solve, the parameters also change Add to custom function op2
error because i do not know how to inject op2 as ast tree to be used by ast tree
>>> class ChangeAddToMultiply(ast.NodeTransformer, ast2.NodeTransformer):
...     """Wraps all integers in a call to Integer()"""
...     def visit_BinOp(self, node):
...         print(dir(node))
...         print(dir(node.left))
...         if isinstance(node.op, ast.Add):
...             ast.Call(Name(id="op2", ctx=ast2.Load()), [node.left, node.right
], [])
...         return node
...
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'ast2' is not defined
>>>
>>> code = inspect.getsourcelines(solve)
>>> tree = ast.parse(code)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "C:\Python27\lib\ast.py", line 37, in parse
    return compile(source, filename, mode, PyCF_ONLY_AST)
TypeError: expected a readable buffer object
>>> tree2 = ast.parse("def op2(a,b): return a*b+a")
>>> tree = ChangeAddToMultiply().visit(tree,tree2)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'tree' is not defined
>>> ast.fix_missing_locations(tree)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'tree' is not defined
>>> co = compile(tree, '<ast>', "exec")
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'tree' is not defined
>>>
>>> exec(code)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: exec: arg 1 must be a string, file, or code object
>>> exec(co)

original code
import ast
from __future__ import division
from sympy import *
x, y, z, t = symbols('x y z t')
k, m, n = symbols('k m n', integer=True)
f, g, h = symbols('f g h', cls=Function)
import inspect
def op2(a,b):
    return a*b+a

class ChangeAddToMultiply(ast.NodeTransformer, ast2.NodeTransformer):
    """Wraps all integers in a call to Integer()"""
    def visit_BinOp(self, node):
        print(dir(node))
        print(dir(node.left))
        if isinstance(node.op, ast.Add):
            ast.Call(Name(id="op2", ctx=ast2.Load()), [node.left, node.right], [])
        return node

code = inspect.getsourcelines(solve([x*y - 1, x - 2], x, y))
tree = ast.parse(code)
tree2 = ast.parse("def op2(a,b): return a*b+a")
tree = ChangeAddToMultiply().visit(tree,tree2)
ast.fix_missing_locations(tree)
co = compile(tree, '<ast>', "exec")

exec(code)
exec(co)

A: I guess __add__ is what you're looking for.
class A:
    def __init__(self, value):
        self.value = value

    def __add__(self, other):
        return self.value*other.value + 4

>>> a = A(3)
>>> b = A(4)
>>> a + b
16

EDIT:
A solution to replace the + operator with a function already existing:
class A:
    @staticmethod
    def additionFunction(a1, a2):
        return a1*a2 #Put what you want instead of this

    def __init__(self, value):
        self.value = value

    def __add__(self, other):
        return self.__class__.additionFunction(self.value, other.value)

This one is a bit more tricky. In my opinion, that additionFunction is meant to belong to the A class, but there is no such thing as static methods in Python. So this function must be called from self: self.__class__.additionFunction.
To go further, one could imagine a solution using a meta-class Addable, whose constructor would take an additionFunction as parameter... But it might not be worth it.


text:
Q: Capybara + Selenium 2.0 sometimes fails to click on anchor tag It fails to click on anchor tag  (I know  is a bad practice.)
I found some answer on the internet to use fireEvent. But Selenium2.0 does not provide that function anymore, nor Capybara.
Anybody encounters the same problem?
(Now I'm trying Watir-WebDriver, which does not seem to have this problem so far. It is somewhat strange because in watir-webdriver, it uses selenium-webdriver :S)

A: Try creating a custom step like the one below and invoke it..
When /^(?:|I )follow javascript anchor "([^"]*)"$/ do |link_selector|
   page.execute_script("$('#{link_selector}').click()")
end

A: Instead of click, use SendKeys(OpenQA.Selenium.Keys.Enter)


text:
Q: How to change spinner ArrayList options to buttons? [KOTLIN] I am new in android and kotlin.
I want to change the Arraylist options that is in an spinner to buttons, I am talking about language options that is in spinner, but I don't want to be in spinner. there was nothing related article that shows something like that, I tried to change the spinner to buttons but it was showing error and App crashed! I hope my question be clear to you.
1- this is my LanguageActivity.kt :
class LanguageActivity : AppCompatActivity() {
private lateinit var databinding: ActivityLanguageBinding
private lateinit var locale: Locale
override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    databinding = DataBindingUtil.setContentView(this,R.layout.activity_language)
    val languageList = ArrayList<String>()
    languageList.add("Select")
    languageList.add("English")
    languageList.add("Persian")
    languageList.add("Pashto")
    val adapter = ArrayAdapter(this,
androidx.appcompat.R.layout.support_simple_spinner_dropdown_item, languageList)
    databinding.sLanguage.adapter = adapter
    databinding.sLanguage.onItemSelectedListener = object :
AdapterView.OnItemSelectedListener{
        override fun onItemSelected(parent: AdapterView<*>?, view: View?, position: Int, id:
Long) {
            when(position){
                0 -> {
                }
                1 -> setLocale("en")
                2 -> setLocale("fa")
                3 -> setLocale("ps")
            }
        }
        override fun onNothingSelected(parent: AdapterView<*>?) {
        }
    }
}
fun setLocale (languageName: String){
    locale = Locale(languageName)
    val res = resources
    val dm = res.displayMetrics
    val conf = res.configuration
    conf.locale = locale
    res.updateConfiguration(conf,dm)
    val refresh = Intent(this, LanguageActivity::class.java)
    startActivity(refresh)
}
}

2- and this is the activity_language.xml :
<?xml version="1.0" encoding="utf-8"?>
<layout
xmlns:android="http://schemas.android.com/apk/res/android">
<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">
    <Spinner
        android:id="@+id/sLanguage"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"/>
    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="@string/app_name"/>
</LinearLayout>
</layout>

thank you for helping me. take care.


text:
Q: Synchronous Transcription using Google Cloud Vision Optical Character Recognition (OCR) I am using the Google Cloud Vision OCR as an API for my web app. Users upload 5 files for processing but the endpoint processes them one by one.
https://cloud.google.com/vision/docs/reference/rest/v1/files/asyncBatchAnnotate
There's only documentation for asynchronous batch annotation. Any information on how I could make Google process multiple files at once without creating multiple accounts to process each document?


text:
Q: String array throws ArrayIndexOutOfBoundsException after splitting a String I am trying to develop a Web-Client based Online game using GWT.
The game mechanics work quite fine by now and I'd really like to go on with my next step in my development plan, but now I am stuck with a simple encoding/decoding function I created to store my data for the client into a string.
The steps I took are not that complicated. During runtime, my server creates "ImageStates" of the game Objects to be drawn on a Canvas on my client. Each ImageState contains a number of Layers, which contain Details of what has to be drawn where at what specific time and so on.
I tried ObjectInput/OutputStream, combined with GZip-Compression and ByteInputStreams, but I could not find any GWT implementation of the first two so I had to think about another solution and came across gwt-lzma.
My goal is to encode those details into a single string, compress it on the server, send the compressed Data to the client, decompress and decode it there so it can be "read" by the client. To do so, I created an encoding and a decoding function:
The encoder:
public static String encodeImageStateContainer(HashMap<String,HashMap<Long,ImageState>> imageStateContainer){
    StringBuilder mainStringBuilder = new StringBuilder();

    Iterator<Entry<String,HashMap<Long,ImageState>>> imageStateContainerIterator = imageStateContainer.entrySet().iterator();
    while(imageStateContainerIterator.hasNext()){
        Entry<String,HashMap<Long,ImageState>> tempImageStateManagerMetadata = imageStateContainerIterator.next();

        HashMap<Long,ImageState> tempImageStateManager = tempImageStateManagerMetadata.getValue();

        if(tempImageStateManager.size() > 0){

            if(mainStringBuilder.length() > 0){
                mainStringBuilder.append('}');  //Divisor between Image State Managers
            }

            mainStringBuilder.append(tempImageStateManagerMetadata.getKey());
            mainStringBuilder.append('|');  //Divisor between Name and following Data

            StringBuilder subOneStringBuilder = new StringBuilder();

            Iterator<Entry<Long,ImageState>> tempImageStateManagerIterator = tempImageStateManager.entrySet().iterator();
            while(tempImageStateManagerIterator.hasNext()){
                Entry<Long,ImageState> tempImageStateMetaData = tempImageStateManagerIterator.next();

                if(subOneStringBuilder.length() > 0){
                    subOneStringBuilder.append(')');    //Divisor between Image Objects
                }

                subOneStringBuilder.append(tempImageStateMetaData.getKey());
                subOneStringBuilder.append('-');    //Divisor between Object Id and Image State Data

                StringBuilder subTwoStringBuilder = new StringBuilder();
                ImageState tempImageState = tempImageStateMetaData.getValue();
                subOneStringBuilder.append(tempImageState.getFirstFrameId());   //1. => First Frame Id
                subOneStringBuilder.append(';');    //Divisor between Image State data types
                subOneStringBuilder.append(tempImageState.getFramesPerLayer()); //2. => Total Frame Count
                subOneStringBuilder.append(';');
                subOneStringBuilder.append(tempImageState.getMinumimScaleFactor()); //3. => Minimum Scale Factor
                subOneStringBuilder.append(';');

                ImageStateLayer[] tempImageStateLayers = tempImageState.getImageStateLayers();
                for(int layerId = 0; layerId < tempImageStateLayers.length; ++layerId){

                    if(subTwoStringBuilder.length() > 0){
                        subTwoStringBuilder.append('/');    //Divisor between Image State Layers
                    }

                    //Frame Arrays
                    String[] imageNativePath = tempImageStateLayers[layerId].getImageNativePath();
                    short[] offsetX = tempImageStateLayers[layerId].getOffsetX();
                    short[] offsetY = tempImageStateLayers[layerId].getOffsetY();
                    short[] orientation = tempImageStateLayers[layerId].getOrientation();

                    //Finalization Arrays
                    byte[] imagePathChange = tempImageStateLayers[layerId].getImagePathChange();
                    byte[] offsetXChange = tempImageStateLayers[layerId].getOffsetXChange();
                    byte[] offsetYChange = tempImageStateLayers[layerId].getOffsetYChange();
                    byte[] orientationChange = tempImageStateLayers[layerId].getOrientationChange();

                    //Image Path Data
                    StringBuilder subThreeStrignBuilder = new StringBuilder();
                    for(int imagePathId = 0; imagePathId < imageNativePath.length; ++imagePathId){

                        if(subThreeStrignBuilder.length() > 0){
                            subThreeStrignBuilder.append('#');  //Divisor between Frame Data Sets
                        }

                        subThreeStrignBuilder.append(imageNativePath[imagePathId]);
                        subThreeStrignBuilder.append(',');  //Divisor between Frame Data Set Data
                        subThreeStrignBuilder.append(imagePathChange[imagePathId]);
                    }

                    subTwoStringBuilder.append(subThreeStrignBuilder.toString());
                    subTwoStringBuilder.append('[');    //Divisor between Frame Data Types

                    //OffsetX Data
                    subThreeStrignBuilder = new StringBuilder();
                    for(int offsetXId = 0; offsetXId < offsetX.length; ++offsetXId){

                        if(subThreeStrignBuilder.length() > 0){
                            subThreeStrignBuilder.append('#');  //Divisor between Frame Data Sets
                        }

                        subThreeStrignBuilder.append(offsetX[offsetXId]);
                        subThreeStrignBuilder.append(',');  //Divisor between Frame Data Set Data
                        subThreeStrignBuilder.append(offsetXChange[offsetXId]);
                    }

                    subTwoStringBuilder.append(subThreeStrignBuilder.toString());
                    subTwoStringBuilder.append('[');    //Divisor between Frame Data Types

                    //OffsetY Data
                    subThreeStrignBuilder = new StringBuilder();
                    for(int offsetYId = 0; offsetYId < offsetY.length; ++offsetYId){

                        if(subThreeStrignBuilder.length() > 0){
                            subThreeStrignBuilder.append('#');  //Divisor between Frame Data Sets
                        }

                        subThreeStrignBuilder.append(offsetY[offsetYId]);
                        subThreeStrignBuilder.append(',');  //Divisor between Frame Data Set Data
                        subThreeStrignBuilder.append(offsetYChange[offsetYId]);
                    }

                    subTwoStringBuilder.append(subThreeStrignBuilder.toString());
                    subTwoStringBuilder.append('[');    //Divisor between Frame Data Types

                    //Orientation Data
                    subThreeStrignBuilder = new StringBuilder();
                    for(int orientationId = 0; orientationId < orientation.length; ++orientationId){

                        if(subThreeStrignBuilder.length() > 0){
                            subThreeStrignBuilder.append('#');  //Divisor between Frame Data Sets
                        }

                        subThreeStrignBuilder.append(orientation[orientationId]);
                        subThreeStrignBuilder.append(',');  //Divisor between Frame Data Set Data
                        subThreeStrignBuilder.append(orientationChange[orientationId]);
                    }

                    subTwoStringBuilder.append(subThreeStrignBuilder.toString());

                }
                subOneStringBuilder.append(subTwoStringBuilder.toString());
            }
            mainStringBuilder.append(subOneStringBuilder.toString());
        }
    }

    return mainStringBuilder.toString();
}

The decoder:
public static HashMap<String,HashMap<Long,ImageState>> decodeImageStateContainer(String data){

    String[] imageStateManagerArray = data.split("\\}");
    HashMap<String,HashMap<Long,ImageState>> imageStateManagerContainer = new HashMap<String,HashMap<Long,ImageState>>(imageStateManagerArray.length);

    for(int managerId = 0; managerId < imageStateManagerArray.length; ++managerId){
        String[] tempImageStateData = imageStateManagerArray[managerId].split("\\|");

        HashMap<Long,ImageState> tempImageStateManager = new HashMap<Long,ImageState>();
        imageStateManagerContainer.put(tempImageStateData[0], tempImageStateManager);

        String[] tempImageStateManagerObjects = tempImageStateData[1].split("\\)");

        for(int objectId = 0; objectId < tempImageStateManagerObjects.length; ++objectId){
            String[] tempImageObjectData = tempImageStateManagerObjects[objectId].split("\\-");

            long imageObjectId = Long.parseLong(tempImageObjectData[0]);
            String[] imageStateMetaData = tempImageObjectData[1].split("\\;");
            ImageState tempImageState = new ImageState(Integer.parseInt(imageStateMetaData[1]), Integer.parseInt(imageStateMetaData[0]), Integer.parseInt(imageStateMetaData[2]));
            tempImageStateManager.put(imageObjectId, tempImageState);

            String[] tempImageStateLayerMetaData = imageStateMetaData[3].split("\\/");
            ImageStateLayer[] tempImageStateLayers = new ImageStateLayer[tempImageStateLayerMetaData.length];

            for(int layerId = 0; layerId < tempImageStateLayerMetaData.length; ++layerId){
                String[] layerElements = tempImageStateLayerMetaData[layerId].split("\\[");

                String[] imageNativePathDetails = layerElements[0].split("\\#");
                String[] offsetXDetails = layerElements[1].split("\\#");
                String[] offsetYDetails = layerElements[2].split("\\#");
                **String[] orientationDetails = layerElements[3].split("\\#");**

                //Image Path Data
                String[] imageNativePaths = new String[imageNativePathDetails.length];
                byte[] imagePathChange = new byte[imageNativePathDetails.length];
                for(int id = 0; id < imageNativePathDetails.length; ++id){
                    String[] imagePathDetailElements = imageNativePathDetails[id].split("\\,");
                    imageNativePaths[id] = imagePathDetailElements[0];
                    imagePathChange[id] = Byte.parseByte(imagePathDetailElements[1]);
                }

                //OffsetX Data
                short[] offsetX = new short[offsetXDetails.length];
                byte[] offsetXChange = new byte[offsetXDetails.length];
                for(int id = 0; id < offsetXDetails.length; ++id){
                    String[] offsetXDetailElements = offsetXDetails[id].split("\\,");
                    offsetX[id] = Short.parseShort(offsetXDetailElements[0]);
                    offsetXChange[id] = Byte.parseByte(offsetXDetailElements[1]);
                }

                //OffsetY Data
                short[] offsetY = new short[offsetYDetails.length];
                byte[] offsetYChange = new byte[offsetYDetails.length];
                for(int id = 0; id < offsetYDetails.length; ++id){
                    String[] offsetYDetailElements = offsetYDetails[id].split("\\,");
                    offsetY[id] = Short.parseShort(offsetYDetailElements[0]);
                    offsetYChange[id] = Byte.parseByte(offsetYDetailElements[1]);
                }

                //Orientation Data
                short[] orientation = new short[orientationDetails.length];
                byte[] orientationChange = new byte[orientationDetails.length];
                for(int id = 0; id < orientationDetails.length; ++id){
                    String[] orientationDetailElements = orientationDetails[id].split("\\,");
                    orientation[id] = Short.parseShort(orientationDetailElements[0]);
                    orientationChange[id] = Byte.parseByte(orientationDetailElements[1]);
                }

                //Create the Layer and Add it to the Array
                tempImageStateLayers[layerId] = new ImageStateLayer(imageNativePaths,new short[][]{offsetX,offsetY,orientation}, new byte[][]{imagePathChange,offsetXChange,offsetYChange,orientationChange});

            }

            //Connect the Reference to the layers with the Image State
            tempImageState.setImageStateLayers(tempImageStateLayers);

        }

    }

    return imageStateManagerContainer;
}

Now my problem: If I encode it on the server and decode it directly afterwards It takes about three cycles of Encoding until I get an IndexOutofBoundsException at this specific position in the decoder, the last line is the line where the error seems to be according to stacktrace:
for(int layerId = 0; layerId < tempImageStateLayerMetaData.length; ++layerId){
                String[] layerElements = tempImageStateLayerMetaData[layerId].split("\\[");

                String[] imageNativePathDetails = layerElements[0].split("\\#");
                String[] offsetXDetails = layerElements[1].split("\\#");
                String[] offsetYDetails = layerElements[2].split("\\#");
                String[] orientationDetails = layerElements[3].split("\\#");

I would not say I'm an expert, but after testing the encoder I can definitely say that the string generated by it is always valid, the string at which I get this error is complete as well. There must be something wrong with my decoding function, but I have no idea what it could be.
As I said, the first three cycles are encoded and decoded properly and the data to encode did not change dramatically. There is no way that the encoded string could lead to having a String array smaller than 4 elements. Basically, this error can't exist as far as I understand my code.
I think it could be some kind of memory allocation problem that prevents the string from being split properly, but thats just an idea of a clueless programmer.
Any help is deeply appreciated!

A: I found the solution to my problem:
While encoding, I was printing Numeric types to my string. While selecting my Seperator symbols I didn't take negative values, resulting in a '-' before the digit into consideration, which led to an uncontrolled splitting of my String when I tryed to split by '-'. I replaced the minus with another character and everything works fine now!


text:
Q: Bootstrap 3 modal backdrop is black I use bootstrap`s modal on my site and backdrop opacity is 1. I can change opacity by adding
.modal-backdrop.fade.in {
    opacity: 0.7!important;
}

in my .css file. But when I close modal, opacity changes to 1 and then closing - it's look ugly. I understood, that case in div, which appear in bottom of html document when modal is showing,

but how to remove this div? And it's occure only on product page on other pages it works fine.

A: !important should override inline styles: https://css-tricks.com/override-inline-styles-with-css/
In your example you are missing a white space though.
    .modal-backdrop.fade.in {
         opacity: 0.7 !important;
    }

Update
I assume the modal-backdrop is without the in class on close
    .modal-backdrop.fade, .modal-backdrop.fade.in {
         opacity: 0.7 !important;
    }


text:
Q: My android ui crashes when I collect values from my web server I have successfully connected my android application to my web service. I can send, collect and update detail on my webservice through my android application. But a simple problem arises, When the application is installed on an android phone. In a case when there is a slow internet network and my application takes too long to collect details from  web server my android app crashes.
Please How do I solve this problem. The class that loads the resources.
My code is pasted below.
public class GetLgsInState extends AsyncTask<String,String,String>{
    private ProgressDialog progressdialog = null;
    Context context;
    private String state = "";

    LGModel[] localgovernments = null;

    public GetLgsInState(Context context,String state){

        this.context = context;
        this.state = state;
    }

    @Override
    protected void onPreExecute(){
        super.onPreExecute();

        progressdialog = new ProgressDialog(context);
        progressdialog.setMessage("Loading the local government areas in state ...");
        progressdialog.show();
    }

    @Override
    protected String doInBackground(String... arg0) {
        // TODO Auto-generated method stub
        List<NameValuePair> args = new ArrayList<NameValuePair>();
        args.add(new BasicNameValuePair("id",state));
        JSONHttpClient jsonHttpClient = new JSONHttpClient();
        try{
           localgovernments = jsonHttpClient.Get(RestfulServiceUrl.GetLGInState, args, LGModel[].class);
        }
        catch(Exception e)
        {

            Log.i("collection failed","Could not collect");
        }

        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                if (localgovernments.length > 0) {

                    for(LGModel lg : localgovernments){
                        //HashMap<String, String> mapLG = new HashMap<String, String>();
                        //mapLG.put(LGModel.LGName,lg.getName());

                        //hospitalList.add(mapLG);

                        lgspinnerAdapter.add(lg.getName());

                        lgspinnerAdapter.notifyDataSetChanged();

                    }

                }
                else
                {
                    //Toast.makeText(context,"No local government for this state",Toast.LENGTH_LONG);
                    errorText.setText("No Local Government entered for this state");
                }
            }
        });

        return null;
    }

    @Override
    protected void onPostExecute(String s){
         progressdialog.dismiss();

    }

}

I delibrately alter the webservice so I simulate the possible error that could occur when there is network problem
09-09 18:12:05.365: D/AndroidRuntime(380): Shutting down VM
09-09 18:12:05.365: W/dalvikvm(380): threadid=1: thread exiting with uncaught exception (group=0x40015560)
09-09 18:12:05.365: E/AndroidRuntime(380): FATAL EXCEPTION: main
09-09 18:12:05.365: E/AndroidRuntime(380): java.lang.NullPointerException
09-09 18:12:05.365: E/AndroidRuntime(380):  at com.example.medicalrobot.HospitalSearchOption$GetLgsInState$1.run(HospitalSearchOption.java:203)
09-09 18:12:05.365: E/AndroidRuntime(380):  at android.os.Handler.handleCallback(Handler.java:587)
09-09 18:12:05.365: E/AndroidRuntime(380):  at android.os.Handler.dispatchMessage(Handler.java:92)
09-09 18:12:05.365: E/AndroidRuntime(380):  at android.os.Looper.loop(Looper.java:130)
09-09 18:12:05.365: E/AndroidRuntime(380):  at android.app.ActivityThread.main(ActivityThread.java:3683)
09-09 18:12:05.365: E/AndroidRuntime(380):  at java.lang.reflect.Method.invokeNative(Native Method)
09-09 18:12:05.365: E/AndroidRuntime(380):  at java.lang.reflect.Method.invoke(Method.java:507)
09-09 18:12:05.365: E/AndroidRuntime(380):  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:839)
09-09 18:12:05.365: E/AndroidRuntime(380):  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:597)
09-09 18:12:05.365: E/AndroidRuntime(380):  at dalvik.system.NativeStart.main(Native Method)
09-09 18:12:08.245: I/Process(380): Sending signal. PID: 380 SIG: 9
09-09 18:12:09.694: I/dalvikvm(409): Could not find method com.actionbarsherlock.internal.nineoldandroids.widget.NineFrameLayout.onHoverEvent, referenced from method com.actionbarsherlock.internal.widget.ActionBarContainer.onHoverEvent
09-09 18:12:09.694: W/dalvikvm(409): VFY: unable to resolve virtual method 4386: Lcom/actionbarsherlock/internal/nineoldandroids/widget/NineFrameLayout;.onHoverEvent (Landroid/view/MotionEvent;)Z
09-09 18:12:09.694: D/dalvikvm(409): VFY: replacing opcode 0x6f at 0x0000
09-09 18:12:09.694: D/dalvikvm(409): VFY: dead code 0x0003-0004 in Lcom/actionbarsherlock/internal/widget/ActionBarContainer;.onHoverEvent (Landroid/view/MotionEvent;)Z
09-09 18:12:09.715: I/dalvikvm(409): Could not find method android.widget.FrameLayout.getAlpha, referenced from method com.actionbarsherlock.internal.nineoldandroids.widget.NineFrameLayout.getAlpha
09-09 18:12:09.715: W/dalvikvm(409): VFY: unable to resolve virtual method 3088: Landroid/widget/FrameLayout;.getAlpha ()F
09-09 18:12:09.715: D/dalvikvm(409): VFY: replacing opcode 0x6f at 0x000b

A: Your variable object localgovernments may be receiving null from web-service output
check if it is null
if (localgovernments!=null){
 if (localgovernments.length > 0) {

                    for(LGModel lg : localgovernments){
                        //HashMap<String, String> mapLG = new HashMap<String, String>();
                        //mapLG.put(LGModel.LGName,lg.getName());

                        //hospitalList.add(mapLG);

                        lgspinnerAdapter.add(lg.getName());

                        lgspinnerAdapter.notifyDataSetChanged();

                    }
}