text:
Q: Can Stand Alone web2py Schedulers deployed on multiple servers (with different web2py versions) safely co-exist? Background Information for my question:
I have an unusual use-case where I am running two different (but related) applications on an old version of web2py and a newer (recent) version.
eg.
"New Server" (an EC2 Instance running with Ubuntu) which runs a web application and a stand alone scheduler related to the web application on web2py version
2.14.6-stable+timestamp.2016.05.10.00.21.47
(Running on Apache/2.4.18 (Ubuntu), Python 2.7.12)
"Old Server" (an EC2 Instance running with Ubuntu) which runs a web application and a stand alone scheduler related to the web application on web2py version
2.9.5-stable+timestamp.2014.03.16.02.35.39
(Running on Apache/2.4.7 (Ubuntu), Python 2.7.6)
Originally the two apps were co-located on the "old" server, what I have done is migrated one of the apps to a much newer server. Medium to long term the old server will be upgraded and brought into line, but for reasons of risk aversion and short term priority I require that these two distinct versions "coexist" in that they point to the same DB infrastructure (a postgres RDS instance).
These two apps have associated stand alone gluon schedulers, which when co-located on the same "old" server functioned well for over a year. After the migration of one of the scheduler processes onto the newer server, to be co-located with the associated web application, I have experienced issues with the web2py scheduler (mostly manifested in the older version). The manifested issue was typically that the older versions stand alone scheduler would stop functioning, in effect locking up.
I have found that using distinct group names for the sets of tasks associated with each stand alone scheduler was helpful in getting the system to function when done in concert with what appeared to be a required modification in the new gluon scheduler to stop it from examining the worker that "belongs" to the "old" server version. This being due to an added column in the new scheduler_worker called "worker_stats" which is not populated by the "legacy" older gluon scheduler version.
My "fix/hack" for the new behaviour is described by following diff output:

    @@ -1083,7 +1081,7 @@ class Scheduler(MetaScheduler):
    """
    sw, st, sd = db.scheduler_worker, db.scheduler_task, db.scheduler_task_deps
    now = self.now()
    -        all_workers = db((sw.status == ACTIVE) & (sw.group_names == "|myNewGroupName|")).select()
    +        all_workers = db(sw.status == ACTIVE).select()
    # build workers as dict of groups
    wkgroups = {}
         for w in all_workers:

Note: I also ensured the old scheduler was running with group_name "myOldGroupName" ... this appeared necessary to ensure no lock up (originally I defaulted the old one to "main"... but I suspect this also caused conflict
Initial Request for community feedback (possibly to be followed by further elaboration by myself and provision of technical details, pending responses and any requests for such):
Is the gluon scheduler supposed to be fully backward compatible ?
Is the gluon scheduler backward compatible when it needs to "co-exist" with another "version" in real time using the same DB tables?
Is it "safe" to mix old and new web2py versions running over the same shared DB tables ?
NOTE: I can confirm that with all actions taken so far, even if scheduling is started and runs for  few hours, it appears to eventually stall for ALL tasks, leaving no tasks able to run and ALL tasks in queued state.... as though entire scheduler mechanism is locked up over both servers stand alone scheduler instances (even though in theory the tasks and associated workers are unrelated (? or are they ?)


text:
Q: How to setup Internet gateway Windows Server 2008 by Routing and Remote Access Server has 2 NICs:
One (WAN) connected to ISP:
IPv4 Address. . . . . . . . . . . : 87.110.xxx.xx
Subnet Mask . . . . . . . . . . . : 255.255.255.240
Default Gateway . . . . . . . . . : 87.110.xxx.xx
Second (LAN) connected to switch and other LAN hosts:
IPv4 Address. . . . . . . . . . . : 192.168.20.1
Subnet Mask . . . . . . . . . . . : 255.0.0.0
Default Gateway . . . . . . . . . :
Under enabled Routing and Remote Access, through wizard configured NAT access for private interface.
However Hosts on LAN can't be ping'ed, as well RDP from server to LAN hosts not working
Any other configs necessary?
Added:
Firewall is switched off
IPv4 Route Table
Active Routes:
Network Destination        Netmask          Gateway       Interface  Metric
          0.0.0.0          0.0.0.0    87.110.xxx.xx    87.110.xxx.xx    276
    87.110.xxx.xx  255.255.255.248         On-link     87.110.xxx.xx    276
    87.110.xxx.xx  255.255.255.255         On-link     87.110.xxx.xx    276
    87.110.xxx.xx  255.255.255.255         On-link     87.110.xxx.xx    276
    87.110.xxx.xx  255.255.255.255         On-link     87.110.xxx.xx    276
        127.0.0.0        255.0.0.0         On-link         127.0.0.1    306
        127.0.0.1  255.255.255.255         On-link         127.0.0.1    306
  127.255.255.255  255.255.255.255         On-link         127.0.0.1    306
        192.0.0.0        255.0.0.0         On-link      192.168.20.1    276
     192.168.20.1  255.255.255.255         On-link      192.168.20.1    276
  192.255.255.255  255.255.255.255         On-link      192.168.20.1    276
   195.122.xxx.xx  255.255.255.240         On-link     87.110.xxx.xx    276
   195.122.xxx.xx  255.255.255.255         On-link     87.110.xxx.xx    276
        224.0.0.0        240.0.0.0         On-link         127.0.0.1    306
        224.0.0.0        240.0.0.0         On-link     87.110.xxx.xx    276
        224.0.0.0        240.0.0.0         On-link      192.168.20.1    276
  255.255.255.255  255.255.255.255         On-link         127.0.0.1    306
  255.255.255.255  255.255.255.255         On-link     87.110.xxx.xx    276
  255.255.255.255  255.255.255.255         On-link      192.168.20.1    276
Persistent Routes:
  Network Address          Netmask  Gateway Address  Metric
          0.0.0.0          0.0.0.0    87.110.180.49  Default

redpajama_set_name: RedPajamaStackExchange


text:
Q: How can I merge or convert multiple ImageMagick command into one single command a) I have multiple ImageMagick commands and I need to convert those multiple commands into one. I tried it by putting all the parameters in single command, but somehow it was not working and I had to discard it.
magick -density 300 cheque25.jpg -depth 8 -strip -background white -alpha off cheque25.png
magick convert cheque25.png -resize 150% res_cheque25.png
magick convert -brightness-contrast 10x30 res_cheque25.png b_res_cheque25.png
magick convert b_res_cheque25.png -threshold 45% bin_res_cheque25.png

b) Also, is there any chance that merged commands will give any different output than multiple single command?

A: Your ImageMagick syntax is not correct in several ways. In ImageMagick 7, you replace convert with magick. Also your input should come right after magick. ImageMagick 6 is forgiving of syntax, but ImageMagick 7 is not. See http://imagemagick.org/script/porting.php#cli
Try the following:
magick cheque25.jpg -depth 8 -strip -alpha off -background white -resize 150% -brightness-contrast 10x30 -threshold 45% -density 300 bin_res_cheque25.png

If that does not work, then provide a link to your input image, so others can test your commands and verify against mine.
The combined commands should give the same as a properly formatted set of commands, provided no syntax errors are present and settings are reset where needed and parenthesis processing is properly used when and where needed. I make no guarantees, since your set of commands is not using proper syntax.


text:
Q: Import system properties to maven plugin's Spring context I have in-house developed maven plugin(lets call it A) which uses spring IOC container and a maven project(call it B) that uses this plugin.
I want to specify particular plugin configuration in B's pom.xml, so this property will be accessed in plugin's spring context
I expect something like this,
pom.xml (project B)
<plugin>
...
 <configuration>
    <dummyproperty>dummy_value</dummyproperty>
 </configuration>
...
</plugin>

Spring_context.xml (project A - plugin)
<bean class="com.blabla.SomeClass">
 <property name="someBeanProperty" value="${dummyproperty}" />
</bean>
<bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">

I've tried various approaches with using plugin configuration, , additional property files, but placeholders in spring context not get populated with real values.
Asking for your help with this
Thanks in advance

A: I've implemented exactly the same kind of plugin. The solution was to have a Properties member in the plugin mojo, which is then configured using the usual <cofiguration> section.
The plugin mojo was responsible for loading the spring XML and creating the app context. Before using the app context, the mojo instantiated a PropertiesPlaceHolderConfigurer, setting the properties to the Properties instance configured in the mojo.
For convenience, I also had a Properties instance where the values were ignored, and instead fetched from the project. This allows properties to be conveniently set in the spring config with the same values as they were in the maven project.


text: Q: How do I locate a third party page represented as a slug in my WordPress website? how do I determine where a WordPress page is located in the admin panel when the page has been built via a third party plugin and has been uploaded to a directory that is just represented by a slug? It goes to example.com/here/ but how do I find out where the '/here/' portion is represented as a WordPress page or file in the admin panel? The page was created using a third party page creator on https://weblimitless.com/ and I can't find the page when searching the pages panel in my WordPress admin panel.


text:
Q: Reading and inserting data into a different server How to insert data into a different server
INSERT INTO   "Database2"."Schema2"."Table2"
(SELECT * FROM "Database1"."Schema1"."Table1")

If Database1 is coming from SERVER A and Database2 is SERVER B?


text:
Q: How do I rotate the Earth about the Sun with OpenGL? Please excuse my question
I spotted my misstake, and it is a dumb one. Everything is working ok. So how can I delete the question?

I can't seem to make an Earth rotate about a Sun with OpenGL and I have no idea as to why that is.
Here's a stripped down version of the (what I believe to be) relevant source code (in c++).
This is the Init() function that is called once before any other OpenGL function is called:
void Init() {

  glMatrixMode(GL_MODELVIEW);

  gluLookAt (
    0,  1, -3, // Where am I
    0,  0,  0, // Where am I looking at
    0,  1,  0  // Direction of 'my head'
  );

  // Going to Projection mode ...
  glMatrixMode(GL_PROJECTION);
  glLoadIdentity();

  // ... to set up perspective viewing.
  glFrustum   (-0.5,   0.5,
               -0.5,   0.5,
                1.0, 100.0);

  // Going back to Model view since drawing
  // is done entierly in Modelview.
  glMatrixMode(GL_MODELVIEW);
}

Then this is the Draw() function that is called repeadetly in order to "animate" the scene:
void Draw() {

  glClear(
    GL_COLOR_BUFFER_BIT |
    GL_DEPTH_BUFFER_BIT
  );

  // Draw yellow Sun
  glColor3d(1.0, 1.0, 0.0);
  sphere(radius_sun);

  // draw the path of the Earth around
  // the Sun. Assume distance Earth to Sun = 1

  glColor4d( 0.0, 0.0, 1.0, 0.5);
  glBegin(GL_LINE_LOOP);

    for (double q=0; q<=1; q+=0.01) {
      double rad = q * M_PI * 2.0;
      glVertex3d(std::cos(rad), 0, std::sin(rad));
    }

  glEnd();

  // the Earth
  glColor3d(1.0, 1.0, 1.0);

  glPushMatrix();

  // Assign a value to t dependant on the
  // time already passed.
  double t = IncreasingDouble();

  double angle = t * M_PI * 2.0;

  // Rotate scene angle degres about y-axis:
  glRotated   (angle, 0, 1, 0);

  // And then translate coordinate system
  glTranslated(1, 0, 0);

  sphere(radius_earth);

  // Restore matrix for next call
  glPopMatrix();

  // Swap Buffers and the more snipped..
}

I don't spot my mistake but the earth is moving spirally away from the sun further and further although the rest of the scene (Sun and Earth's orbit-path) are drawn correctly.

A: The problem must be elsewhere, maybe inside your sphere() method. I'm following the same steps as you, but mine works. Here's what I've got, and it's working the way you want (one sphere rotates smoothly around another) (Also, note my gluLookAt and glFrustum are different, but that should make no difference. I just do it this way so I can use my mouse to change my viewing point):
// draw the scene
void myGlutDisplay( void )
{
    glClearColor(0, 0, 0, 0);
    glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT);

    // projection transform
    glMatrixMode(GL_PROJECTION);
    glLoadIdentity();
    glFrustum(-1, 1, -1, 1, 1, 1000);

    // camera transform
    glMatrixMode(GL_MODELVIEW);
    glLoadIdentity();
    gluLookAt(eye[0], eye[1], eye[2], lookat[0], lookat[1], lookat[2], 0, 1, 0);

    //
    // draw some stuff
    //

    // Draw yellow Sun
    glColor3d(1.0, 1.0, 0.0);
    glutSolidSphere(1, 128, 128);

    glPushMatrix();
    double angle = (t+=.1) * 3.14156 * 2.0;
    glRotated(angle, 0, 1, 0);
    glTranslated(5, 0, 0);
    glutSolidSphere(1,128,128);
    glPopMatrix();

    glutSwapBuffers();
}


text:
Q: Please help solve flutter app get this problem I'm getting the following error while trying to build run the app in debug mode on android.
Looks like there is an issue with the shared preferences package launching lib\main.dart on sdk gphone x86 in debug mode...
   C:\Users\rootx\AppData\Local\Pub\Cache\hosted\pub.dartlang.org\shared_preferences-0.5.12+4\android\src\main\java\io\flutter\plugins\sharedpreferences\MethodCallHandlerImpl.java:9: warning: [deprecation] AsyncTask in android.os has been deprecated
            import android.os.AsyncTask;
C:\Users\rootx\AppData\Local\Pub\Cache\hosted\pub.dartlang.org\shared_preferences-0.5.12+4\android\src\main\java\io\flutter\plugins\sharedpreferences\MethodCallHandlerImpl.java:121: warning: [deprecation] AsyncTask in android.os has been deprecated
                new AsyncTask<Void, Void, Boolean>() {           C:\Users\rootx\AppData\Local\Pub\Cache\hosted\pub.dartlang.org\shared_preferences-0.5.12+4\android\src\main\java\io\flutter\plugins\sharedpreferences\MethodCallHandlerImpl.java:121: warning: [deprecation] AsyncTask() in AsyncTask has been deprecated
                new AsyncTask<Void, Void, Boolean>() {
                ^

            C:\Users\rootx\AppData\Local\Pub\Cache\hosted\pub.dartlang.org\shared_preferences-0.5.12+4\android\src\main\java\io\flutter\plugins\sharedpreferences\MethodCallHandlerImpl.java:123: warning: [deprecation] doInBackground(Params...) in AsyncTask has been deprecated
                  protected Boolean doInBackground(Void... voids) {
                                    ^
              where Params,Result are type-variables:
                Params extends Object declared in class AsyncTask
                Result extends Object declared in class AsyncTask
            C:\Users\rootx\AppData\Local\Pub\Cache\hosted\pub.dartlang.org\shared_preferences-0.5.12+4\android\src\main\java\io\flutter\plugins\sharedpreferences\MethodCallHandlerImpl.java:121: warning: [deprecation] AsyncTask() in AsyncTask has been deprecated
                new AsyncTask<Void, Void, Boolean>() {                                                                        C:\Users\rootx\AppData\Local\Pub\Cache\hosted\pub.dartlang.org\shared_preferences-0.5.12+4\android\src\main\java\io\flutter\plugins\sharedpreferences\MethodCallHandlerImpl.java:128: warning: [deprecation] onPostExecute(Result) in AsyncTask has been deprecated
                  protected void onPostExecute(Boolean value) {
                                 ^
              where Result is a type-variable:
                Result extends Object declared in class AsyncTask         C:\Users\rootx\AppData\Local\Pub\Cache\hosted\pub.dartlang.org\shared_preferences-0.5.12+4\android\src\main\java\io\flutter\plugins\sharedpreferences\MethodCallHandlerImpl.java:131: warning: [deprecation] execute(Params...) in AsyncTask has been deprecated
                }.execute();
                 ^
              where Params,Progress,Result are type-variables:
                Params extends Object declared in class AsyncTask
                Progress extends Object declared in class AsyncTask
                Result extends Object declared in class AsyncTask
            7 warnings

            I/flutter_petcar( 8034): Late-enabling -Xcheck:jni
            I/flutter_petcar( 8034): Unquickening 12 vdex files!
            W/flutter_petcar( 8034): Unexpected CPU variant for X86 using defaults: x86

A: Upgrade your shared preferences plugin to the latest version which is shared_preferences: ^2.0.8,
then flutter clean and flutter run again.


text:
Q: Code for Continuous week and quarter count I am creating a dashboard but I need to make the date's week and quarter continuous and automatic. Anyone hre who can help with the code?
I did try making it manually but then my client requires me to have it automatically. I am using excel vba

A: You can use my Week and Quarter functions:
' Returns the ISO 8601 week of a date.
' The related ISO year is returned by ref.
'
' 2016-01-06. Gustav Brock, Cactus Data ApS, CPH.
'
Public Function Week( _
    ByVal Date1 As Date, _
    Optional ByRef IsoYear As Integer) _
    As Integer

    Dim Month       As Integer
    Dim Interval    As String
    Dim Result      As Integer

    Interval = IntervalSetting(dtWeek)

    Month = VBA.Month(Date1)
    ' Initially, set the ISO year to the calendar year.
    IsoYear = VBA.Year(Date1)

    Result = DatePart(Interval, Date1, vbMonday, vbFirstFourDays)
    If Result = MaxWeekValue Then
        If DatePart(Interval, DateAdd(Interval, 1, Date1), vbMonday, vbFirstFourDays) = MinWeekValue Then
            ' OK. The next week is the first week of the following year.
        Else
            ' This is really the first week of the next ISO year.
            ' Correct for DatePart bug.
            Result = MinWeekValue
        End If
    End If

    ' Adjust year where week number belongs to next or previous year.
    If Month = MinMonthValue Then
        If Result >= MaxWeekValue - 1 Then
            ' This is an early date of January belonging to the last week of the previous ISO year.
            IsoYear = IsoYear - 1
        End If
    ElseIf Month = MaxMonthValue Then
        If Result = MinWeekValue Then
            ' This is a late date of December belonging to the first week of the next ISO year.
            IsoYear = IsoYear + 1
        End If
    End If

    ' IsoYear is returned by reference.
    Week = Result

End Function

' Returns the quarter of a date.
' Value is 1 for the first quarter of the year,
' 4 for the last.
'
' 2015-12-21. Gustav Brock, Cactus Data ApS, CPH.
'
Public Function Quarter( _
    ByVal Date1 As Date) _
    As Integer

    Dim Result  As Integer

    ' Find the quarter.
    Result = DatePart(IntervalSetting(DtInterval.dtQuarter), Date1)

    Quarter = Result

End Function

They both use several constants and supporting functions. Too much to post here, so please visit the full code and documentation at my project at GitHub: VBA.Date.


text:
Q: How can i get the Cell address from excel How can i get the Cell address from excel given a row and column number for example
row 2 and col 3 should return C2... Please help

A: Just an improvement, the col-- was in the wrong place
static string GetCellAddress(int row, int col)
    {
        StringBuilder sb = new StringBuilder();

       do
        {
            col--;
            sb.Insert(0, (char)('A' + (col % 26)));
            col /= 26;
        } while (col > 0);
        sb.Append(row);
        return sb.ToString();
    }

A: This one (untested) should also work with column addresses over that are over 26:
using System.Text;

public string GetCellAddress(int row, int col) {
    StringBuilder sb = new StringBuilder();
    col--;
    do {
        sb.Insert(0, (char)('A' + (col % 26)));
        col /= 26;
    } while (col > 0);
    sb.Append(row);
    return sb.ToString();
}

Corrected: the column address was backwards

A: I'm not a big user of VSTO C# - I usually opt for VBA. However, the following pair of functions might be useful for you. Unsure if they can be streamlined some more:
public string RangeAddress(Excel.Range rng)
{
    return rng.get_AddressLocal(false, false, Excel.XlReferenceStyle.xlA1,
           missing, missing);
}
public string CellAddress(Excel.Worksheet sht, int row, int col)
{
    return RangeAddress(sht.Cells[row, col]);
}

The RangeAddress will take any Excel range and throw you back the address. If you want the absolute style (with dollar signs, e.g. $C$3) then you have to change the first two parameters of the get_AddressLocal call to true, true.
To get the cell address from a row/col pair, you can use CellAddress. It does need a sheet to get the address. However, you could swap in (Excel.Worksheet)ActiveSheet if you don't want to provide a sheet (this may or may not work, depending on what you have open in your VSTO session).

A: public string GetCellAddress(int row, int col) {
        return (char)((int)'A' + (row - 1)) + col.ToString();
}

A: Cells(2, 3).Address

A: I'm using zero-based row and column index. So I had to adapt the code of prior answers to the following.
It took some trial and error to get this right for all possible addresses i.E. A1, Z2, AA2, ZZ10, ...
    public string GetAddress(int col, int row)
    {
        col++;
        StringBuilder sb = new StringBuilder();
        do
        {
            col--;
            sb.Insert(0, (char)('A' + (col % 26)));
            col /= 26;

        } while (col > 0);
        sb.Append(row + 1);
        return sb.ToString();
    }


text:
Q: Sphinx and JavaScript Documentation Workflow For my JavaScript framework I would like to use Sphinx. Since I am new in the Sphinx world I would like you people to help me out getting started with Sphinx and JavaScript.

A: I believe you're looking for Sphinx' JavaScript Domain feature.
Edit: From a quick glean at the documentation & tools, it doesn't look like you can use ReST inside your JavaScript. You'll either have to fish out the documentation from the comments, or keep it around in sidecar-files.

A: Sorry for too late response )
Like you I want build docs for my own JS framework based on AngularJS.
And like oliverseal, I am built sphinx extension in native way for sphinx and ext.autodoc
sphinxcontrib-autoanysrc
It simple and clean, but does have ext.autodoc features for auto generation signatures and others, but it enough for me store reST docs of framework API in js files )
You can implement ext.autodoc features with sphinxcontrib-autoanysrc extension check out  autoanysrc.JSAnalyzer


text:
Q: What is the proper way to update all elements of a rendered page via AJAX? I have a complicated page being rendered by PHP and would like to keep all elements of the page up to date via AJAX long polling.  Is there some kind of general / clever way to design an infrastructure to support this without having to specify manually each element to update?  Just looking for ideas.  Thanks!

A: Using jQuery, I would send a comma-separated list of jQuery selectors to update to the server. The server will ultimately respond by reading those selectors and producing the HTML to fill up the elements matching the selectors:
$.get("/updater", { elementsToUpdate: "#someDiv,#someTable,#someOtherElement"}, function(json) {
      $.each(json, function(k, v) {

        // the key is the selector, the value is the
        // HTML to set to that (or those) element(s):
        $(k).html(v);
      });
}, "json"); // we are expecting the server to return JSON

The server will respond by sending JSON to the client with the following structure:
 {"#someDiv":"this is some HTML to fill up div with ID someDiv","#someOtherElement":"here is some more HTML","#someTable":"here is some more HTML"}

A: You can poll a page which returns you the json-encoded structure of your page, like:
var page = {
    'elem1': {
        'html': '
... ',
        'update': True
    },
    'elen2': {
        'update': False

and so on, then update what necessary, having only one poll.

A: maybe add a special class to all the elements to be updated via ajax, and also you can encode extra data in some other attributes for example
test

then with jquery you can easily pull out that data and eval it, and use it in your ajax

A: Keep your pages elements structure as private data and have the public elements to update them
var page = (function(){
    var private_data = {
    //json
    };

    return {
        workOnData : function(){//process the data}

    }
})()

This is good way you can keep your pages data safe and smooth.

A: I'd use jQuery to do that if I were you o: then you could do something like...
$('div.updateThisClass').css('color','#fff')


text:
Q: Restrict .ics file from forwarding I'm able to create and send .ics files using the below code.
System.Net.Mail.MailMessage msg = new MailMessage("test@gmail.com", "test2@gmail.com");

        StringBuilder str = new StringBuilder();
        str.AppendLine("BEGIN:VCALENDAR");
        str.AppendLine("PRODID:-//Schedule a Meeting");
        str.AppendLine("VERSION:2.0");
        str.AppendLine("METHOD:REQUEST");
        str.AppendLine("BEGIN:VEVENT");
        str.AppendLine(string.Format("DTSTART:{0:yyyyMMddTHHmmssZ}", DateTime.Now.AddMinutes(+330)));
        str.AppendLine(string.Format("DTSTAMP:{0:yyyyMMddTHHmmssZ}", DateTime.UtcNow));
        str.AppendLine(string.Format("DTEND:{0:yyyyMMddTHHmmssZ}", DateTime.Now.AddMinutes(+660)));
        str.AppendLine("LOCATION: " + "abcd");
        str.AppendLine(string.Format("UID:{0}", Guid.NewGuid()));
        str.AppendLine(string.Format("DESCRIPTION:{0}", msg.Body));
        str.AppendLine(string.Format("X-ALT-DESC;FMTTYPE=text/html:{0}", msg.Body));
        str.AppendLine(string.Format("SUMMARY:{0}", msg.Subject));
        str.AppendLine(string.Format("ORGANIZER:MAILTO:{0}", msg.From.Address));

        str.AppendLine(string.Format("ATTENDEE;CN=\"{0}\";RSVP=TRUE:mailto:{1}", msg.To[0].DisplayName, msg.To[0].Address));

        str.AppendLine("BEGIN:VALARM");
        str.AppendLine("TRIGGER:-PT15M");
        str.AppendLine("ACTION:DISPLAY");
        str.AppendLine("DESCRIPTION:Reminder");
        str.AppendLine("END:VALARM");
        str.AppendLine("END:VEVENT");
        str.AppendLine("END:VCALENDAR");

        byte[] byteArray = Encoding.ASCII.GetBytes(str.ToString());
        MemoryStream stream = new MemoryStream(byteArray);

        Attachment attach = new Attachment(stream, "test.ics");

        msg.Attachments.Add(attach);

        System.Net.Mime.ContentType contype = new System.Net.Mime.ContentType("text/calendar");
        contype.Parameters.Add("method", "REQUEST");
        AlternateView avCal = AlternateView.CreateAlternateViewFromString(str.ToString(), contype);
        msg.AlternateViews.Add(avCal);

        using (SmtpClient smtpclient = new SmtpClient("smtp.gmail.com", 587))
        {
            smtpclient.UseDefaultCredentials = false;
            smtpclient.Credentials = new NetworkCredential("test@gmail.com", "*********");
            smtpclient.EnableSsl = true;
            smtpclient.Send(msg);
        }

Is there a way that can restrict receivers to forward the invite to others? or can restrict the invite for the email of attendees specified?


text:
Q: Conditional Logic for getting a list of sub categories in ACF I am creating a business listings and Advanced Custom Field (ACF) helps me to create the backend form.
The question is, how do I get the sub category of a main category only if I set the condition.
For example,

*

*I have 100s of City names as City Taxonomy

*I have 100s of Area names as sub category of the City Taxonomy
I have created a form that includes these 2 fields.

*

*City:_________ (Drop down selection of City Taxonomy)

*Area Name:_______ (I want this sub category drop down to show up based on City selection above)

Is this possible? Or does it require coding to make it work?
I have searched enough and I could not find even a premium plugins to support this.

I can simply set these 2 fields to pull data from City Taxonomy but the data entry becomes very tough with hyphen appearing before sub-city Taxonomies and possible duplicate value under different city.
Thanks in advance.


text:
Q: iMessageApp - MessagesViewController is not in the view hierarchy I work on the iMessage App and stumbled upon this nasty bug. I would really appreciate the power of the community. Did anyone manage to solve it?

*

*A clear description of the problem:

I work on a Standalone iMessage App. When the iMessage app is active but hidden below the keyboard tapping on the message from that extension opens an app with an empty screen. Investigation of this problem led me to the conclusion that there is no UIWindow attached to the window property of the view in the MessagesViewController. Also, the MessagesViewController is not displayed in the view hierarchy, and MessagesViewController life cycle methods like viewDidLoad and viewDidAppear are not called.

*

*A step-by-step set of instructions to reproduce the problem:

*

*Open an iMessage App (for example Youtube) and send a message from that app to a chat.

*Open the iMessage App again

*Scroll up so that the iMessage App gets hidden below the keyboard

*Scroll down to find a message that you've sent in step 1

*Tap on the message

*The app will expand with an empty view

Here is the bug reproduced in Apple's iMessage Example App https://youtube.com/shorts/3UGyZimctSg?feature=share


text:
Q: java method calling magic 8 ball Here are the parameters:
Create a method called get8BallAnswers (2 point)
The method should have no parameters
The method will build the array of possible String answers (from BA5), and return the entire array
Overload the get8BallAnswers method (2 points)
The method should have 1 integer parameter, where the user can pass a random number to it
The method should return 1 possible String answer from the array. Hint: You can use the method you created in step 2 to retrieve the array of answers.
Create a method called magic8Ball that will basically run the whole program. (2 point)
It should ask the user to enter a question for the 8 Ball, generate a random number, and pass that to one of the methods above to get a response.
You will call this magic8Ball method in the main method.
The method should be called within the do-while loop, and repeat if the user wants to run the program again or not.
here's what I have:
package magic8;
import java.util.Random;
import java.util.Scanner;

public class magic8Ball {

public static String[] get8BallAnswers() {
    String[] ball;
    return ball = new String[] {"Yes, of course!", "Without a doubt, yes.",
"You can count on it.", "For sure!", "Ask me later.", "I'm not sure.", "I can't tell you right now", "I'll tell you after my nap.", "No way!", "I don't think so.", "Without a doubt, no.", "The answer is clearly No."};
}

public static void main(String[] args) {
    boolean run = true;{

    while (run) {
        magic8Ball();

        System.out.println("Do you want to try again, yes or no?");
        Scanner scnr = null;
        String go = scnr.nextLine();
        go = go.toLowerCase();

    if (go.equals("n")) {
        System.out.println("Goodbye");
        run = false;

    }

    if (go.equals("no")) {

        System.out.println("Goodbye");
        run = false;}
    }
}
}
public static void magic8Ball() {
    Scanner input = new Scanner(System.in);
    String response;
    System.out.println("Please ask me a question.");
    response = input.nextLine();

    Random gen = new Random();
    int pick = gen.nextInt(ball.length);
    System.out.println(ball[pick]);
    return;
}
}

I can't get the random number generator to pass a integer into the array ball to get a response.

A: Try this
private static Scanner scanner = new Scanner(System.in);

private static String[] get8BallAnswers() {
    return new String[] {"Yes, of course!", "Without a doubt, yes.", "You can count on it.",
            "For sure!", "Ask me later.", "I'm not sure.", "I can't tell you right now",
            "I'll tell you after my nap.", "No way!", "I don't think so.",
            "Without a doubt, no.", "The answer is clearly No."};
}

private static String get8BallAnswers(int num) {
    return get8BallAnswers()[num];
}

public static void main(String[] args) {
    while (true) {
        magic8Ball();

        System.out.println("Do you want to try again, yes or no?");

        if (scanner.nextLine().toLowerCase().contains("n")) {
            System.out.println("Goodbye");
            break;
        }
    }
}

private static void magic8Ball() {
    System.out.println("Please ask me a question.");
    scanner.nextLine();

    System.out.println(get8BallAnswers(new Random().nextInt(get8BallAnswers().length)));
}


text:
Q: Can a slash in the url be taken as a query insntead of a path to a file directory By my limited understanding the " / " in an URL defines a path in the file directory the html is suppost to be pulled from.
So how is it possible that sites like reddit have URLs such as "reddit.com/u/username", where the slash doesn't define the file directory but is more so taken as a query that requests certain data from a user? Shouldn't you get an error back, that the site doesn't exist because it's not actually a file in the directory?

A:
By my limited understanding the " / " in an URL defines a path in the file directory the html is suppost to be pulled from.

No. It defines a path segment in the path requested from the HTTP server.
The HTTP server is software, it can be written to handle that path in any way the developer likes.
"Map the URL path onto a filesystem path" is only one (simple and common) way an HTTP server can handle paths in URLs.
"Pass it on to a server side program which reads the whole URL and acts in a custom way" is another. If you were using PHP then you might read $_SERVER['REQUEST_URI'].
"Convert the path segments into query string parameters on a different URL and  effectively start the request handling again" is another. Typically, if you were using Apache HTTPD, you would use mod_rewrite for this.
"Have a custom webserver which maps them directly to functions" is another. It's a common approach when writing server side code in Node.js (e.g. with Express routes).

A: Beacuse they use rewrite for pretty urls.


text:
Q: X server randomly restarts I'm running a Debian 9 kiosk with Cinnamon and Chrome browsers. It works fine until it reboots itself without any apparent reason. When this happens, it normally does 2 or 3 restarts in a row and then keeps working fine for a couple of days until it happens again.
I've checked my /var/log/syslog and all I can find there is this:
lots of cronjobs without noticeable errors...
.....
Jun 30 21:30:46 myuser x-session-manager[728]: WARNING: t+185522.72248s: Requesting system shutdown...
Jun 30 21:30:46 myuser x-session-manager[728]: WARNING: t+185522.72265s: Attempting to shutdown using systemd...
......
shuts down, restarts and work for a 50 minutes and then...
again, no noticeable error in here...
......
Jun 30 22:20:58 myuser x-session-manager[720]: WARNING: t+72.48357s: Requesting system shutdown...
Jun 30 22:20:58 myuser x-session-manager[720]: WARNING: t+72.48380s: Attempting to shutdown using systemd...

I was not able to find any documentation on why the X session could want to restart my system.
Would appreciate any tip on how to debug this issue.
PS: The temperatures are fine, about 54°C on peaks.


text:
Q: Get value of a string that is passed as parameter I need to pass in parameters to my sub/function.
When the parameter is passed, the value in the string, I would like to get the value evaluated and sent as:
Dim strParams As String = drRow(0)

' drRow is a row from DB Table. the value in drRow(0) =
' "@FromDate=""" & Now.AddDays(-10).ToShortDateString & """&@ToDate=""" & Now.AddDays(-4).ToShortDateString "

I would like to see this converted to:
Dim strFinal as string

strFinal = ProcessString(strParams)

End Result should be:
strFinal = "@FromDate=10/09/2011&@ToDate=10/15/2011"

Any ideas how I can do this. I am getting the initial string from DB, I need to convert to the final string, I am not able to figure out how to write the "ProcessString" function.
Thanks for looking.

A: "IF" you can change your parameter statement to something simple like:

@FromDate=;-10;@ToDate=;-4

Then you can do something like this:
Dim strParams As String = "@FromDate=;-10;@ToDate=;-4"
Dim value As String = String.Empty
Dim parts() As String = strParams.Split(";"c)
If parts.Length = 4 Then
  Dim fromDays As Integer
  Dim toDays As Integer
  If Integer.TryParse(parts(1), fromDays) AndAlso Integer.TryParse(parts(3), toDays) Then
    value = parts(0) + Now.AddDays(fromDays).ToShortDateString + parts(2) + Now.AddDays(toDays).ToShortDateString
  End If
End If

MessageBox.Show("Value = " & value)

If it's anything more complicated than that then you will have to start parsing every part of your string with lots of If and Select statements-- you should probably heed Jim Mischel's advice and try a different approach.

A: This is the end result of what i used based on suggestions.. Thanks  Guys.
Public Function ProcessParameters(ByVal strParams As String) As String

    Dim arrParams() As String
    'strParams = "@FromDate=-10;&@ToDate=-4;&@CompanyID=1"

arrParams = strParams.Split(";")
 Dim arrP() As String
    Dim strFinalParams As String = ""
    For Each strP As String In arrParams
        arrP = strP.Split("=")
        If arrP(0).ToString.EndsWith("Date") Then
            strFinalParams &= arrP(0) & "=" & Now.AddDays(arrP(1)).ToShortDateString
        Else
            strFinalParams &= arrP(0) & "=" & arrP(1)
        End If
    Next
    Return strFinalParams
End Function

}


text:
Q: How to view the values of Swift float2, float3, float4, etc in XCode debugger? I am always hampered in debugging by the inability of XCode to display the values contained in the float3 and like types.  I always have to go in, put down some print statements, and then recompile.  And this is especially painful when I am trying to track where in a series of calculations a number is going wrong.
How do you view the values of these variables in XCode?  (and why doesn't Apple fix this issue...)
Thanks

A: Try adding extensions for those types to your code:
extension float3: CustomStringConvertible {
    public var description: String {
        return "x: \(self.x)\ny: \(self.y)\nz: \(self.z)"
    }
}
extension float4: CustomStringConvertible {
    public var description: String {
        return "x: \(self.x)\ny: \(self.y)\nz: \(self.z)\nw: \(self.w)"
    }
}

var aFloat3 = float3(x: 1.0, y: 2.0, z: 3.0)
var aFloat4 = float4(x: 1.0, y: 2.0, z: 3.0, w: 4.0)

print (aFloat3)
print (aFloat4)


text:
Q: How to bind text insertion in isearch I'd like to have M-u to insert an underscore when I am in isearch (isearch-regexp and also the reverse variants).
Neither
(define-key isearch-mode-map (kbd "M-u") 'insert-underscore)

nor
(add-hook 'isearch-mode-hook
      (lambda ()
       (local-set-key (kbd "M-u") 'insert-underscore)
      ))

insert-underscore is my function that simply inserts "_". It works in the main frame and also in minibuffer, but I can't get it working in isearch...
Thank you!

A: Isearch doesn't use regular commands.  (kbd "_") along with every other
printable character is bound to a special command in isearch-mode-map. It's
not obvious, but a lot of things happen in "isearch-mode" when you press a
key.  Display is refreshed with new results, wrapping is a possibility, etc, etc,
You'd have to manipulate raw keyboard events to get this to work.
(defun underscore ()
  (interactive)
  (isearch-unread-key-sequence (list ?_)))

(define-key isearch-mode-map (kbd "M-u") 'underscore)

Note that this code is not robust; for example, numeric prefix does not work.
EDIT: After letting percolate in my mind for a while, it occured to me that this is the exact use-case for translation keymaps
(define-key key-translation-map (kbd "M-u") (kbd "_"))

Ain't Emacs grand?


text:
Q: How to set permission to " Allow from all " like Wamp in cPanle Hosting I was trying to pass data to my php API as JSON. API was hosted in localhost using Wamp.
then there was an error in android logcat -
org.json.JSONException: Value This site requires Javascript to work, please enable Javascript in your browser or use a browser with Javascript support
2019-05-13 23:35:48.165 5767-5866/codecanyon.getpills W/System.err: org.json.JSONException: Value


text:
Q: Find which class an object was instantiated in I am trying to learn unnecessarily complicated source code. There is a method public void passObject(SomeObject someObject), and I want to know which class someObject was instantiated in. The problem is, as we traverse up the call hierarchy, the branching factor is very large. For example, three methods can pass someObject through passObject, and three methods before these three methods can pass the same object respectively.
Is there some method that I can insert into passObject such as:
public void passObject(SomeObject someObject) {
    whereDidThisComeFrom(someObject); // Should print the class (perhaps) where someObject was instantiated.
    //
    //do the other stuff that passObject is supposed to do.
}

I use Eclipse.

A: The easiest / dirtiest way is to just put (new Exception("test")).printStackTrace() in SomeObject's constructor and run the code. You'll get a stack trace printed to the console every time SomeObject is instantiated.
Eclipse also supports breakpoints in constructors so you could set a breakpoint and debug.

A: It's true that using 'Show Call Hierachy' can show too many results to really give you an idea of execution flow.
Instead, you could try using Eclipse in debug mode, and put a break-point on the first line of passObject(SomeObject someObject). You'll then see the current stack-trace. By inspecting the code on the stack-trace you can determine the call hierarchy which actually occurred.
Alternatively, if you can't debug, can you add another line to passObject(SomeObject someObject) to print the current stack trace? See here for details.


text:
Q: Dagger2 injection of a ViewModel without @Inject constructor I have large Android ViewModel classes that tend to have a lot of dependencies (most of them are DAOs from Room, one per SQLite table). Some have more than 10 dependencies.
This is fine but the @Inject constructor is bloated with arguments, and contains only boilerplate code to set the injected members from the constructor arguments.
I wanted to switch to "regular" injected members, identified individually with an @Inject annotation, like other (dumb) classes.
This fails for Android related classes (although ViewModels are advertised as non-Android dependent, e.g. they don't use the Android framework) such as activities and fragments.
The workaround for that is to use a factory, which is injected from the Application class using the nice HasActivityInjector, HasServiceInjector, etc. interfaces.
Dagger doesn't provide any HasViewModelInjector, so if I persist in injecting members individually instead of injecting the constructor, here's what I'm given:

error: [dagger.android.AndroidInjector.inject(T)] XXXViewModel cannot be provided without an @Inject constructor or from an @Provides-annotated method. This type supports members injection but cannot be implicitly provided.

If I create a module that has a @Provides annotation to create the ViewModel, this doesn't inject individual members.
Did I miss something (my last sentence is what's most important in my question) or is it simply not possible to inject members, and I have to inject the constructor?

A bit of code.
What I want:
class MyViewModel extends ViewModel {
    @Inject
    MyDao myDao;
}

versus what I need to do:
class MyViewModel extends ViewModel {
    private final MyDao myDao;

    @Inject
    MyViewModel(MyDao myDao) {
        this.myDao = myDao;
    }
}

First block of code (what I want) requires this method in a module:
@Provides
MyViewModel provideMyViewModel() {
    return new MyViewModel();
}

but in this case the myDao field is null. How to inject the @Inject-annotated members?
I want to avoid the use of the 2nd block of code, which tends to create a huge constructor bloated with many arguments, should I need to inject a lot of members.

A: There are multiple ways of injection and I think you are referring to field injection. Field injection, unlike constructor injection, must be triggered manually. To do that, define a method in your component with the view model as parameter.
void inject(ViewModel viewModel)

And then call this method from your view model constructor perhaps.
class MyViewModel extends ViewModel {
    private final MyDao myDao;

    @Inject
    MyDao myDao;

    public MyViewModel() {
        MyComponent mycomponent = DaggerMyComponent.....
        myComponent.inject(this);
    }
}


text:
Q: Measuring connectivity between clusters in an organizational network in R I'm trying to conceptualize a network analysis problem and figure out where to start in terms of analysis techniques in R. Apologies as I'm fairly new to all this.
Basically, I have a employee network for an organization which spans multiple geographies. I want to define metrics to calculate how well the nodes in a specific geography are connected to the nodes in geographies other than its own.
Also, I am looking for any libraries/ functions that already exist in R to perform such calculations. I understand there is a wealth of network analysis techniques out there, but I'm at a loss where to start really.

A: The Krackhardt ratio, also known as the E-I ratio, provides a measurement of "the relative density of internal connections within a social group compared to the number of connections that group has to the external world." If I understand your question correctly, this is exactly what you are looking for.
You could calculate the average Krackhardt ratio for nodes in each geographic location, and compare them against each other.
There is a short implementation in R here:
https://rpubs.com/pjmurphy/300606


text:
Q: What version of Blend supports WPF 4.5, Portable Class Library? I am setting up the project structure for a new greenfield application.  Our initial release will only support a WPF client, but we want to eventually roll out Metro and Silverlight clients as well.  I decided on the following:
Core Library - Portable class library targeting .NET for metro, .NET 4.5, SL4, Windows Phone 7.5
WPF Application - Targeting .NET 4.5
Our Model/ViewModel layer is defined in the Core Library, View defined in the WPF Application.  I chose .NET 4.5 in order to support defining the viewmodel in the core library in a way that can be consumed by both WPF and Metro.
This works fine in the Visual Studio 11 Beta running on Windows 7 Pro.  I have a working view that is data bound to the ViewModel defined in the Core Library.  My problem is Blend.  When I open the View in Blend, I get no designer.  I suspect the problem here is support for WPF on .NET 4.5.  I have tried Blend 4 and Blend for VS11 Beta.
Does anyone know how to get the designer working in Blend for WPF views as described above?
*Status as of 2012-05-10:
  No combination of VS11 and Blend appear to support WPF 4.5.

A: edit: At this time, there's no Blend support for WPF 4.5.  Here's the relevant info:
You need to install Visual Studio 11 Beta (Ultimate, Premium, or Professional -- NOT Express since it lacks the Blend pieces you want) on a Windows 8 preview build.  That's just how they decided to line things up.  Even once you do this, you still won't have WPF support:

Please be aware that in the Visual Studio beta, the XAML authoring
  support for Windows 8 is not quite at the same level of stability and
  completeness yet as the HTML authoring support.

Windows 8 requirement: http://blogs.msdn.com/b/devschool/archive/2012/03/01/blend-5-and-visual-studio-11-awesome.aspx
Visual Studio versions: http://blendinsider.com/technical/visual-authoring-for-the-windows-8-consumer-preview-with-blend-and-visual-studio-2012-02-29/

A: Since Visual Studio 2012, Update 2, the preview version of Blend (Blend + Sketchflow Preview for VS2012) has been merged with into the vanilla "Blend for Visual Studio 2012". This means that there is now a single designer application for all XAML platforms:

With Blend (for Visual Studio 2012), you can design and build:

*

*Windows Store apps

*Windows Phone apps

*Sketchflow prototypes

*Microsoft Silverlight and Windows Presentation Foundation (WPF) applications


text:
Q: Filtering Immutable.js List: filter vs skipUntil vs findIndex/takeLast I need to filter an Immutable.js List which is already sorted. To compare three different approaches, I performed the following benchmark test (based on Benny):
import b from 'benny'
import { Range } from 'immutable'

const elementCount = 100000
const list = Range(0, elementCount).toList()
const predicate = (e: number): boolean => e > elementCount / 2

b.suite(
  'Filter sorted Immutable.js List',

  b.add('via filter', () => {
    list.filter(predicate)
  }),

  b.add('via skipUntil', () => {
    list.skipUntil(predicate)
  }),

  b.add('via findIndex/takeLast', () => {
    list.takeLast(list.size - list.findIndex(predicate))
  }),

  b.cycle(),
  b.complete()
)

These were the results on my machine:
via filter:
    104 ops/s, ±1.54%   | slowest, 77.09% slower

via skipUntil:
    104 ops/s, ±1.65%   | 77.09% slower

via findIndex/takeLast:
    454 ops/s, ±1.17%   | fastest

Obviously, I expected the plain filter approach to be the slowest with O(n), but I am a bit baffled that findIndex/takeLast is much faster than skipUntil – could anyone explain please?
UPDATE: This looks like a regression in v4.0.0-rc.12 compared to v3.8.2, I reported an issue

A: In immutable, the most expensive/slowest operation is when it has to create something new.
findIndex only returns a single element. it does not have to create or modify anything.
takeLast internally is using slice, which uses sequences to create a sublist instead of populating a new list itself.
filter returns a new collection with all the matching elements. Creating said list is expensive.
skipUntil is internally calling skipWhile(not(predicate)), which seems to work similar to filtering.

Returns a new Collection of the same type which includes entries
  starting from when predicate first returns true.

You might get faster results from skipUntil when creating a Seq out of the list first, as it is a lazy wrapper and let's you do some operations withouth fully realizing the complete collection.
The docs are actually quite good, I recommend looking at them regularly. Immutable has quite some pitfalls where you can waste performance, so I tend to look up functions in the doc every 2nd day.


text:
Q: post array of objects to mvc controller I'n using ajax post to controller in mvc4,
my code controller is :
[HttpPost]
public JsonResult UpdateAllSettings(int PresetID,List<CustomerAjaxServiceSettingPoco> customerServiceSettings)
{

and CustomerAjaxServiceSettingPoco is:
 public class CustomerAjaxServiceSettingPoco
    {
        public int ID { get; set; }
        public string ClientSettingValue { get; set; }
    }

my javascript is :
 var customerServiceSettings = new Array();
        $('.settings_user').each(function () {
            customerServiceSettings[customerServiceSettings.length] = { 'ID': $(this).data('settingsid'), 'ClientSettingValue': $(this).val() };
        });

$.ajax({
        url: '/Services/UpdateAllSettings?PresetID=' + PresetID,
        type: 'POST',
        data: { 'customerServiceSettings':JSON.stringify( customerServiceSettings) },
        traditional: true,
        dataType: 'json',
        success: function (result) {
            do...
        }
    });

still in debug mode I get "customerServiceSettings count=0" and "PresetID = 1"
what am I doing wrong ?
in fire bug the post source is :
parameters
customerServiceSettings [{"ID":1,"ClientSettingValue":"False"},{"ID":2,"ClientSettingValue":"False"},{"ID":3,"ClientSettingValue":"False"},{"ID":4,"ClientSettingValue":"False"},{"ID":5,"ClientSettingValue":"True"},{"ID":6,"ClientSettingValue":"True"},{"ID":9,"ClientSettingValue":"True"},{"ID":10,"ClientSettingValue":"False"},{"ID":11,"ClientSettingValue":"True"},{"ID":12,"ClientSettingValue":"True"},{"ID":13,"ClientSettingValue":"False"},{"ID":14,"ClientSettingValue":"True"},{"ID":15,"ClientSettingValue":"True"},{"ID":67,"ClientSettingValue":""},{"ID":68,"ClientSettingValue":""},{"ID":69,"ClientSettingValue":""},{"ID":70,"ClientSettingValue":""},{"ID":21,"ClientSettingValue":"True"},{"ID":22,"ClientSettingValue":"True"},{"ID":23,"ClientSettingValue":"False"},{"ID":24,"ClientSettingValue":"True"},{"ID":25,"ClientSettingValue":"False"},{"ID":27,"ClientSettingValue":"False"},{"ID":28,"ClientSettingValue":"False"},{"ID":71,"ClientSettingValue":""},{"ID":72,"ClientSettingValue":""}]
Source
customerServiceSettings=%5B%7B%22ID%22%3A1%2C%22ClientSettingValue%22%3A%22False%22%7D%2C%7B%22ID%22%3A2%2C%22ClientSettingValue%22%3A%22False%22%7D%2C%7B%22ID%22%3A3%2C%22ClientSettingValue%22%3A%22False%22%7D%2C%7B%22ID%22%3A4%2C%22ClientSettingValue%22%3A%22False%22%7D%2C%7B%22ID%22%3A5%2C%22ClientSettingValue%22%3A%22True%22%7D%2C%7B%22ID%22%3A6%2C%22ClientSettingValue%22%3A%22True%22%7D%2C%7B%22ID%22%3A9%2C%22ClientSettingValue%22%3A%22True%22%7D%2C%7B%22ID%22%3A10%2C%22ClientSettingValue%22%3A%22False%22%7D%2C%7B%22ID%22%3A11%2C%22ClientSettingValue%22%3A%22True%22%7D%2C%7B%22ID%22%3A12%2C%22ClientSettingValue%22%3A%22True%22%7D%2C%7B%22ID%22%3A13%2C%22ClientSettingValue%22%3A%22False%22%7D%2C%7B%22ID%22%3A14%2C%22ClientSettingValue%22%3A%22True%22%7D%2C%7B%22ID%22%3A15%2C%22ClientSettingValue%22%3A%22True%22%7D%2C%7B%22ID%22%3A67%2C%22ClientSettingValue%22%3A%22%22%7D%2C%7B%22ID%22%3A68%2C%22ClientSettingValue%22%3A%22%22%7D%2C%7B%22ID%22%3A69%2C%22ClientSettingValue%22%3A%22%22%7D%2C%7B%22ID%22%3A70%2C%22ClientSettingValue%22%3A%22%22%7D%2C%7B%22ID%22%3A21%2C%22ClientSettingValue%22%3A%22True%22%7D%2C%7B%22ID%22%3A22%2C%22ClientSettingValue%22%3A%22True%22%7D%2C%7B%22ID%22%3A23%2C%22ClientSettingValue%22%3A%22False%22%7D%2C%7B%22ID%22%3A24%2C%22ClientSettingValue%22%3A%22True%22%7D%2C%7B%22ID%22%3A25%2C%22ClientSettingValue%22%3A%22False%22%7D%2C%7B%22ID%22%3A27%2C%22ClientSettingValue%22%3A%22False%22%7D%2C%7B%22ID%22%3A28%2C%22ClientSettingValue%22%3A%22False%22%7D%2C%7B%22ID%22%3A71%2C%22ClientSettingValue%22%3A%22%22%7D%2C%7B%22ID%22%3A72%2C%22ClientSettingValue%22%3A%22%22%7D%5D

A: Try add contentType and stringify whole object, something like this:
$.ajax({
        type: 'POST',
        dataType: 'json',
        url: '...',
        data: JSON.stringify({ steps: ['1', '2', '3'] }),
        contentType: 'application/json; charset=utf-8',
});


text:
Q: hashmap cache in servlet I am trying to implement a servlet for GPS monitoring and trying create simple cache, because i think that it will be faster then SQL request for every Http Request. simple scheme:
in the init() method, i reads one point for each vehicle into HashMap (vehicle id = key, location in json = value) . after that, some request try to read this points and some request try to update (one vehicle update one item). Of course I want to minimize synchronization so i read javadoc :
http://docs.oracle.com/javase/6/docs/api/java/util/HashMap.html

Note that this implementation is not synchronized. If multiple threads access a hash map concurrently, and at least one of the threads modifies the map structurally, it must be synchronized externally. (A structural modification is any operation that adds or deletes one or more mappings; merely changing the value associated with a key that an instance already contains is not a structural modification.)

If I am right, there is no any synchronization in my task, because i do only "not a structural modification == changing the value associated with a key that an instance already contains)". is it a correct statement?

A: Use the ConcurrentHashMap it doesn't use synchronization by locks, but by atomic operations.

A: Wrong.  Adding an item to the hash map is a structural modification (and to implement a cache you must add items at some point).
Use java.util.concurrent.ConcurrentHashMap.

A: If I understand correctly, you have two types of request:

*

*Read from cache

*Write to cache (to update the value)

In this case, you may potentially try to write to the same map twice at the same time, which is what the docs are referring to.
If all requests go through the same piece of code (e.g. an update method which can only be called from one thread) you will not need synchronisation.
If your system is multi-threaded and you have more than one thread or piece of code that writes to the map, you will need to externally synchronise your map or use a ConcurrentHashMap.

For clarity, the reason you need synchronisation is that if you have two threads both trying to update the a JSON value for the same key, who wins? This is either left up to chance or causes exceptions or, worse, buggy behaviour.
Any time you modify the same element from two threads, you need to synchronise on that code or, better still, use a thread-safe version of the data structure if that is applicable.

A: if all the entries are read into hashmap in init() and then only read/modified - then yes, all the other threads theoretically do not need to sync, though some problems might arise due to threads caching values, so ConcurrentHashMap would be better.
perhaps rather than implementing cache yourself, use a simple implementation found in Guava library

A: Caching is not an easy problem - but it is a known one. Before starting, I would carefully measure wheter you really do have a performance problem, and whether caching actually solve it. You may think it should, and you may be right. You may also be horrendously wrong depending on the situation ("Preemptive optimization is the root of all evil"), so measure.
This said, do not implement a cache yourself, use a library doing it for you. I have personnaly good experience with ehcache.


text:
Q: Best way to extract values from strings (regexp?) I'm working with an app (Ruby 1.9.2, Rails 3) and an API and need interface an API given certain param values.
What's the best way to break this:
bedrooms: 3 - 7
bathrooms: 1 - 8
sqft: 1000 - 8000
price: $100000 - $800000

Into this:
bedrooms_min = 3
bedrooms_max = 7
bathrooms_min = 1
bathrooms_max = 8
sqft_min = 1000
sqft_max = 8000
price_min = 100000
price_max = 800000

A: price_input = "$100000 - $800000"
price_min, price_max = price_input.gsub(/[^\d-]/, '').split('-', 2).map(&:to_i)
price_min # 100000
price_max # 800000

So, basically we remove everything except digits and '-' sign that separates two values and then split string in two by this separator.


text:
Q: How can I express a multi-line regex in assertRegex in Python 3? I'm using the assertRegex() function from the unittest library in Python 3.4. It only takes two relevant parameters: the text to match against and the regex. The seems to prevent me from expressing any regex-related constants such as re.MULTILINE.
How can I construct or specify a multi-line regex and use it with assertRegex()? Alternatively, is there a related way of solving my problem?

A: See here in the Python docs:
(?iLmsux)

(One or more letters from the set 'i', 'L', 'm', 's', 'u', 'x'.) The group matches the empty string; the letters set the corresponding flags: re.I (ignore case), re.L (locale dependent), re.M (multi-line), re.S (dot matches all), re.U (Unicode dependent), and re.X (verbose), for the entire regular expression. (The flags are described in Module Contents.) This is useful if you wish to include the flags as part of the regular expression, instead of passing a flag argument to the re.compile() function.
Note that the (?x) flag changes how the expression is parsed. It should be used first in the expression string, or after one or more whitespace characters. If there are non-whitespace characters before the flag, the results are undefined.

A: One way is to construct Regexp with re.compile (Official Python 3 reference). An example is
self.assertRegex(str1, re.compile('\\bcd '+re.escape(os.getcwd())+'\n', re.M | re.I))

This is useful when the expression is complex.


text:
Q: Getting file size of each file on a very large file system I have to move the 20TB file system with a couple of million of files to a ZFS file system. So I would like to get an idea of the file sizes in order to make a good block size selection.
My current idea is to `stat --format="%s" each file and then divide the files into bins.
#!/bin/bash

A=0 # nr of files <= 2^10
B=0 # nr of files <= 2^11
C=0 # nr of files <= 2^12
D=0 # nr of files <= 2^13
E=0 # nr of files <= 2^14
F=0 # nr of files <= 2^15
G=0 # nr of files <= 2^16
H=0 # nr of files <= 2^17
I=0 # nr of files >  2^17

for f in $(find /bin -type f); do

    SIZE=$(stat --format="%s" $f)

    if [ $SIZE -le 1024 ]; then
    let $A++
    elif [ $SIZE -le 2048 ]; then
    let $B++
    elif [ $SIZE -le 4096 ]; then
    let $C++
    fi
done

echo $A
echo $B
echo $C

The problem with this script is that I can't get find to work inside a for-loop.
Question
How to fix my script?
And is there a better way to get the all the file sizes of a file system?

A: The main problem is that you are using command substitution to feed the output of find to the for loop. Command substitution works by running the command within parentheses (or backticks) to completion, collecting its output, and substituting it in to the script. That doesn't support streaming, meaning the for loop won't run until the find scan is completely done, and you'll need lots of memory to buffer the output of find too.
Especially because you are scanning many terabytes worth of files, you will want to use something that supports streaming, like a while loop:
find /bin -type f | while read f; do
    ...
done

With something that can stream, your script will at least work, but keep in mind that this technique forces you to invoke an external command (stat) once for each and every file that is found. This will incur a lot of process creation, destruction, and startup cost for the stat command. If you have GNU find, something that outputs the size of each file right in the find command with its -printf option for example would perform much better.
Aside: the let statements in the body of the loop look wrong. You are expanding the contents of the $A, $B, and $C variables instead of referencing them. You shouldn't use $ here.

A: If just want to find out the number of files between say 100M and 1000M you can do the following
find . -size +100M -size -1000M  -type f | wc -l

A: I would investigate using dd to read the zfs metadata, which should be contained on the data disks themselves.
That might be a bad suggestion and could result in you wasting time.  But crawling the filesystem with bash is going to take a long time and chew system cpu utilization.

A: find /bin/ -type f -printf "%s\n" > /tmp/a

And then use the following as script.pl < /tmp/a.
#!/usr/bin/perl

use warnings;
use strict;
use Data::Dumper;

my %h = ();

while (<STDIN>) {
    chomp;
    if    ($_ <= 2**10) { $h{1} += 1}
    elsif ($_ <= 2**11) { $h{2} += 1}
    elsif ($_ <= 2**12) { $h{4} += 1}
    elsif ($_ <= 2**13) { $h{8} += 1}
    elsif ($_ <= 2**14) { $h{16} += 1}
    elsif ($_ <= 2**15) { $h{32} += 1}
    elsif ($_ <= 2**16) { $h{64} += 1}
    elsif ($_ <= 2**17) { $h{128} += 1}
    elsif ($_ >  2**17) { $h{big} += 1}
}

print Dumper \%h;

A: The venerable du command would provide you with sizes more directly.


text:
Q: Is it possible to use non-orthogonal 2D axes for plots in Mathematica? I want to plot uni-variate functions using 2D plots but I want to be able to change the angle between the axes so that they are not perpendicular. Is this possible?
I have looked through all the graphics options and have not be able to discover any that accomplish this. Such an option might reasonably be called AxesAngle. I know I could do a plot without the axes and then draw these later on my own but this is not what I want. I want the plot to be based on non-parallel axes.

A: You can rotate to achieve any desired angle between axes and also their position.
ParametricPlot3D[{x, 0, Sin[x]}, {x, -π, π},
 Axes -> {True, False, True}, AxesOrigin -> {0, 0, 0}, Boxed -> False]


text:
Q: Hadoop: Create empty bag if field is null in Pig I have an example of the following data
id : long,
list: {(itemId: Long, itemName: charArray)}

In my data, list can either be a bag of tuples or null. I would like to change the null into an empty bag (consisting of 0 elements)
I tried something like :
answer = FOREACH data
 GENERATE (list is null ? {} : list) AS list;

It says that {} and list are not compatible schemas. I am wondering how I can create an empty bag with a compatible schema
I ended up doing this and it worked:
answer = FOREACH data
GENERATE (list is null ? (bag{tuple(long,chararray)}){} : list) AS list:{(itemId: long, itemName: charArray)};

A: {} has no types as is. Bags always have a tuple type inside of it. list and your empty bag need to have the same type.
I unfortunately don't have Pig up in a way that I can test this for you and I'm not sure exactly how to do it, but it's going to be something along the lines of this... I couldn't find good documentation on how to set the type of a bag...
Try this perhaps?
answer = FOREACH data
GENERATE (list is null ? (bag{tuple(long,chararray)}){} : list) AS list;

A: If you have the chance to use it, take a look at Apache DataFu project: http://datafu.incubator.apache.org
It has lots of useful stuff for Pig, including datafu.pig.bags.NullToEmptyBag(), which does exactly what you are looking for:
DEFINE NullToEmptyBag datafu.pig.bags.NullToEmptyBag();
...
answer = FOREACH data GENERATE NullToEmptyBag(list) AS list...;

A: empty tuple should be ()
empty bag should be {}
empty map should be []


text:
Q: TypeError: Service is not a function when calling API by angular js Whenever I run the app implemented by angularjs 1.4.3.
BannerService.js
app.service('BannerService',function ($http) {

    this.save = function saveBanner(banner) {
        return $http({
              method: 'POST',
                url: 'http://localhost:8081/api/banners'
            });
    }

});

BannerController.js
app.controller('BannerAddCtrl', ['$scope','$log','BannerService',
    function ($scope,$log, BannerService) {
        $scope.save = function() {
            BannerService.saveBanner(myBanner)
                .success(function (result) {
                    $log.debug('RESULT', result);
                }, function (reason) {
                    $log.debug('REASON', reason);
                });
        }

}]);
And index.html
 <div class="modal-footer">
    <button type="button" class="btn btn-primary btn-block" ng-click="save()">Save Banner</button>

  </div>

It throws an exception as below:
TypeError: BannerService.saveBanner is not a function
at ChildScope.$scope.save (bannerControllers.js:64)
at fn (eval at compile (angular.js:13145), <anonymous>:4:203)
at callback (angular.js:23298)
at ChildScope.$eval (angular.js:15846)
at ChildScope.$apply (angular.js:15945)
at HTMLButtonElement.<anonymous> (angular.js:23303)
at HTMLButtonElement.dispatch (jquery.js:4435)
at HTMLButtonElement.elemData.handle (jquery.js:4121)

Can someone help me why I get the error. Greatly appreciate your time.

A: Take a look at the error message:
BannerService.saveBanner is not a function

Basically, your app is looking for the property saveBanner assigned to your Service. But currently you haven't declared such a property. Instead your Service contains a property called save which defines a function (called saveBanner).
AngularJS doesn't care about a named function which is assigned to a property. So instead, you've to adjust the propertyname itself. So your Service's function/property should be like this.
this.saveBanner = function () { ... }

A: Write your service like below.
var self = this;
self.saveBanner = function () { ... }

A: You're save function in the controller isn't actually calling the function in your service.
app.service('BannerService',function ($http) {
        return {
          saveBanner: function(banner) {
                return $http({
                      method: 'POST',
                        url: 'http://localhost:8081/api/banners'
                    });
                  }
               }
});


text:
Q: R how to get the function definition when call inside other function result <- .Call("mcga", popsize, chsize, crossprob, mutateprob,
    elitism, minval, maxval, maxiter, par, best, evalFunc,
    population, costs, envv, PACKAGE = "mcga")

how to get the mcga function definition in R, mcga is a R package for genetic algorithm.

A: .Callis used to call compiled code (dll or equivalent). The only way is to retrieve the source package (the .tar.gz), uncompress and have a look at the source code -- Cf https://cran.r-project.org/web/packages/mcga/index.html; uncompress and have a look at "src" folder (seems to be C code in that case)

A: You can get the definition of the function at the GitHub page of the package:
https://github.com/cran/mcga/blob/master/src/mcga.c
Regards,
J_F


text:
Q: php shortcode with id I need a piece of code that transforms
[plugin-testplugin]

to a PHP include. This is working fine.
However, I want to have something more like this:
[plugin-testplugin 12]

where the testplugin only shows the content with 12 as id in the database.
How can I accomplish this?
This is my code:
$regex = '~\[plugin-([^]]+)]~';
$plugin = htmlspecialchars_decode($page['plugin']);
$parts = preg_split($regex, $plugin, -1, PREG_SPLIT_DELIM_CAPTURE);

foreach($parts as $k => $v){
    if($k & 1)
        include('plugins/'.$v.'/'.$v.'.php');
    else
        echo htmlspecialchars_decode($v);
}


text:
Q: C standard regarding sizeof overflowing size_t Is this undefined behavior?  The relevant parts of the standard don't say much.
size_t n = SIZE_MAX / sizeof(double) + 1;
size_t m = sizeof(double[n]);

A: The C standard does not explicitly state that the size_t type is sufficient for working with the sizes of all objects or types, especially for hypothetical types that are not actually instantiated.
In C 2018 7.19 2, the standard says that size_t "is the unsigned integer type of the result of the sizeof operator". That tells us about the type size_t but not about the values that may arise during computation. In 5.2.4, the standard recognizes that C implementations necessarily have limits, and that they must break down at various points.
7.19 4 says "The types used for size_t and ptrdiff_t should not have an integer conversion rank greater than that of signed long int unless the implementation supports objects large enough to make this necessary." This reaffirms our desire that size_t be capable of representing the sizes of all supported objects, particularly since it implies that the existence of an object makes it "necessary" that size_t be able to represent it, but it is not an explicit statement that size_t must do so, nor does it apply to hypothetical types that can be described but not instantiated as objects.
Were we to evaluate n * sizeof(double), we know the result: 6.2.5 9 says "A computation involving unsigned operands can never overflow, because a result that cannot be represented by the resulting unsigned integer type is reduced modulo the number that is one greater than the largest value that can be represented by the resulting type." However, with sizeof(double[n]), it is not completely clear this applies because, although n is unsigned, it is not the direct operand of sizeof, where the computation of a result that cannot be represented occurs. The standard does not explicitly tell us that the result of this sizeof will be reduced in the same way.
Thus, this operation is not covered by the C standard.


text:
Q: What are the implications of setting application registration to "Accounts in any organizational directory" As part of the Virtual Assistant deployment documentation, it asks to set the application registration to allow Accounts in any organizational directory.
However, it doesn't describe the implications are of this overlooked setting.

*

*For example, say we want this application to only be available to employees of a particular organization. Should we still set the app registration to Accounts in any organizational directory and then build authentication into the bot elsewhere?

*What if we are required to set it to Accounts in this organizational directory only. For example, say you're deploying this for a client and their security practices don't allow us to make this change. How can we work around this?

*How does this impact testing with the bot emulator? How about through the Azure Portal interface?

A: This was actually a discussion point that popped up last week internally. Posting answer here so the community can see sooner, before we can get official MSFT documentation out there

User's issue
User created a bot with manual app registration, and continued to get "Internal Server Error"

"We tried a number of things to get around this, and through trial and
  error we found that once we changed the app registration setting for
  Supported account types from "Accounts in this organizational
  directory only" to "Accounts in any organization directory", restarted
  the app, and the bot started working again.  I replicated this in my
  sub, as well."

"Accounts in any organizational directory" Explanation
This is required so that we (in the bot framework.com) can request a token for the bot.  Pulled from a related thread:
Issue
Bots failing to work from the start due to the below error:
[Error] Microsoft.BotBuilderSamples.EchoWithCounterBot: Exception caught : Microsoft.Bot.Connector.Authentication.MicrosoftAppCredentials+OAuthException: Bad Request --->System.Net.Http.HttpRequestException: Response status code does not indicate success: 400 (Bad Request).

at System.Net.Http.HttpResponseMessage.EnsureSuccessStatusCode()

at Microsoft.Bot.Connector.Authentication.MicrosoftAppCredentials.<RefreshTokenAsync>d__36.MoveNext()

This exception was occurring because the Bot Framework SDK was trying to make a call to the botframework.com AAD tenant to retrieve a token, and AAD was replying back with an HTTP 400 Bad Request, indicating there was an issue with the app registration credentials.
Further troubleshooting uncovered the below specific error from AAD:
Application with identifier '[appID]' was not found in the directory 'botframework.com'.

Context
An app registration has three options/scopes for what kind of accounts can use it:

*

*Accounts in the current organizational directory (for you, that would be the xxx directory)

*Accounts in any organizational directory

*Accounts in any organizational directory and personal Microsoft accounts (e.g. Skype, Outlook.com, Xbox, etc.)

I refer to the numbers above numerous times below.
By default, when allowing the Azure Portal to create its own app registration during Bot resource creation, it does so with option 3 above. This is true if you opt for automatic creation, or click the link during creation to manually create a registration – both of those create a registration with option 3.
For example, if creating a Web App Bot in the portal, the default option (at the bottom) is this:

You can expand that part to get this:

If you click the link to "Create App ID …" it brings you to the current App Registrations portal with a pre-populated app ID and name.
Both methods above create an app registration with the #3 scope above.
Cause
Based on discussions with the AAD team and testing I performed on Bots and registrations last week, the issue was caused by the scope of the registration being too narrow.
In your case, app registrations were configured with a #1 scope above, which limits the registration so it can be used only by xxx. Since the Bot Framework SDK needs the AAD botframework.com tenant to use that registration, it failed to retrieve a token.

Resolution
As a test, we modified the existing registration from option #1 to option #2 using the App registrations (Preview) blade in the Azure Portal (under the Azure Active Directory section). Since this option opens the registration to be used by any AAD organization, which includes botframework.com, the Bot SDK had no issues retrieving a token and started working immediately.

Going Forward
Since your organization utilizes a separate management system/application for app registrations, you'll need to ensure that registrations created for use by Bots are created with option #2 or #3, or modified afterwards if created with #1. A Bot will not work, guaranteed, if the registration can only be used by the xxx tenant, which is option #1.
Existing registrations can be modified from the Azure Portal:
Portal -> Azure Active Directory -> App registrations (Preview) -> [choose one] -> Authentication blade
If you see this, then the registration is already scoped for #3 and should be fine:

If you see this, then ensure #2 is selected:


text:
Q: CleverElements / Sendcockpit SOAP API parameters aren't recognized I'm trying to use the CleverElements SOAP API, but I can't get it to work. I have honestly never worked with SOAP (but a lot with XML-RPC, REST, etc.), and thought it should be straightforward.
I'm using Ruby with the savon gem. I can call any function via SOAP which doesn't need any parameters, but on functions with parameters, the SOAP service doesn't recognize the parameters.
This is my request:
<?xml version="1.0" encoding="UTF-8"?>
<env:Envelope xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:wsdl="Sendcockpit/API" xmlns:env="http://schemas.xmlsoap.org/soap/envelope/" xmlns:ins0="Sendcockpit/API">
  <env:Header>
    <validate>
      <userid>32027</userid>
      <apikey>**************</apikey>
      <version>1.0</version>
      <mode>live</mode>
    </validate>
  </env:Header>
  <env:Body>
    <apiGetListDetails>
      <listID>72472</listID>
    </apiGetListDetails>
  </env:Body>
</env:Envelope>

This is the WSDL file: http://api.sendcockpit.com/server.php?wsdl
Am I missing something (maybe dead simple, super obvious, basic SOAP) stuff?

A: Never mind. Apparently I need a wrapping <ctListRequest> node. I was under the impression that savon applies all things specified by the wsdl file...
This request works:
<?xml version="1.0" encoding="UTF-8"?>
<env:Envelope xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:wsdl="Sendcockpit/API" xmlns:env="http://schemas.xmlsoap.org/soap/envelope/" xmlns:ins0="Sendcockpit/API">
  <env:Header>
    <validate>
      <userid>32027</userid>
      <apikey>***********</apikey>
      <version>1.0</version>
      <mode>live</mode>
    </validate>
  </env:Header>
  <env:Body>
    <apiGetListDetails>
      <ctListRequest>
        <listID>72472</listID>
      </ctListRequest>
    </apiGetListDetails>
  </env:Body>
</env:Envelope>


text:
Q: Redraw issue objective-c This is my problem:

The background of the progress indicator doesn't appear to be redrawing, and it's certainely not transparent.  I'm using core animation to animate the image in the background; when I don't use core animation it looks fine.  This is the code I am using:
    [[NSAnimationContext currentContext] setDuration:0.25];
    [[ViewImage animator] setAlphaValue:0.5f             ];
    [[statusText animator] setAlphaValue:0.1f            ];
    [progressIndicator usesThreadedAnimation             ];

The progress indicator doesn't use core animation.  I have also tried removing [progressIndicator usesThreadedAnimation]; which doesn't help.

A: -usesThreadedAnimation is the getter for the property. You want -setUsesThreadedAnimation: to set the property.
Also, for the transparency issue, I believe you need to switch on layers for at least the progress indicator if not the parent view as well. That should fix the transparency issue.


text:
Q: Union with nested list/multiple for loops I have a dictionary like so:
myDict = {'items':
            [{'names': [{'longName1', 'shortName1'},
                      {'shortName2', 'longName2'}]},
            {'names': [{'longName3', 'shortName3'},
                      {'shortName4', 'longName4'}]}]}

Attempting to get the keys (i.e. shortName) in a set Pythonically. I have the following statement, but it's complaining that i isn't defined. What am I doing wrong?
shortNames = set().union(*(j.values() for j in i["names"] for i in myDict["items"]))

Expected result:
set(['shortName1', 'shortName2', 'shortName3', 'shortName4'])

A: You are accessing i["names"] before i is defined by i in myDict["items"].

A: You have to swap the for loops:
set().union(*[j for i in myDict["items"] for j in i["names"]])

A: See, it is not advisable to chain list comprehensions just for the sake of brevity. Since you are asking, one way would be:
>>> from itertools import chain
>>> {j for j in (chain.from_iterable(sum([i['names'] for i in myDict['items']],[]))) if j.startswith('short')}

{'shortName1', 'shortName2', 'shortName3', 'shortName4'}

Your method could not work:

*

*As dacx mentioned.

*j.values() would not give you shortNames as those are inside sets not dicts, and sets do not have .values() method.

OR:
>>> {j for j in set().union(*(set().union(*i['names']) for i in myDict['items'])) if j.startswith('short')}
{'shortName1', 'shortName2', 'shortName3', 'shortName4'}


text:
Q: How to consume messages from JMS Topic in Java Yes, I have googled but it's very confusing to me. I want to continuously receive messages from a Topic (it's an oracle AQ topic) similar to the way that I use the MessageListener interface onMessage method for Queues. I can't seem to find a clear answer
With Queues - it's simple. Create an MDB publisher/producer class to send messages, and a Consumer class that implements MessageListener to receive messages. With Topics - there seems to be a different strategy when it comes to receiving.
I have tried examples that implement the MessageConsumer interface as well as MessageListener interface but nothing is really clear cut and nothing works for me. I have tried the subscriber.receive() method using MessageConsumer to create a durable subscriber on the topic session - not only does it not work but it only happens when you call the receive method, but I want something that will consume messages as and when they come.

A: Both MessageListener and MessageConsumer should work. With JMS topics it's important to understand that you must create the subscription before messages are sent. Any message sent to the topic before the subscription is created will not be dispatched to that subscription's consumer. Also, ensure you invoke start() on the Connection.


text:
Q: node istanbul code coverage with Jasmine producing an empty coverage folder I am running jasmine to test my code and it works fine.
In my package.json file I have this command:
"cover": "./node_modules/.bin/istanbul cover node_modules/.bin/jasmine-node unit_test"
where unit_test contains my jasmine spec.
For some reason when I run my coverage it runs my jasmine tests, produces an empty coverage folder and then hangs.
Does anyone know why please?

A: I doubt anyone will ever read this but I found a solution if youre facing the same problem.
Ensure your db connection is closing - istanbul will just hang forever and wait for all connections to close before doing anything.


text:
Q: iOS Google Maps Issue I developing a google maps application for IOS. I have a problem. I sent request to the google maps Then returns an empty. This issue has become the last 2 days. Please help me
Request:
http://maps.googleapis.com/maps/api/geocode/json?latlng=4.963404,52.337971&sensor=true
Result:
{
   "results" : [],
   "status" : "ZERO_RESULTS"
}

A: Did you mean to write
http://maps.googleapis.com/maps/api/geocode/json?latlng=52.337971,4.963404&sensor=true

4.963404, 52.337971 is in the middle of the indian ocean. The nearest valid address is thousands of kilometers away.


text:
Q: Source Tracked vs Non-Source-Tracked org What's the difference between these 2 kind of orgs?
It seems Trailhead Playgrounds orgs I am creating are non-source-tracked org and certain CLI commands can't be run against it.
How I can identify them, create a source tracking org and what exactly is the difference between them?
Thanks

A: Source tracking is available in scratch orgs, and, as of Summer '20, is in beta for Developer and Developer Pro sandboxes if the optional feature is enabled in Setup.
Source tracking makes it possible to use the sfdx force:source:pull and force:source:push commands (and their GUI equivalents), which automatically identify changed metadata components between your local source tree and the remote org.
Without source tracking, you must use manifest-based deployments using a package.xml manifest with commands like sfdx force:source:deploy. This entails creating and managing a manifest to define which specific components you wish to interact with.
Trailhead Playgrounds do not currently have source tracking. They are a type of Developer Edition org (not a sandbox). They can, however, be Dev Hubs, which allow you to create scratch orgs.


text: Q: How generate 200% image size and save with suffix @2x I need to know is it possible to generate 200%,200% image size and save with suffix @2x simply in WordPress? want to enable a simple retina ready theme.


text:
Q: console.log(data) to json file in javascript I'm working on one page with forms.
I need help with the JS script below
When I press SUBMIT I get data in console.log, but I want in json file on server, or xml data, but every time when I change something in the form to add new data in that file, not to create new file
Any help?

;(function($) {
  $.fn.toJSON = function() {
    var $elements = {};
    var $form = $(this);
    $form.find('input, select, textarea').each(function() {
      var name = $(this).attr('name')
      var type = $(this).attr('type')
      if (name) {
        var $value;
        if (type == 'radio') {
          $value = $('input[name=' + name + ']:checked', $form).val()
        } else if (type == 'checkbox') {
          $value = $(this).is(':checked')
        } else {
          $value = $(this).val()
        }
        $elements[$(this).attr('name')] = $value
      }
    });
    return JSON.stringify($elements)
  };
  $.fn.fromJSON = function(json_string) {
    var $form = $(this)
    var data = JSON.parse(json_string)
    $.each(data, function(key, value) {
      var $elem = $('[name="' + key + '"]', $form)
      var type = $elem.first().attr('type')
      if (type == 'radio') {
        $('[name="' + key + '"][value="' + value + '"]').prop('checked', true)
      } else if (type == 'checkbox' && (value == true || value == 'true')) {
        $('[name="' + key + '"]').prop('checked', true)
      } else {
        $elem.val(value)
      }
    })
  };
}(jQuery));

$(document).ready(function() {
  $("#_save").on('click', function() {
    console.log("Saving form data...")
    var data = $("form#test-form").toJSON()
    console.log(data);
    localStorage['form_data'] = data;

    return false;
  })

});

A: If you are using jQuery then you can easily serialise form like this:
$("form-selector").on("submit", function(event) {
    event.preventDefault();
    let form_data = $(this).serialize();
    console.log(form_data);
});

From your post, it is not totally clear what you want to do with the serialised form data. If you want to post that data to the server and save it as a file then this is a totally different topic. You didn't provide any info regarding your server-side technology - is it PHP, .NET, nodeJS, Python, ...
Well anyway... regardless your server-side technology you can post serialised data by jQuery's post method (https://api.jquery.com/jquery.post/):
let some_data = {field_name: 'Some name', field_surname: 'some surename', field_other: 'some other data'};
let jqxhr = $.post("http://example-host.com/service.php", some_data)
  .done(function() {
    console.log("success");
  })
  .fail(function() {
    console.log("error");
  })
  .always(function() {
    alert("finished");
  });

And altogether (client side JS):
$("form-selector").on("submit", function(event) {

    event.preventDefault();
    let form_data = $(this).serialize();
    console.log('Form data', form_data);

    let posting = $.post("http://example-host.com/service.php", form_data);

    posting.done(function() {
        console.log("Form data ajax post - success");
    });

    posting.fail(function() {
        console.log("Form data ajax post - error");
    });

    posting.always(function() {
        alert("Form data ajax post - finished");
    });

});

A: Already did serialize data from form
this is form
<form id="test-form"">

Scan Vehicle Barcode

Click the button next to the input-field to start scanning an barcode

                            <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarToggleExternalContent" aria-controls="navbarToggleExternalContent" aria-expanded="false" aria-label="Toggle navigation">

                            </button>

                        EAN:
                        <input id="isbn_input" class="isbn" type="text" name="barcode" />
                        <button type="button" class="btn btn-outline-success my-2 my-sm-0 scan"> Scan Barcode</button>

                            <input class="form-check-input" type="radio" name="vehiclecategory" id="inlineRadio1" value="CHASSIS">
                            CHASSIS

                            <input class="form-check-input" type="radio" name="vehiclecategory" id="inlineRadio2" value="SCATTOLINI">
                            SCATTOLINI

                            <input class="form-check-input" type="radio" name="vehiclecategory" id="inlineRadio3" value="VAN">
                            VAN

                            Position:
                            <select class="form-control" id="sel1" name="trainposition">
                                <option></option>
                                <option>A</option>
                                <option>B</option>
                                <option>C</option>
                            </select>

                            Wagon:
                            <select class="form-control" id="sel2" name="wagonposition">
                                    <option></option>
                                    <option>34</option>
                                    <option>35</option>
                                    <option>36</option>
                                    <option>37</option>
                                    <option>38</option>
                                    <option>39</option>
                                    <option>40</option>
                                    <option>41</option>
                                    <option>42</option>
                                    <option>43</option>
                                    <option>44</option>
                                    <option>45</option>
                                    <option>46</option>
                                    <option>47</option>
                                    <option>48</option>
                                    <option>49</option>
                                    <option>50</option>
                                    <option>51</option>
                                    <option>52</option>
                                    <option>53</option>
                                    <option>54</option>
                                    <option>55</option>
                                    <option>56</option>
                                    <option>57</option>
                                    <option>58</option>
                                    <option>59</option>
                                    <option>60</option>
                                    <option>61</option>
                                    <option>62</option>
                                    <option>63</option>
                            </select>

                    <input type='submit' id='_save' value='SUBMIT THE VEHICLE' class="btn btn-primary btn-lg">

</form>

Simple Barcode scanner and collecting some data.
All of this is working well, and my data is saved in console.log()
I want that data from console.log to be saved in some file like .json or .xml
server-side nodeJS
enter image description here
enter image description here


text:
Q: Using MiniTest, when trying to test `omniauth-google-oauth2` gem I keep getting a 302 redirect to my sign_in path I've setup omniauth-google-oauth2 gem with my rails application.  And it works but while I try to write my test for it I keep getting a 302 redirect.  Many of the website results I've seen reference how to test it in Rspec, but I'm trying to do it with MiniTest that comes with Rails.  Since I'm new to it I'm struggling seeing where I'm messing things up.
routes.rb
Rails.application.routes.draw do

  devise_for :users, controllers: { omniauth_callbacks: "users/omniauth_callbacks" }

  devise_scope :user do
      get 'sign_in', :to => 'devise/sessions#new', :as => :new_user_session
      get 'sign_out', :to => 'devise/sessions#destroy', :as => :destroy_user_session
    end

  root to: "home#index"

end

test_helper.rb
ENV['RAILS_ENV'] ||= 'test'
require_relative '../config/environment'
require 'rails/test_help'
require 'mocha/minitest'

class ActiveSupport::TestCase
  # Setup all fixtures in test/fixtures/*.yml for all tests in alphabetical order.
  fixtures :all

  def setup_omniauth_mock(user)
    OmniAuth.config.test_mode = true
      OmniAuth.config.mock_auth[:google_oauth2] = OmniAuth::AuthHash.new({
        provider: "google_oauth2",
        email: "#{user.email}",
        first_name: "#{user.first_name}",
        last_name: "#{user.last_name}"
      })
      Rails.application.env_config["devise.mapping"] = Devise.mappings[:user]
    Rails.application.env_config["omniauth.auth"] = OmniAuth.config.mock_auth[:google_oauth2]
  end

  def login_with_user(user)
    setup_omniauth_mock(user)
    get user_google_oauth2_omniauth_authorize_path
  end

end

module ActionController
    class TestCase
        include Devise::Test::ControllerHelpers
    end
end

module ActionDispatch
    class IntegrationTest
        include Devise::Test::IntegrationHelpers
    end
end

test/integration/login_with_google_oauth2_test.rb
require 'test_helper'

class LoginWithGoogleOauth2Test < ActionDispatch::IntegrationTest
  setup do
    @user = users(:one)
  end

  test "allows a logged-in user to view the home page" do
    login_with_user(@user)
    get root_path
    assert_redirected_to root_path
    assert_selector "h1", text: "#{user.full_name}"
  end

end

Error when running rails test
daveomcd@mcdonald-PC9020:~/rails_projects/haystack_scout$ rails test
Running via Spring preloader in process 24855
/home/daveomcd/.rvm/gems/ruby-2.5.1/gems/spring-2.0.2/lib/spring/application.rb:185: warning: Insecure world writable dir /home/daveomcd/.rvm/gems/ruby-2.5.1/bin in PATH, mode 040777
Run options: --seed 55919

# Running:

.....F

Failure:
LoginWithGoogleOauth2Test#test_allows_a_logged-in_user_to_view_the_home_page [/mnt/c/Users/mcdonaldd/Documents/Rails Projects/haystack_scout/test/integration/login_with_google_oauth2_test.rb:20]:
Expected response to be a redirect to <http://www.example.com/> but was a redirect to <http://www.example.com/sign_in>.
Expected "http://www.example.com/" to be === "http://www.example.com/sign_in".

bin/rails test test/integration/login_with_google_oauth2_test.rb:17

Finished in 0.238680s, 25.1383 runs/s, 50.2766 assertions/s.
6 runs, 12 assertions, 1 failures, 0 errors, 0 skips

A: So I've been able to figure out a means to testing omniauth-google-oauth2.  I'll do my best to show it below.  Thanks to anyone who took the time to look into my question.
test\integration\authorization_integration_test.rb
require 'test_helper'

class AuthorizationIntegrationTest < ActionDispatch::IntegrationTest
  include Capybara::DSL
  include Capybara::Minitest::Assertions
  include Devise::Test::IntegrationHelpers

    setup do
        OmniAuth.config.test_mode = true
        Rails.application.env_config["devise.mapping"] = Devise.mappings[:user]
        Rails.application.env_config["omniauth.auth"]  = google_oauth2_mock
    end

    teardown do
        OmniAuth.config.test_mode = false
    end

    test "authorizes and sets user currently in database with Google OAuth" do
        visit root_path
        assert page.has_content? "Sign in with Google"
        click_link "Sign in with Google"
        assert page.has_content? "Successfully authenticated from Google account."
    end

    private

        def google_oauth2_mock
            OmniAuth.config.mock_auth[:google_oauth2] = OmniAuth::AuthHash.new({
            provider: "google_oauth2",
            uid: "12345678910",
            info: {
                email: "fakeemail@gmail-fake.com",
                first_name: "David",
                last_name: "McDonald"
            },
            credentials: {
                token: "abcdefgh12345",
                refresh_token: "12345abcdefgh",
                expires_at: DateTime.now
            }
          })
        end

end


text:
Q: Is > higher than all others in the Java wildcard subtype hierarchy? I'm doing a review for a final tomorrow. I'm being asked to draw the subtype hierarchy of the following types. I want to make sure all the answers I've gotten are correct. I kept in mind generic rules regarding subtypes. Is this correct?

*

*List<?>, List<Integer>, List<Object>, List<Number>, List<? extends Number>, List<? super Number>

*Set<Integer>, List<String>, Object, Collection<Integer>, Collection<Object>, Collection<?>
My drawing:

A: This is actually rather complicated. See http://www.angelikalanger.com/GenericsFAQ/FAQSections/TechnicalDetails.html#FAQ207