text:
Q: How to merge two data frames with duplicate rows? I have two data frames df1 and df2. The df1 has repeated text wrt column name but column hobby changes. The df2 also has repeated text in the column name. I want to merge both the data frames and keep everything.
df1:
name   hobby

mike   cricket
mike   football
jack   chess
jack   football
jack   vollyball
pieter sleeping
pieter cyclying

my df2 is
df2:
name

mike
pieter
jack
mike
pieter

Now I have to merge df2 with df1 on name column
So my resultant df3 should look like this:
df3:
name   hobby

mike   cricket
mike   football
pieter sleeping
pieter cyclying
jack   chess
jack   football
jack   vollyball
mike   cricket
mike   football
pieter sleeping
pieter cyclying

A: You want to assign an order for df2, merge on name, then sort by the said order:
(df2.assign(rank=np.arange(len(df2)))
    .merge(df1, on='name')
    .sort_values('rank')
    .drop('rank', axis=1)
)

Output:
      name      hobby
0     mike    cricket
1     mike   football
4   pieter   sleeping
5   pieter   cyclying
8     jack      chess
9     jack   football
10    jack  vollyball
2     mike    cricket
3     mike   football
6   pieter   sleeping
7   pieter   cyclying


text:
Q: InDesign Server Crashing on Data Merge I'm trying to do a very basic data merge with InDesign Server and keep getting a crash.
I begin the server with ./InDesignServer -port 18383 starts with no problems.
I call the script with ./sampleclient ./scripts/test.jsx
The .jsx looks like this:

var source = File("/Users/me/Desktop/InDesign Server/example/example.indd")
var destination = File("/Users/me/Desktop/InDesign Server/example/example.pdf")
var sourceData = File("/Users/me/Desktop/InDesign Server/example/example.csv")
var doc = app.open(source);

doc.dataMergeProperties.selectDataSource(sourceData);
doc.dataMergeProperties.dataMergePreferences.recordNumber = 1;
doc.dataMergeProperties.mergeRecords(); // <-- Crashes here

var myPDFExportPreset = app.pdfExportPresets.item(0);
app.documents.item(0).exportFile(ExportFormat.pdfType, destination, false, myPDFExportPreset);
app.documents.item(0).close(SaveOptions.no);
doc.close(SaveOptions.no);

InDesign Server responds with:
Tue Sep 18 09:48:21 2018 INFO   [javascript] Executing Script
./InDesignServer: line 13: 30363 Segmentation fault: 11  "$installed_name" "$@"

And crashes. This script runs perfectly fine in InDesign CC Desktop. Server appears to crash on the .mergeRecords() call. Any ideas why?
Edit: I've modified the code to 1) Have no spaces in the file path 2) check that my objects all exist before performing the merge.

var source = File("/Users/me/Desktop/example/example.indd");
var destination = File("/Users/me/Desktop/example/example.pdf");
var sourceData = File("/Users/me/Desktop/example/example.csv");

var doc = app.open(source);
doc.dataMergeProperties.selectDataSource(sourceData);

if (source.exists && destination.exists && sourceData.exists) {
    try {
        app.consoleout("Performing merge...");
        doc.dataMergeProperties.mergeRecords(); // <-- Crashes here
    } catch (err) {
        app.consoleout(err);
    }
} else {
    app.consoleout("Something doesn't exist...");
}

It logs "Performing merge..." so my file paths do in fact point to files that exist. What's more, it full on crashes, and does not report any errors.
Edit 2:
It should be noted, this is the error the Terminal window which launched sampleclient gets from IDS: Error -1 fault: SOAP-ENV:Client [no subcode]
"End of file or no input: Operation interrupted or timed out"
Detail: [no detail]

A: The folks at Adobe took notice, and fixed this issue for the 2019 release of InDesign Server. The same script, with a similar merging document, no longer produces the error.
So, for a solution, update to 2019.
More information:
Adobe Forums Post

A: Found a solution, if others find themselves in my situation.
Still a mystery why mergeRecords() seems broken in Server.
doc.dataMergeProperties.exportFile()

Props to Colecandoo: https://forums.adobe.com/thread/2478708
My code is now:

var source = File("/Users/me/Desktop/example/example.indd");
var destination = File("/Users/me/Desktop/example/example.pdf");
var sourceData = File("Macintosh HD:Users:me:Desktop:example:example.csv");

var doc = app.open(source);
var myExport = File(doc.filePath + "/" + doc.name.split(".indd")[0] + ".pdf");
doc.dataMergeProperties.dataMergePreferences.recordNumber = 3;
with (doc.dataMergeProperties.dataMergePreferences) {
   recordSelection = RecordSelection.ONE_RECORD;
            }
   app.dataMergeOptions.removeBlankLines = true;
                doc.dataMergeProperties.exportFile(myExport, "[High Quality Print]", );

Still takes some tweaking, but it's performing the merge - this is what I needed.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Google Apps Script: Why are equal strings/values coming up as not equal I have equal strings coming up as not equal in a google apps script function and can't figure out why. Other answers to this question on the forum are in other languages I don't understand yet. Here's the code:
function testForMatch() {
  var ss = SpreadsheetApp.getActive();
  var masterSheet = ss.getSheetByName('Leaderboard');
  var masterLength = masterSheet.getMaxRows() - 3;
  var masterData = masterSheet.getRange(4, 2, masterLength).getValues();      //gets all the student names from the leaderboard

  var titleSheet = ss.getSheetByName('Title - Standard scores');
  var titleLength = titleSheet.getMaxRows() -3;
  var titleData = titleSheet.getRange(4, 2, titleLength).getValues();    //gets all the student names from the standard score sheet

  for ( i = 0; i < masterLength; i ++) {
    if(masterData[i] != titleData[i]) {
      var row = i + 1;
      var error = "Uh oh! It looks like " + masterData[i] + " and " + titleData[i] + " do not match in row " + row;
      var ui = SpreadsheetApp.getUi();
      var response = ui.alert(error);
    }
  }
}

even if I just type simple strings into the matching cells it tells me they don't match. Likewise for numbers.
Only thing I can think is that my script isn't actually comparing the values. If that's true, how do I get it to do that?
Thanks for helping!

A: if(masterData[i][0] != titleData[i][0]) {
...would compare the cell values


text:
Q: I have a long list of dataframe and want to convert each to numpy array X1,X2,X3 given pandas dataframes df1,df2,df3 in python using for loop I have a long list of pandas dataframes. The need for me is to get numpy array X1 for dataframe df1, numpy array X2 for dataframe df2, numpy array X3 for dataframe df3 without doing it one after the other.
i.e
X1=df1.values
X2=df2.values
X3=df3.values

Using for loops comes to mind. Anyone can help with this?
example dataframe:
import pandas as pd

df1=pd.DataFrame({'number':[1,2,3],'color':['Red','Green','Blue'],'symbol':['R','G','B']}

                ,columns=['number','color','symbol'])

df2=pd.DataFrame({'number':[4,5,6],'color':['Black','Yellow','Orange'],'symbol':['B','Y','O']}

                ,columns=['number','color','symbol'])

df3=pd.DataFrame({'number':[7,8,9],'color':['Purple','White','Violet'],'symbol':['P','W','V']}

                ,columns=['number','color','symbol'])

A: Check if this works for you:
import pandas as pd
import numpy as np

df1=pd.DataFrame({'number':[1,2,3],'color':['Red','Green','Blue'],'symbol':['R','G','B']}

                ,columns=['number','color','symbol'])

df2=pd.DataFrame({'number':[4,5,6],'color':['Black','Yellow','Orange'],'symbol':['B','Y','O']}

                ,columns=['number','color','symbol'])

df3=pd.DataFrame({'number':[7,8,9],'color':['Purple','White','Violet'],'symbol':['P','W','V']}

                ,columns=['number','color','symbol'])

for i in range(1,4):
    globals()["X" + str(i)] = np.array(globals()["df" + str(i)])


text:
Q: how to have a hyperlink in custom web part property i am working on a custom web part property and my question is how can i have hyper-link(seen in the below image) or bold or italic text in the custom property for the web part?

A: Check out Tobias Zimmergren's post on the ToolPart:  http://www.zimmergren.net/archive/2008/11/29/how-to-custom-web-part-properties-toolpart.aspx


text:
Q: Displaying attribute labels instead of attribute names in Yii2 audit trail extension output I've installed an extension that displays database changes of curtain views. Audit_trail by bedezign.
It keeps all the changes in a table. There's a model field, a field field, etc.
"Model" field's values are like "app/model/Request".
"Field" field's values are field names.
I want to display field's labels instead of names.
I tried to implement it like this:
$m = $model->model;
return $m::getAttributeLabel($model->field);

I have the following error:

Calling unknown method: yii\web\View::attributeLabels()

I guess this is because my $m variable is not being understood as a class, but as a simple string. Is there any way I can get around this?

A: The method getAttributeLabel() is in the Model itself, and the input is a string.
http://www.yiiframework.com/doc-2.0/yii-db-baseactiverecord.html#getAttributeLabel()-detail

public string getAttributeLabel ( $attribute )

So try $model->getAttributeLabel('fieldName')


text:
Q: Using mRender with two data variables in jquery Datatables? I have several columns defined using datatables. I assign "mData" which I manipulate mRender to display. However, I would like to display two data variables in one column in order to create a link, something like this:
    {"mData": "foo",
     "mData2": "bar",
     "mRender": function(data, data2){
          return 'bar'; //
      }
    }

Is there a way to do this?

A: The mRender function is passed the data for the whole row.  So, you can access any property you want:
{
    mData: "bar",
    mRender: function(data, type, val) {
        switch (type) {
            case 'display':
                return '' + data.bar + '';
                break;
            // optionally, add case statements for 'sort', 'filter', and 'type'
            default:
                return data.bar;
                break;
        }
    }
}

A:                 'paging': true,
                'sort': true,
                'searching': true,
                'scrollY':70,
                "ajax": {
                    "url": '/Home/GetDept',
                    "type": "get",
                    "datatype" :"json"
                },
                "columns": [
                     { "data": "city", "autoWidth": true },
                     { "data": "postalcode", "autoWidth": true },
                     { "data": "adress", "autoWidth": true },

                     {
                         "data": "deptid",
                         "data": "namedept",
                         "width": "50px", "render": function (data, type, row, meta) {

                             return '' + row.namedept + ' ';
                         }
                     }

                ]
            })


text:
Q: A command to merge video and audio file using "ffmpeg" and remove the source files I want to merge audio and video using ffmpeg. I use following command but it keeps the input (source) files while I want to delete them after they were merged. I want to see if there is a command for that or not!
ffmpeg -i "a.avi" -i "a.wav" -y -acodec copy -vcodec copy "b.avi"

A: The same command adding && rm a.avi a.wav at the end.


text:
Q: Using underset and overset together I would like to use underset and overset together above and below the word. Current  output looks like this:
\begin{equation}
    v_t(j)=max^{N}_{i=1}v_{t-1}(i)a_{ij}b_j(o_t)
\end{equation}

I would like both the superset and the underset to be placed exactly above and below the max.

A: Welcome to TeX.SE!
As egreg pointed out in the comments, you can achieve what you want using \max_{i=1}^{N}, like so:
\documentclass[12pt]{article}
\usepackage{amsmath} % Only for the equation* environment

\begin{document}
  \begin{equation*}
    v_t(j) = \max_{i=1}^{N}v_{t-1}(i)a_{ij}b_j(o_t)
  \end{equation*}
\end{document}

A: Here is maybe an easier fix yet - just nest overset in underset, or the other way around, as in:
v_t(j)=\overset{N}{ \underset{i=1}{max}} \hspace{0.1cm} v_{t-1}(i)a_{ij}b_j(o_t)


text:
Q: Configure SQuirreL for DB2 How to configure SQuirreL for DB2 access.
In SQuirreL I do see two DB2 drivers. But they are both marked with an red X.
I checked with Start Page but did not find an easy solution :/

A: *

*Download the DB2 Driver from the IBM Website and extract the ZIP archive.
Optionally you may want to copy it from the DB2 Server installation path:
/opt/ibm/db2/V11.1/java/db2jcc4.jar

*Use db2jcc4.jar and copy it into the squirrel folder e.g. plugins/db2

*In der Driver in the tab "Extra Class Path" add the db2jcc4.jar file

*Change the class name to com.ibm.db2.jcc.DB2Driver


text:
Q: JavaFX: How to setText of ComboBoxes and ToggleButtons in loop? I have a JavaFX application with a lot of ToggleButtons, ComboBoxes and TextFields organised in lists by their types. I have also a JSON file with list of my Member's class objects.
Ofcourse I have a @FXML adnotations buttons for buttons, etc.
When my app launch I want to set for everyone ToggleButton a specific Text what I have prepared in JSON file for specific Member. I planned to do this by using initialize() method to call my method fillToggleButtons():
List<Member> membersFromJSON = new ArrayList<>();
List<ToggleButton> sendToTeamMembers = new ArrayList<>();

private void fillToggleButtons() {

    Reader reader = null;
    try {
        reader = new FileReader(JSONFilePaths.membersJSONFilePath);
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    }
    Gson gson = new Gson();
    Type memberList = new TypeToken<ArrayList<Member>>() {}.getType();
    List<Member> members = gson.fromJson(reader, memberList);

    for (int i = 0; i < sendToTeamMembers.size(); i++) {
        for (int k = 0; k < members.size(); k++) {
                sendToTeamMembers.get(i).setText(members.get(k).getName());
        }
    }
}

But when I do this, my loops don't work. I have the same Text for everyone ToggleButton, but in JSON file I have them different. Do I need an ObservableList here instead of standard java List?
The same question for ComboBoxes (I know I should use index, also I have it in the same JSON file as Member's ID/index).
What should I do for set Text in loop for JavaFX objects?

A: Your loop logic is wrong - you're setting each ToggleButton's text multiple times (first to members.get(0).getName(), then to members.get(1).getName(), etc).
In the end, each ToggleButton will have its name set to the name of the last member from the list.
You only need one for loop:
for (int i = 0; i < sendToTeamMembers.size(); i++) {
    sendToTeamMembers.get(i).setText(members.get(i).getName());
}

Be sure to check if members list contains at least sendToTeamMembers.size() elements before you call the code above - and if it doesn't, there's probably some error with loading/parsing your JSON file that you'll need to fix first.


text:
Q: akka http mock (authorization) directive I'm trying to write unit testing to an akka-http server (route), but having trouble with the authorization directive.
I simply want to ignore (mock) the authorization directive.
A minimal version of my code:
object App {

    val logger: Logger = Logger[App]

    def main(args: Array[String]): Unit = {
        implicit val system: ActorSystem = ActorSystem("my-system")
        implicit val executionContext: ExecutionContextExecutor = system.dispatcher

        val service = new TestRoute()
        val bindingFuture = Http().bindAndHandle(service.route, "0.0.0.0", 8080)

        bindingFuture.onComplete {
            case Success(_) => println(s"listening on localhost:8080")
            case Failure(error) => println(s"failed: ${error.getMessage}")
        }
    }

    object TestRoute {

        def authorize: Directive1[JsObject] = extractCredentials.flatMap {
            case Some(OAuth2BearerToken(token)) => verifyToken(token) match {
                case Success(t) =>
                    logger.debug("token verified successfully")
                    provide(t)
                case Failure(t) =>
                    logger.warn(s"token is not valid: ${t.getMessage}")
                    reject(Rejections.validationRejection(t.getMessage))
            }
            case _ =>
                logger.warn("no token present in request")
                reject(AuthorizationFailedRejection)
        }

        def verifyToken(token: String): Try[JsObject] = {
            val source = Source.fromResource("public_production.pem")
            val fileData = try source.mkString finally source.close()
            JwtSprayJson.decodeJson(token, fileData, Seq(JwtAlgorithm.RS256))
        }
    }

    class TestRoute {
        val route: Route =
            TestRoute.authorize { jwtClaims =>
                println(jwtClaims)
                complete("sucess")
            }
    }
}

I want to test the Route in TestRoute. So authorize is the directive I want to mock. I simply want to control what authorize will return, without having to actually getting in the function.
My colleague suggested to wrap the Route in some kind of class that will take the authorize method as an argument, such that in the unit-test I can control it very easily. But I'm looking for the mock answer.
I saw some examples with Mockito, but none of them were compatible with my scalatest version, which is 3.1.0.


text:
Q: Excel Index and Match Function to verify data I have 2 spreadsheets of user data from 2 different systems.
I want to use a combination of conditions. I want to look for matches that contain 2 of the 3 conditions but it must include the C2 condition regardless.
So Ideally something like ...Match(A2&C2 OR B2&C2,'Old System'!A:A&'Old System'!B:B&'Old System'!I:I,0)),"")
This is the formula I am currently using but I have noticed it looks for matches of all 3 conditions rather than what I'm looking for.
=IFERROR(INDEX('Old System'!K:K,MATCH(A2&B2&C2,'Old System'!A:A&'Old System'!B:B&'Old System'!I:I,0)),"")
Just for context, here are the matching columns between the two systems
Old System K - $ amount paying in old system, New System A -> Old System A - User ID, New System B -> Old System B - Name, New System C -> Old System I - Payment Group Name

A: I would match the first and third column and then if that errored out match the second and third.
=IFERROR(INDEX('Old System'!K:K,IFERROR(MATCH(A2&C2,'Old System'!A:A&'Old System'!B:B,0),
                                  MATCH(B2&C2,'Old System'!A:A&'Old System'!B:B,0))),"")

You could also do this with an XLOOKUP if your version of Excel supports it.
XLOOKUP(A2&C2,'Old System'!A:A&Sheet2!B:B,Sheet2!K:K,
       XLOOKUP(B2&C2,'Old System'!A:A&'Old System'!B:B,'Old System'!K:K,""))


text:
Q: Multi thread program with Timer and Signals I am very newcomer to multi thread programming, so this question might seem a little silly ,  Follow is my code, I am trying to have 2 threads :
struct sigaction    S1,S2;
struct itimerval    T1,T2;

void Function1(){
    cout<<"Function1 "<<endl;
}
void Function2(){
    cout<<"Function2 "<<endl;
}

void Thread_Function(){
    int t=70000;
    memset (&s2, 0, sizeof (s2));
    s2.sa_handler = &Function2;

    sigaction (SIGALRM, &s2, NULL);

    sigemptyset(&s2.sa_mask);
    s2.sa_flags = 0;

    T2.it_value.tv_sec = 0;
    T2.it_value.tv_usec =t;
    T2.it_interval.tv_sec =0;
    T2.it_interval.tv_usec =t;
    setitimer (ITIMER_REAL, &T2, NULL);
}

int main(){

    int t=50000;
    memset (&s1, 0, sizeof (s1));
    s1.sa_handler = &Function1;

    sigaction (SIGALRM, &s1, NULL);

    sigemptyset(&s1.sa_mask);
    s1.sa_flags = 0;

    T1.it_value.tv_sec = 0;
    T1.it_value.tv_usec =t;
    T1.it_interval.tv_sec =0;
    T1.it_interval.tv_usec =t;
    setitimer (ITIMER_REAL, &T1, NULL);

    thread t1(Thread_Function);
}

Problem is Function1 does not execute in other words I cant see Function1 on my output

A: From the setitimer manual page

A process has only one of each of the three types of timers.

You are trying to have two timers of the same type, this is not possible.
If you want to have multiple timers another solution is required.

A: Signals don't work well with threads.
They also don't work per thread but per process. What you are doing is first setting the SIGALRM signal handler to Function1 then you start a thread and you then overwrite the handler to call Function2 instead.
Even if you would have per-thread signal handler a signal is send to the whole process. So one random thread will handle the signal and all the other threads wont.
You can specify which thread you want to handle the signal with pthread_sigmask. But in general mixing signals and multithreading does not work well at all.
Here you have some similar questions which may shine a light on this more. They may talk about pthread instead of std::thread but the issues there are the same.
Signal handling in pthreads
POSIX threads and signals


text:
Q: Custom 404 page won't allow additional edits I was able to follow these directions to implement a custom 404 page in SharePoint 2010.
I wanted to make additional formatting changes to the custom page after implementation. including fixing a broken image link. But none of the changes seem to take. I tried different browsers with different nonexistent links and they all show the original version of the custom page.

A: To set custom 404 - Page Not found, first implement your custom page and deploy it as farm solution in Layouts folder. Once you deploy it into layouts folder execute below powersheell command.
$webApp = Get-SPWebApplication http://test
$webApp.UpdateMappedPage([Microsoft.SharePoint.Administration.SPWebApplication+SPCustomPage]::Error,"/_layouts/1033/Custom_Error.html")
$webApp.Update()

This will update SharePoint default Page Not Found Error Page and sets your custom Page instead.
For more details: Click Here


text:
Q: Error parsing JSON: invalid character 'Â' looking for beginning of value while creating azure data factory source dataset I was trying to create a source data set which should point to one of the files in data lake gen2 using terraform. I was using below terraform code.
resource "azurerm_resource_group" "myresourcegroup" {
    name     = "${var.applicationName}-${var.environment}-rg"
    location = var.location
    tags = {
        environment = var.environment
    }
}

Linked service for ADLS gen 2
resource "azurerm_data_factory_linked_custom_service" "storagels" {
  name                 = "${var.applicationName}-${var.environment}-storagels"
  data_factory_id      = azurerm_data_factory.adf.id
  type                 = "AzureBlobFS"
  description          = "storage connection linked service"
  integration_runtime {
    name = azurerm_data_factory_integration_runtime_self_hosted.ir.name
  }
  type_properties_json = <<JSON
  {
        "url": "https://cdfstagesrg.dfs.core.windows.net",
            "accountKey": {
                "type": "AzureKeyVaultSecret",
                "store": {
                    "referenceName": "${azurerm_data_factory_linked_service_key_vault.akvls.name}",
                    "type": "LinkedServiceReference"
                },
                "secretName": "storageaccesskey"
            }
        },
       "connectVia":{
      "referenceName": "${azurerm_data_factory_integration_runtime_self_hosted.ir.name}",
      "type": "IntegrationRuntimeReference"
       }
JSON

  depends_on = [azurerm_data_factory_integration_runtime_self_hosted.ir]
}

Dataset creation
resource "azurerm_data_factory_custom_dataset" "datalakelookup" {
  name            = "${var.dataset_name}-datalakelkp"
  data_factory_id = azurerm_data_factory.adf.id
  type            = "LinkedServiceReference"

  linked_service {
    name = "${var.applicationName}-${var.environment}-storagels"

  }
  type_properties_json = <<JSON
  {
    "properties": {
        "linkedServiceName": {
            "referenceName": "${var.applicationName}-${var.environment}-storagels",
            "type": "LinkedServiceReference"
        },
        "annotations": [],
        "type": "Excel",
        "typeProperties": {
            "sheetName": "Datalake",
            "location": {
                "type": "AzureBlobFSLocation",
                "fileName": "tablesnames.xlsx",
                "folderPath": "caseact/Input",
                "fileSystem": "cdfstage"
            },
            "firstRowAsHeader": true
        },
        "schema": []
    }
}
JSON

    depends_on = [azurerm_resource_group.myresourcegroup,azurerm_data_factory.adf,azurerm_data_factory_integration_runtime_self_hosted.ir,azurerm_data_factory_linked_custom_service.clihive-linked-service]
}

All my resources are creating fine but at dataset creation it is giving error as : Error parsing JSON: invalid character 'Â' looking for beginning of value.
Update
I have used jsonencode function then getting different error.

A: Instead of using heredoc syntax for JSON, it would be a better idea to use jsonencode [1]. Here is an example of how you should change the first type_properties_json:
type_properties_json = jsonencode(
  "url" = "https://cdfstagesrg.dfs.core.windows.net"
  "accountKey" = {
     "type" = "AzureKeyVaultSecret"
     "store" = {
        "referenceName" = "${azurerm_data_factory_linked_service_key_vault.akvls.name}",
        "type" = "LinkedServiceReference"
      }
     "secretName" = "storageaccesskey"
    }
   "connectVia" = {
      "referenceName" = "${azurerm_data_factory_integration_runtime_self_hosted.ir.name}"
      "type" = "IntegrationRuntimeReference"
   }
)

Alternatively, I would suggest using the templatefile built-in function [2] in order to make sure you are providing the right values using Terraform interpolation syntax. So, this part from the jsonencode function call would go to a template file (let's call it storagels.tpl):
  "url" = "https://cdfstagesrg.dfs.core.windows.net"
  "accountKey" = {
     "type" = "AzureKeyVaultSecret"
     "store" = {
        "referenceName" = "${account_key_reference_name}",
        "type" = "LinkedServiceReference"
      }
     "secretName" = "storageaccesskey"
    }
   "connectVia" = {
      "referenceName" = "${connect_via_reference_name}"
      "type" = "IntegrationRuntimeReference"
   }

Then, in the type_properties_json, the templatefile function call would be inside of the jsonencode function call:
type_properties_json = jsonencode(templatefile("${path.root}/storagels.tpl",
  account_key_reference_name = azurerm_data_factory_linked_service_key_vault.akvls.name
  connect_via_reference_name = azurerm_data_factory_integration_runtime_self_hosted.ir.name
))

The path.root means that the template file storagels.tpl has to be in the same directory as the terraform code. More about the path variables can be found in [3].
NOTE: You would have to do something similar for the second JSON from your question.

[1] https://www.terraform.io/language/functions/jsonencode
[2] https://www.terraform.io/language/functions/templatefile
[3] https://www.terraform.io/language/expressions/references


text:
Q: Accessing inner child selector from unique parent in coffeescript/selenium I am writing a test in selenium using coffeescript.js and chai frameworks to select an inner child element where the parent has a unique class name.
The children elements are reused through the application and are not unique, so I need the parent's name to be used as a unique locator

portals-client__portals is the parent element I want to use to reference toggles__name
  "created_portal_in_super": {
    "xpath": "//span[contains(@class,'toggles__name')]"
  }

what is the correct way of nesting this?
I know for tables, something like tbody > tr > td can be used but I am not sure how to make this work in the above example.

A: Try to use this XPath:
//div[contains(@class, "portals-client__portals")]//span[@class="toggles__name"]

A: Css selector:
.portals-client__portals span.toggles__name


text:
Q: How to make the Python subprocess wait for some input when running through SLURM script? I am running some Python code using a SLURM script on a remote server accessed through SSH. At some point, issues related to licenses on the SLURM platform may happen, generating errors in Python and ending the subprocess. I want to use try-except to let the Python subprocess wait until the issue is fixed, after that it can keep running from where it stopped.
What are some smart implementations for that?
My most obvious solution is just keeping Python inside a loop if the error occurs and letting it read a file every X seconds, when I finally fix the error and want it to keep running from where it stopped, I would write something on the file and break the loop. I wonder if there is a smarter way to provide input to the Python subprocess while it is running through the SLURM script.

A: One idea might be to add a signal handler for signal USR1 to your Python script like this.
In the signal handler function, you can set a global variable or send a message or set a threading.Event that the main process is waiting on.
Then you can signal the process with:
kill -USR1 <PID>

or with the Python os.kill() equivalent.

Though I do have to agree there is something to be said for the simplicity of your process doing:
touch /tmp/blocked.$$

and your program waiting in a loop with a 1s sleep for that file to be removed. This way you can tell which process id is blocked.


text:
Q: ember filter on promised inside a model i have two models:
User:
export default DS.Model.extend({
  books: hasMany('book', { async: true }),
});

book:
export default DS.Model.extend({
  title: DS.attr('string'),
  state: DS.attr('number'),
});

in my of my controller i am getting one user as my model and i want to create a computed property like this
  activeBooks: Ember.computed('model.books', function() {
    var books = this.get('model.books').filter(function (book, index, array) {
      // debugger;
      return (this.get('book.state') === 1);
    }.bind(this));
    return books;
  }),

but the filter is not working and basically return a empty array.
P.S 1. i am side loading books alone with user. and at the debugger line i query for this.get('user.books.length')  i get the correct number of books for each user. could someone point out what i am doing wrong here?
thanks a lot!

A: You can use filterBy and return the result.
activeBooks:Ember.computed('model.books', function() {
 return this.get('model.books').filterBy('state',1);
})

You don't need to use bind(this) inside filter function.


text:
Q: loading xml node to a list that can be edit? im looking for a way to load data from my xml to  lists that i can edit the items and then load the changes back to the xml file;
<game id="1" name="animals" instruction=" instruction here ">
<words>
  <word wordName="Weasel" categoryCode="1" categoryName="Mammals" />
  <word wordName="Dog" categoryCode="1" categoryName="Mammals" />
  <word wordName="Cat" categoryCode="1" categoryName="Mammals" />
  <word wordName="Snake" categoryCode="2" categoryName="Reptiles" />
  <word wordName="Chameleon" categoryCode="2" categoryName="Reptiles" />
  <word wordName="agama" categoryCode="2" categoryName="Reptiles" />
  <word wordName="Chicken" categoryCode="3" categoryName="Birds" />
  <word wordName="Peacock" categoryCode="3" categoryName="Birds" />
  <word wordName="Pigeon" categoryCode="3" categoryName="Birds" />
</words>`

for example: then i load my page, there will be 5 lists, (2 of them will be empty at the moment), and the other 3 will be "mammals" "reptiles" and "birds". under each on of those will be a list of all the items other that list. under mammals: weasel, dog, cat and so on.
im looking for a way to let my user change everything, add 2 more nodes (there for the extra empty lists), change the wordName value, change the categoryName value, add more values etc...
anyone got any suggestions on how to make the list? which component can i use?
im programing in c# and on visual studio 2010.
thanks :)

A: You can start with:
XElement root = XElement.Load(file);

With the root node, you can then find the word children with:
IEnumerable<XElement> wordList = root.Decendants("word");

Then loop over the wordList view each XElement word to get data (there are plenty of examples of that here and elsewhere, just search for it).  And you can add more to any XElement with its .Add() method.  If you want to add it to the "words" element, you can search for that with:
XElement words = root.Element("words"); // if it is a first rank child or
XElement words = root.XPathSelectElement("//words[word]"); // if it is burried deeper

The //words[word] in XPathSelectElement means .Descendants("words") that has a child word.  To use XPathSelectElement you need to add the following using to your csharp file:
using System.Xml.XPath;

There are obviously other tricks, ways and means depending on your needs.  Good luck!


text:
Q: ChakraUI & Typescript custom theme I am new to ChakraUI and Typescript mixed together.
Following ChakraUI DOC I have created a file like this:
import { theme } from '@chakra-ui/core';

const customTheme = {
  ...theme,
  colors: {
    ...theme.colors,
    brand: {
      900: '#1a365d',
      800: '#153e75',
      700: '#2a69ac',
    },
  },
};

export default customTheme;

Unfortunately on customTheme I have a rid of these errors:
Exported variable 'customTheme' has or is using name 'ZIndices' from external module "/Users/username/project-test/node_modules/@chakra-ui/core/dist/theme/index" but cannot be named.ts(4023)
Exported variable 'customTheme' has or is using name 'Radii' from external module "/Users/username/project-test/node_modules/@chakra-ui/core/dist/theme/index" but cannot be named.ts(4023)
Exported variable 'customTheme' has or is using name 'Opacity' from external module "/Users/username/project-test/node_modules/@chakra-ui/core/dist/theme/index" but cannot be named.ts(4023)
Exported variable 'customTheme' has or is using name 'Borders' from external module "/Users/username/project-test/node_modules/@chakra-ui/core/dist/theme/index" but cannot be named.ts(4023)

Any hint?
Using:
TS: latest version
ChakraUI: latest version
Thank you in advance

A: this code should work for you:
import { extendTheme } from '@chakra-ui/react'

const customTheme = {
  ...theme,
  colors: {
    ...theme.colors,
    brand: {
      900: '#1a365d',
      800: '#153e75',
      700: '#2a69ac',
    },
  },
};

export default extendTheme(customTheme);

and then you can import this in _App.js  and add it in ChakraProvider like this:
<ChakraProvider theme={customTheme}>


text:
Q: Создаю панель управления сайтом на php Всем добрый день, может я дурак а может и просто делать нечего, но задался идеей создания панели управления для небольшого сайта, в целом функционал продуман, есть наброски решения разных функциональных моментов, но одно мне не ясно. Каким образом я могу при создании новости или статьи, прикрепить картинку? В целом все будет взаимодействовать с БД, все новости и тд будут храниться там, в теории можно было бы как-то загрузить через то же меню "создание новости" картинку, название и путь которой просто вставить в БД, для дальнейшего Echo через php. Интересны любые варианты, любые языки. Не знаю для чего, но прикреплю черновик функционала панели. Также понимаю что возможное решение где-то на поверхности, но все что можно было прогуглить я пытался, везде только готовые варианты, и поймите правильно, я не использую готовые CMS поскольку сама тема очень интересна, да и возможностей всегда больше когда делаешь сам (Ну или с помощью сеньоров Стака)

На данный момент в силах реализовать только пару вещей из задуманных, соответственно все что связано с записью в БД и последующего мониторинга для меня не сложно. Тут скорее отсутствует фундаментальное понимание как подобные вещи работают, например если я захочу прикрепить не 1 фотографию а целую галерею, это же должно быть заранее обозначено? Не стану же я в БД писать таблицу для каждой новости, ведь только в таком случае можно удобно и правильно безгранично подкреплять ссылки на фотки. Очень много что написал неправильно, прошу не ловить кринж, в данной теме меньше полугода.


text:
Q: Magentoo add slashes to file_name I try extend an core class.
But catch error:
Warning: include(
\\\\\\\\\\\\MyModule\Ajaxsearch\Model\Resource\Eav\Mysql4\Product\Collection
\\\\\\\\\\.php) [function.include]: failed to open stream:...
Why magento add slashes to addres? May be config error?

A: Try enabling magic_quotes_gpc by commenting the flag in the .htaccess file.


text:
Q: How to use variables in Wscript.Shell + cmd.exe? I'm trying to substitute variables to path in a wsh.run command (it should launch a batch file), but I got an error in the dos console: "The file name, directory name or volume label syntax is incorrect".
Here the code that works:
Sub TestDos()
Dim wsh As Object
Set wsh = VBA.CreateObject("WScript.Shell")
Dim fBatFile As String
Dim ErrorCode As Integer
Dim wkPath As String
Dim waitOnReturn As Boolean: waitOnReturn = True
Dim windowStyle As Integer: windowStyle = 1

wkPath = Application.ActiveWorkbook.Path
fBatFile = wkPath & "\run.bat"

ErrorCode = wsh.Run("cmd.exe /c cd /d G:\Projects && G:\Projects\run.bat", windowStyle, waitOnReturn)
Debug.Print ErrorCode

End Sub

I tried with:
ErrorCode = wsh.Run("cmd.exe /c cd /d wkPath && fBatFile", windowStyle, waitOnReturn)

Or:
ErrorCode = wsh.Run("cmd.exe /K cd /d " & wkPath & fBatFile & "", windowStyle, waitOnReturn)

but it doesn't work.
Anyone can help me, please?

A: I found the solution:

ErrorCode = wsh.Run("cmd.exe /c cd /d " & wkPath & " && " & fBatFile,
  windowStyle, waitOnReturn)

I can't find a clear webpage that explain when and how we need
'&' and "".
The official documentation is very obscure for me.
Anyway, even this time, it's done!
P.S.: If I use "cmd.exe /k" (I hold the dos console open), instead of '/c', the VBA Editor give me a "Overflow" error. Fortunately, I needed to close the dos console at the end of the batch file.


text:
Q: How to write console.log to a file instead Now I show the information using:
console.log (kraken.id, markets)

However, I want to write all the information that goes to the console to a file instead. How can that be done by completing the below code?
'use strict';
var ccxt = require('ccxt');

(async () => {
  let kraken = new ccxt.kraken()
  let markets = await kraken.load_markets()
  //console.log (kraken.id, markets)

  //How to write above console.log to file?
  const fs = require('fs');
  fs.writeFile("/Users/Andreas/Desktop/NODE/myproject/files/test.txt", "allinfoAsstring", function (err) {
    if (err) {
      return console.log(err);
    }

    console.log("The file was saved!");
  });
})()

A: thx for the diverse solutions.  the simplest way for me was
node app.js > app.log 2>&1
This would redirect stdout to a file named app.log and redirect stderr to stdout.
So all my console.log are going to app.log

A: You can try to create an Object out of your variables and format them as a JSON string.

/* ... */
const obj = {kraken, markets}

const fs = require('fs');
fs.writeFile("/Users/Andreas/Desktop/NODE/myproject/files/test.txt", JSON.stringify(obj), function(err) {
    if(err) {
        return console.log(err);
    }

    console.log("The file was saved!");
});

Later, you can retrieve the values from the file, by running

fs.readFile('/Users/Andreas/Desktop/NODE/myproject/files/test.txt', 'utf8', function(err, data) {
 const obj = JSON.parse(data)

 console.log("The data from the file is: " + obj)
})

A: You can use JSON.stringify(obj), every object can be convert into string via this method.

A: I recommend not using console.log in production as it sync code.
you can use winston instead
and you got in an easy way all the logs to file (if you wanted) by using new transports
const logger = winston.createLogger({
  level: 'info',
  format: winston.format.json(),
  defaultMeta: { service: 'user-service' },
  transports: [
    //
    // - Write to all logs with level `info` and below to `combined.log`
    // - Write all logs error (and below) to `error.log`.
    //
    new winston.transports.File({ filename: 'error.log', level: 'error' }),
    new winston.transports.File({ filename: 'combined.log' })
  ]
});

A: An addition to loicnestler's answer that means you don't need to change your 'console.log' statements:
Update the reference to 'console.log', so it calls 'writeFile' when logging:
const log = console.log;
console.log = (data) => {
    log(data);
    <loicnestler's writeFile logic>
}

A: In Node, console.log() calls util.inspect() to print objects.
You should call that directly and write it to a file.


text:
Q: Python Variable keeps resetting using actions.py I guys. I have made an actions.py file with several classes. What Im trying to do is that I want a variable (in this case its called flag) I want to set it at zero as default and change it through the function. For some reason it keeps resetting flag to 0 when flag is used in another function.
`
from typing import Any, Text, Dict, List

from rasa_sdk import Action, Tracker
from rasa_sdk.executor import CollectingDispatcher

# Import the getData module to fetch the data.
from dbConnect import getData
import dbConnect
import mysql.connector
flag = 0

class FindByLocation(Action):
    def name(self) -> Text:
        return "action_find_by_location"

    def run(self, dispatcher: CollectingDispatcher,
        tracker: Tracker,
        domain: Dict[Text, Any]) -> List[Dict[Text, Any]]:

    location = tracker.get_slot("location")
    price= tracker.get_slot("price")
    cuisine = tracker.get_slot("cuisine")
    print(location)
    # write the sql query here.
    query = "SELECT Name FROM Restaurant WHERE Location = '%s'" % location
    query3 = "SELECT COUNT(Name) FROM Restaurant WHERE Location = '%s' LIMIT 5" % location
    query2 = "CREATE VIEW LocationView AS SELECT RestaurantID, Name, PhoneNumber, Rating, PriceRange, Location, Sublocation FROM Restaurant WHERE Sublocation = '%s'"%(location)

    #pass the sql query to the getData method and store the results in `data` variable.
    var_location = getData(query)
    print(var_location)
    if not var_location:
        flag = 1
        var_sublocation = getData(query2)
        dispatcher.utter_message(text="یہ جگہ کس ایریا میں ہے")
    else:
        if cuisine is not None:
            count = getData(query3)
            dispatcher.utter_message(text="Find By Location",json_message=var_location)
            dispatcher.utter_message(text="Results found",json_message=count)
            dispatcher.utter_message(text="آپ کس پرائس میں کھانا پسند کریں گے")
        else:
            count = getData(query3)
            dispatcher.utter_message(text="Find By Location",json_message=var_location)
            dispatcher.utter_message(text="Results found",json_message=count)
            dispatcher.utter_message(text="آپ کس طرح کا کھانا پسند کریں گے؟")

        return[]

class FindBySublocation(Action):
    def name(self) -> Text:
        return "action_find_by_sublocation"

def run(self, dispatcher: CollectingDispatcher,
        tracker: Tracker,
        domain: Dict[Text, Any]) -> List[Dict[Text, Any]]:
    flag = 1
    print("FLAG VALUEEEEEE")
    print(flag)
    location = tracker.get_slot("location")
    query = "SELECT Name, Rating FROM LocationView WHERE Location = '%s'" % (location)
    query2 = "SELECT COUNT(Name), Rating FROM LocationView WHERE Location = '%s'" % (location)

    location = getData(query)
    location_count = getData(query2)
    dispatcher.utter_message(text="Sublocation Restaurants Found",json_message=location)
    dispatcher.utter_message(text="Results found",json_message=location_count)
    dispatcher.utter_message(text="آپ کس طرح کا کھانا پسند کریں گے؟")

    return[]

class FindByCuisineAndLocation(Action):
    def name(self) -> Text:
        return "action_find_by_location_and_cuisine"

def run(self, dispatcher: CollectingDispatcher,
        tracker: Tracker,
        domain: Dict[Text, Any]) -> List[Dict[Text, Any]]:

    cuisine = tracker.get_slot("cuisine")
    location = tracker.get_slot("location")
    print(cuisine)
    print(location)
    print("flag value in Cuisine and Location")
    print(flag)
    # write the sql query here.
    if flag==0:
        query = "Select Name, Rating From Restaurant Where Location = '%s' AND RestaurantID IN (SELECT RestaurantID FROM Cuisine WHERE Name = '%s') LIMIT 5" % (location,cuisine)
        query2 = "Select COUNT(Name), Rating From Restaurant Where Location = '%s' AND RestaurantID IN (SELECT RestaurantID FROM Cuisine WHERE Name = '%s') LIMIT 5" % (location,cuisine)
    else:
        query = "Select Name, Rating From LocationView Where Location = '%s' AND RestaurantID IN (SELECT RestaurantID FROM Cuisine WHERE Name = '%s') LIMIT 5" % (location,cuisine)
        query2 = "Select COUNT(Name), Rating From LocationView Where Location = '%s' AND RestaurantID IN (SELECT RestaurantID FROM Cuisine WHERE Name = '%s') LIMIT 5" % (location,cuisine)

    #pass the sql query to the getData method and store the results in `data` variable.
    location_cuisine = getData(query)
    location_cuisine_count= getData(query2)

    print("data: ",location_cuisine)

    dispatcher.utter_message(text="Find By Cuisine And Location ",json_message=location_cuisine)
    dispatcher.utter_message(text="Number of places ",json_message=location_cuisine_count)
    dispatcher.utter_message(text="آپ کس پرائس میں کھانا پسند کریں گے")

    return []

By the time my flag which should be changed to 1 after being executed in Sublocation (which it does according to the terminal) it is changed to 0 when used again in any other function especially find_by_location_and_cuisine
Thank you for your help!

A: If you want to use the global flag, use
global flag

in the function you want to use it.
If you don't mention this statement, the flag variable is considered as a local variable, i.e., a new local variable is created.


text:
Q: Running a whole scenario before another scenario I'm not able to figure out how to run a whole scenario before an other scenario, so that my test are not dependant on eachother.
I have this imaginary scenarios.
Scenario A
Given I have something
When I sumbit some data
I should see it on my webpage
Scenario B
Given SCENARIO A
When I delete the data
I should not see it on my webpage
When I run this scenario case, the software does not recognize Scenario A in scenario B, and ask me to create the step, like this...
You can implement missing steps with the snippets below:
@Given("^Registrere formue og inntekt$")
public void registrere_formue_og_inntekt() throws Throwable {
// Write code here that turns the phrase above into concrete actions
throw new PendingException();
}

A: You could either:

*

*Use a Background to group all the steps that need to be executed before the different scenarii:

Background:
Given I have something
When I submit some data
Then I should see it on my webpage

Scenario: B
When I delete the data
Then I should not see it on my webpage

*

*Group them as part of a step definition:

@Given("^Scenario A")
public void scenario_A() {
    I_have_something();
    I_submit_some_data();
    I_should_see_it_on_my_page();
}

which you can then use like this:
Given Scenario A
When I delete the data
Then I should not see it on my webpage

Using this technique, you usually observe that some actions are constantly reused, and you may want to factor them out so that they can be reused across different step definitions; at that point, the Page Object pattern comes very handy.

A: Cucumber scenarios are supposed to be independent. A lot of work is done assuming and ensuring that independence. Trying to go against will be an obstacle course.
Having said that, you could create your custom implementation of the Cucumber JUnit runner. Having this custom implementation, and by looking at the source of the original runner, you can expose / wrap / change the internals to allow what you want. For example with the following runner:
public class MyCucumber extends Cucumber {

    private static Runtime runtime;
    private static JUnitReporter reporter;
    private static List<CucumberFeature> features;

    public MyCucumber(Class<?> clazz) throws InitializationError, IOException {
        super(clazz);
    }

    @Override
    @SuppressWarnings("static-access")
    protected Runtime createRuntime(ResourceLoader resourceLoader,
            ClassLoader classLoader, RuntimeOptions runtimeOptions)
            throws InitializationError, IOException {
        this.runtime = super.createRuntime(resourceLoader, classLoader, runtimeOptions);
        this.reporter = new JUnitReporter(runtimeOptions.reporter(classLoader), runtimeOptions.formatter(classLoader), runtimeOptions.isStrict());
        this.features = runtimeOptions.cucumberFeatures(resourceLoader);

        return this.runtime;
    }

    public static void runScenario(String name) throws Exception {
        new ExecutionUnitRunner(runtime, getScenario(name), reporter).run(new RunNotifier());
    }

    private static CucumberScenario getScenario(String name) {
        for (CucumberFeature feature : features) {
            for (CucumberTagStatement element : feature.getFeatureElements()) {
                if (! (element instanceof CucumberScenario)) {
                    continue;
                }

                CucumberScenario scenario = (CucumberScenario) element;
                if (! name.equals(scenario.getGherkinModel().getName())) {
                    continue;
                }

                return scenario;
            }
        }

        return null;
    }

}

You can setup your test suite with:
@RunWith(MyCucumber.class)
public class MyTest {
}

And create a step definition like:
@Given("^I first run scenario (.*)$")
public void i_first_run_scenario(String name) throws Throwable {
    MyCucumber.runScenario(name);
}

It is a fragile customization (can break easily with new versions of cucumber-junit) but it should work.


text:
Q: Firebase DNS - Where to upload project (Deploy vs upload filezilla) I want to build a site with an angular environment, currently I have a static site with a domain bought on aruba.
I bought a custom domain with linux hosting but being static I use it to apply the new changes in production through Filezilla.
My doubt is that if I switch to firebase to run angular, do I have to deploy to Firebase? Or do I always have to upload via filezilla?
I think it's the first answer, as the site is uploaded via deploy and not on Aruba hosting, correct?
Another question: do you know how to unlink a domain from a firebase project? In the sense that if you wanted to remove the custom domain from a firebase project, just delete the project or do something else? I have not found any information about it.
Thank you so much in advance


text:
Q: Is it possible to toggle or reverse the direction of a css animation? As an example, lets say I have a wash that I want to go across a container when a user does something and reverse when they do it again, something like:
@keyframes wash{
  0%{clip-path: circle(0% at bottom left);}
  100%{clip-path: circle(150% at bottom left);}
}

@keyframes wash-reverse{
  0%{clip-path: circle(150% at bottom left);}
  1000%{clip-path: circle(0% at bottom left);}
}

.container.opening{
  animation : wash;
}

.container.closing{
  animation : wash-reverse;
}

If I want the container to start unaffected by the wash then I want to apply the "wash" to the container (using the opening css class) and then remove it (with the closing css class) is it possible to define a single animation and have a separate CSS rule that says "play the animation backwards"?
I've tried the animation-direction : reverse but I can't get it to work.
A JS fiddle of a working (Chrome only) example where you click on the 'toggle' button to add and remove the wash, completed by defining both animations distinctly, is here:
http://jsfiddle.net/errumm/c7ojz7r6/1/

A: Try to change the solution by using translation instead of key-frames.
Config a translation on 'clip-path'. Change the logic of toggle button to add/remove 'in' class.
.adl-modal{
 -webkit-clip-path: circle(0 at bottom left);
}

.adl-modal.in{
 -webkit-clip-path: circle(150% at bottom left);
}


text:
Q: Pushing an OR into the node check To do an OR on two different nodes, I can do the following:
//C:Year[not(@value="2019")] | //R:Year[not(@value="2019")]

However, if there is a long expression, this becomes a bit unwieldy, especially if there are more than 2 ORs. Is there a way to do something like the following:
//(C:Year or R:Year)[not(@value="2019")]

Basically, is it possible rather than evaluate the full axis-node-predicate expression and OR-ing the full thing, to be able to put an OR within the node test itself.

A: This (only) works in XPath 2.0+
//(C:Year | R:Year)[not(@value="2019")]

But, unfortunately, not in XPath 1.0.
The W3C XPath 1.0 language reference states under 3.1:

Parentheses may be used for grouping.
[14] Expr        ::= OrExpr
[15] PrimaryExpr ::= VariableReference | '(' Expr ')' | Literal | Number | FunctionCall

However /steps/ (*StepExpr) are not mentioned.
But the XPath 2.0 ref states:

Parentheses must be used when "/" is used on the left hand side of
an operator, as in "(/) * 5".

With this hint I came up with this query that also works in XPath 1.0:
((//C:Year)|(//C:Year))[not(@value="2019")]

So, v2+ is more flexible but the same principle applies. Gustafson, M. Kay, and others discussed an XPath 2.0 bug long this lines leading to Errata XP.E3. D. Chamberlin:

On July 31, 2007, the Query and XSLT working groups agreed to add
parentheses to the expansions of leading-/ and leading-// in path
expressions, as suggested by this bug report. The revised expansions
will appear in a future errata document. Regards, Don Chamberlin (for
the joint working groups)


text:
Q: AppStore - Application runtime Validation ( Sign key in google ) lastly we receive a lot of cracked installs without jailbroken devices. The problem is enterprise distribution. Since a week I'm searching for one good solution, but I can't find any... The main problem is, it's a multiplayer based game so any hacks are destroying our game community.
I must say I'm desperate as it's really easy to crack the game with Rasticrac for example ( we did it in an hour). But we couldn't find any way to validate on the server if a client is running our legal app downloaded from AppStore or the one installed from the crack.
It's pretty easy on Google as we have SSL connection where we send encrypted Sign key, we decrypt it on server-side and compare to original sign key. If someone is using a modded version, the signing key is different.
We wanted to introduce the same verification on iOS... But we found that it's impossible to do...
Please help us, we strongly searching for a good solution, as we need it in our new productions as well.


text:
Q: SFHFKeychainUtils persistance I am using SFHFKeychainUtils for storing data in keychain.
My question is - once I delete the application from the background, does the data stay within the SFHFKeychainUtils? And if so, for how long?
Any guidance or reference would be appreciated. Thanks in advance.

A: Hey i am not working with this wrapper class but if this classes deal with keychain then it will be defiantly save the credential after delete application form BG even from device and re-install app. you can get that credential.
For more information about keychain services please refer this apple doc.
Apple also provide sample code.


text:
Q: How to show activity only to the user whom the post belongs to in Public activity gem what am trying to do is to use public activity gem to build a notification system i followed this railscast and everything worked just fine. I have a article and a comment model where users can comment on each others article and the user whom the article belongs to will get notified in their activity feed, but the problem here is that the activity page shows activity of all users, but now i want to show activity only to the specific person whom the article belongs to. Means if a user clicks on the activity button they will only see the activities that happened on there article. Is there any way to accomplish that ? Thanks in advance.
what i had tried till now, but it doesn't seems to work
activities_controller.rb
class ActivitiesController < ApplicationController
 def index
   @activities = PublicActivity::Activity.all.order("created_at desc")
                  .where(trackable_type: "Comment", owner_id: current_user.id, owner_type: "User")
 end
end

A: @activities = PublicActivity::Activity.order("created_at desc")
          .where(trackable_type: "Comment", owner_id: current_user.id, owner_type: "User")

Should work


text:
Q: An unusual trimmer resistor
I first thought that this component had failed from old age as its jacket was crumbling away. However the metal clamp attached to it about halfway down has a dimple presumably to make contact with the exposed coil, and has a wire heading off from it. My guess is it must be a type of trimmer resistor I haven't encountered before, where the clamp is snugged up once the appropriate value is found. Does this part have a reliable name? I'd like to look into them further.
For interest, I found it inside an old vacuum tube voltmeter that I'm being careful about before powering up.

A: These were common in vacuum tube electronics. They were referred to as a power resistor. I remember IRC as one brand and probably have a few around. Vacuum circuits consumed a lot more power (both voltage and current) then transistors and the components used had to be compatible. The one shown was set and cemented into place so it would not change adjustment. Tolerance of parts were not near as good as they are today. Just out of curiosity is that a Heath Kit or another do it yourself unit.

A: Adjustable power resistor. Here is an example of a current production unit. Here is another type.
The resolution is not very good on them, and the open element is not ideal, but they have their applications even today.


text:
Q: PHP: Button not proceeding to the next page under IF ELSE I have a question. I have a little problem using PHP regards the IF ELSE. I have a condition there where, when I choose in the dropdown is "All" the save button will be disabled, and it's working. But, when I choose the "Top" the save button is enabled yet it's not proceeding to the next page.
Before I place it in IF ELSE, the save button is working but then when I place it to the IF ELSE save button, is not proceeding in the next page.
Below is my code:
 $dropdown_value = (string)$_POST["id"];

if ($dropdown_value == 'All')
{
echo "<input type='submit' name='save' value='Save' disabled onClick='this.form.action='save_data.php'; this.form.submit()'>    ";
$all = mysql_query("SELECT fldBldgName FROM tblbuildings");
while ($row = mysql_fetch_array($all))
{

echo "
<input type='checkbox' name='play[]' class='chk_boxes1' value='" . $row['fldBldgName']."'>";
echo $row['fldBldgName'];"
";

}
}
else if ($dropdown_value == 'Top')
{
echo "<input type='submit' name='save' value='Save'  onClick='this.form.action='save_data.php'; this.form.submit()'>    ";
echo "
<input type='checkbox' class='checkall'> Check all
";
$top = mysql_query("SELECT fldBldgName FROM tblbuildings ORDER BY fldBldgName ASC LIMIT 30");
while ($row = mysql_fetch_array($top))
{
echo "
";
echo "
<input type='checkbox' name='play[]' class='chk_boxes1' value='" . $row['fldBldgName']."'>";
echo $row['fldBldgName'];"
";

echo "

";
}
}

A: I think you have a quote issue
onClick='this.form.action='save_data.php'; this.form.submit()'

I think the single quotes around save_data.php is ending your onClick. Since you are echoing this inside php double quotes, try something like
onClick=\"this.form.action='save_data.php'; this.form.submit()\"

so it is now
echo "<input type='submit' name='save' value='Save'  onClick=\"this.form.action='save_data.php'; this.form.submit()\">    ";


text:
Q: Compiling *.Rnw files with knitr --without Rstudio I would like to use knitr to create presentations that embed R objects and code.
For IT reasons I am restricted to vim, so i have found the available Rstudio+knitr examples fairly unhelpful.  The vim section of the knitr documents is also very skinny, and therefore unhelpful.
Is someone able to provide some guidance on how to compile a *.Rnw or *.Rmd file using knitr (or alternately point me to a decent online tutorial?) using some combination of vim, R, and the command line?
thanks in advance

A: Instead of going through Rstudio, you can use the functions in the knitr package directly. There are some options you can tweak, but to get started, all you have to do is call the knit() function on your .Rnw file:
library(knitr)
knit('my_input.Rnw')

If you're missing some of Rstudio's features, it's worth remembering that most of them are just making use of things that are already available in various R packages, so you can usually find a way to use them when you don't have Rstudio available.


text:
Q: reading file into a dictionary I was wondering if there is a way that i can read delimitered text into a dictionary. I have been able to get it into lists no problem here is the code:
def _demo_fileopenbox():
    msg  = "Pick A File!"
    msg2 = "Select a country to learn more about!"
    title = "Open files"
    default="*.py"
    f = fileopenbox(msg,title,default=default)
    writeln("You chose to open file: %s" % f)
    c = []
    a = []
    p = []

    with open(f,'r') as handle:
        reader = csv.reader(handle, delimiter = '\t')
        for row in reader:
            c = c + [row[0]]
            a = a + [row[1]]
            p = p + [row[2]]
        while 1:
            reply = choicebox(msg=msg2, choices= c )
            writeln( reply + ";\tArea: " + a[(c.index(reply))] + " square miles \tPopulation: " + p[(c.index(reply))] )

that code makes it 3 lists because each line of text is a country name, their area, and their population. I had it that way so if i choose a country it will give me the corrosponding information on pop and area. Some people say a dictionary is a better approach, but first of all i dont think that i can put three things into one spot int the dictionary. I need the Country name to be the key and then the the population and area the info for that key. 2 dictionaries could probably work? but i just dont know how to get from file to dictionary, any help plz?

A: You could use two dictionaries, but you could also use a 2-tuple like this:
countries = {}

# ... other code as before

    for row in reader:
        countries[row[0]] = (row[1], row[2])

Then you can iterate through it all like this:
for country, (area, population) in countries.iteritems():
    # ... Do stuff with country, area and population

... or you can access data on a specific country like this:
area, population = countries["USA"]

Finally, if you're planning to add more information in the future you might instead want to use a class as a more elegant way to hold the information - this makes it easier to write code which doesn't break when you add new stuff. You'd have a class something like this:
class Country(object):

    def __init__(self, name, area, population):
        self.name = name
        self.area = area
        self.population = population

And then your reading code would look something like this:
for row in reader:
    countries[row[0]] = Country(row[0], row[1], row[2])

Or if you have the constructor take the entire row rather than individual items you might find it easier to extend the format later, but you're also coupling the class more closely to the representation in the file. It just depends on how you think you might extend things later.
Then you can look things up like this:
country = countries["USA"]
print "Area is: %s" % (country.area,)

This has the advantage that you can add new methods to do more clever stuff in the future. For example, a method which returns the population density:
class Country(object):

# ...

    def get_density(self):
        return self.population / self.area

In general I would recommend classes over something like nested dictionaries once you get beyond something where you're storing more than a couple of items. They make your code easier to read and easier to extend later.
As with most programming issues, however, other approaches will work - it's a case of choosing the method that works best for you.

A: Something like this should work:
from collections import defaultdict

myDict = {}
for row in reader:
    country, area, population = row
    myDict[country] = {'area': area, 'population': population}

Note that you'll have to add some error checking so that your code doesn't break if there are greater or less than three delimited items in each row.
You can access the values as follows:
>>> myDict['Mordor']['area']
175000
>>> myDict['Mordor']['population']
3000000

A: the value of the dictionary can be a tuple of the population and area info. So when you read in the file you can do something such as
countries_dict = {}

for row in reader:
        countries_dict[row[0]] = (row[1],row[2])

A: data = []

with open(f,'r') as handle:
    reader = csv.reader(handle, delimiter = '\t')
    for row in reader:
        (country, area, population) = row
        data.append({'country': country, 'area': area, 'population': population})

Data would then be a list of dictionaries.
But I'm not sure that's really a better approach, because it would use more memory. Another option is just a list of lists:
data = list(csv.reader(open(f), delimiter='\t'))
print data
# [['USA', 'big', '300 million'], ...]


text:
Q: Linkedin Api how to get groups details through people search I need to get the groups of an user,
IN.API.Raw("/people-search:(people:(id,first-name,last-name,email-address,industry,summary,num-connections,headline,group-memberships:(group:(id)))?first-name=ramesh&last-name=kotha&count="+25).result(function(result, metadata) {
//got the details here
}

when i use result.values[0].person.groupMembership.group.id it is saying undefined.
How to get the groups of a user.

A: Nesting the requests to build the objects would work:
IN.API.Raw("/people-search:(people:(id,first-name,last-name,email-address,industry,summary,group-memberships,num-connections,headline))?first-name=ramesh&last-name=kotha&count="+25)
.result(function(result, metadata) {
     console.log(result);

     for(person in result.people.values){
        console.log(person);
       IN.API.Raw()
          .url("/people/" + result.people.values[person].id + "/group-memberships:(group:(id,name),membership-state)")

         .result(function(result, metadata){

            console.log(result);
          });

    }

})


text:
Q: iOS 13 : Space grouping separator changed We use NumberFormatter class to format some amounts in the app. Since we migrated on iOS 13, it seems that the groupingSeparator space used for the Locale fr_FR changed.
We have tests on formatted strings amounts such as :
var amount = "1000"
XCTAssertEqual(amount.formattedValue, "1 000,00")

On iOS < 13, This test succeeds. But if we launch test on iOS > 13, this test will fail.
The reason is because the type of space used for the groupingSeparator property of NumberFormatter in iOS 13 has changed so
1 000,00 will not be equal to 1 000,00 according the space grouping separator which is used.
Any idea to always use the correct space grouping separator according the current iOS version ?
Edit : We found that the used space on iOS 13 is now the NARROW NO-BREAK SPACE
Edit 2 : The currencyGroupingSeparator has also changed with the NNBSP, all currency grouping separator have been replaced with this new one.

A: Ok finally found a solution :

*

*Defined an extension of String which replace all new spaces of the string by the original white space.
public extension String {
    var originalWhiteSpaced: String {
            let narrowNonBreakingSpace = "\u{202F}"
            let nonBreakingSpace = "\u{00a0}"

        return self
            .replacingOccurrences(of: narrowNonBreakingSpace, with: " ")
            .replacingOccurrences(of: nonBreakingSpace, with: " ")
    }}

And use it in the tests :
func testIsFormattingOfAmountCurrencyCorrectWhenAmountIsNegative() {
    let actualResult = formatter.formatAmountCurrency(-123472).originalWhiteSpaced
    let expectedResult = "- 123 472,00 €"

    XCTAssertEqual(actualResult, expectedResult)
}


text:
Q: Sql Where statement dynamic with case I have a Stored Procedure where I pass a value of 0,1,2.
0= no where
1= Duration >0
2= Duration =0

select * from Table where case  when @duration =1 then Duration else 1
  end >0

this works however i can't get the other values to work. I've tried 3 case statements but only the last one works.
How can I get a dynamic where statement to work for 3 values?

A: I wouldn't use a case statement.  Just use boolean logic
select *
  from table
 where (@duration = 0)
    or (@duration = 1 and duration > 0)
    or (@duration = 2 and duration = 0)

A: Assuming I'm ready your question correctly, this should do the trick:
SELECT * FROM yourTable
WHERE (@whereType <> 1 OR Duration > 0)
AND   (@whereType <> 2 OR Duration = 0)

but be careful with this sort of construct if there table contains any significant number of rows: you will be forcing a table scan of yourTable unless you have other filtering clauses for which there are usable indexes.
Edit: Some will find Justin's answer clearer to read (the two acheive the same result), though I prefer to keep the OR clauses inside the brackets as I find the logic easier to follow especially when other filtering clauses are added. In either case the warning about index use and scanning holds.
For Large Tables
Neither this or the other arrangement is suitable for large tables (as your comments suggests you have noticed) unless there are other filtering clauses that dramatically limit the amount of rows the dynamic filter acts upon.
Within a stored procedure you have the option of ad-hoc SQL via EXEC:
SET @SQL = 'SELECT * FROM yourTable '
IF @whereType = 1 THEN @SQL = @SQL + 'WHERE Duration > 0'
IF @whereType = 2 THEN @SQL = @SQL + 'WHERE Duration = 0'
EXEC (@SQL)

Be very careful with this pattern. You can easily open yourself to injection attacks (though this example doesn't) with ad-hoc SQL.
See the article mentioned in Andy's answer for a very detailed discussion of the options available and the issues (with regard to performance, maintainability, and security) you might encounter with each. Erland's other articles are very useful, thorough, and well written too, see http://www.sommarskog.se/index.html (the first one, regarding dynamic SQL, is relevant here too).

A: See the article "Dynamic Search Conditions in T‑SQL" from Erland Sommarskog at http://www.sommarskog.se/dyn-search.html
This explains in detail your options for dynamic searching and the performance implications of doing so.


text:
Q: firebase functions save the file to firebase storage I am trying to generate a bundle in firebase functions and save it to firebase storage
exports.xyzUpdated = functions.firestore.document("xyz/{xyzID}").onWrite(async (change, context) => {
       const db = admin.firestore();
       const bucket = admin.storage().bucket("gs://xxx.appspot.com");// or empty or "xxx.appspot.com"

       const bundle = db.bundle(bundleName);
       const file = bucket.file(`bundles/${bundleName}.xyz`);
       const bundleBuffer = bundle.add(`queryName`, querySnapshot).build();

       await file.setMetadata({
              "Cache-Control": "public, max-age=86400, s-maxage=86400",
            });

       await file.save(bundleBuffer, {});
    });

I see an error in the cloud console:

Error: No such object: xxx.appspot.com/bundles/bundleName.xyz

What's wrong?
Thanks!

A: You are trying to set metadata for a file before that is uploaded. Try changing the order of the statements as shown below:
await file.save(bundleBuffer, {});

await file.setMetadata({
  "Cache-Control": "public, max-age=86400, s-maxage=86400",
});

Alternatively, you can also set metadata while saving the file itself withouy setMetadata like this:
await file.save(bundleBuffer, {
  metadata: {
    cacheControl: "public, max-age=172800",
  }
});


text:
Q: change default homepage in magento2 url only for mobile theme I have a module with 2 themes for mobile and desktop.
In the mobile theme I want to change the default homepage to another url.
So when the mobile detection it is activated instead to go to the default page to go to my module route magento.com/mylink
I can put a redirect in the a block and define this block in cms_index_index.xml but looks a bit "dirty".
Is it a way to reroute the mobile theme homepage directly ?

A: Get the mobile detect class from:
https://github.com/serbanghita/Mobile-Detect/blob/master/Mobile_Detect.php
I put it inside my helper folder and just changed the name, namespace and extended as a helper:
namespace Wirelesslogic\ComesConnected\Helper;
class MobileDetect extends \Magento\Framework\App\Helper\AbstractHelper
{
...

Create a module and add the following line in the di.xml file inside etc:
<preference for="Magento\Cms\Controller\Index\Index" type="Wirelesslogic\ComesConnected\Controller\Cms\Index" />

Following this sample create a folder call Cms in the controller folder with a index.php and add the following code:
<?php
namespace Wirelesslogic\ComesConnected\Controller\Cms;
use Magento\Framework\Controller\ResultFactory;
use Wirelesslogic\ComesConnected\Helper\MobileDetect;
use \Magento\Framework\App\Action\Action;
use \Magento\Framework\App\Action\Context;

class Index extends Action

{
    protected $resultFactory;
protected $mobileDetect;

public function __construct(
    Context $context,
    ResultFactory $resultFactory,
    MobileDetect $mobileDetect
)
{
    $this->resultFactory = $resultFactory;
    $this->mobileDetect = $mobileDetect;
    parent::__construct($context);
}

public function execute($coreRoute = null)
{
    $resultRedirect = $this->resultFactory->create(ResultFactory::TYPE_REDIRECT);
    if ($this->mobileDetect->isMobile()) {
        $resultRedirect->setPath('activate');
        return $resultRedirect;
    } else {
        $pageId = $this->_objectManager->get(
            \Magento\Framework\App\Config\ScopeConfigInterface::class
        )->getValue(
            \Magento\Cms\Helper\Page::XML_PATH_HOME_PAGE,
            \Magento\Store\Model\ScopeInterface::SCOPE_STORE
        );
        $resultPage = $this->_objectManager->get(\Magento\Cms\Helper\Page::class)->prepareResultPage($this, $pageId);
        if (!$resultPage) {
            /** @var \Magento\Framework\Controller\Result\Forward $resultForward */
            $resultForward = $this->resultForwardFactory->create();
            $resultForward->forward('defaultIndex');
            return $resultForward;
        }
        return $resultPage;
    }
    }
}

Clear cache, compile or what ever you need to do depending your env.
Work with routes some times require to delete some var folders so if is not responding delete the var content.

A: I believe the best way in this case will be using custom router. Here is an article about routing in Magento2 . Here is how to detect mobile And how to redirect... I think you'll easily google it. If no, let me know, I'll add this part


text:
Q: print students from a particular year using user input x = input("Enter a Filename: ")
try:
    o = open(x, "r")
    p = o.read()
    y = tuple(j.split() for j in p.splitlines())
    for v1,v2,v3,fname,*rest_of_name in y:
        print("{:<30} {:<10} {:<5} {:<5}".format(' '.join(rest_of_name) + ',' + fname, v1,v3, v2))
    b = int(input("Enter a year: "))
    if b == int(v2):
        print("{:<30} {:<10} {:<5} {:<5}".format(' '.join(rest_of_name) + ',' + fname, v1,v3, v2))

    o.close()
except IOError as e :
    print("File Does Not Exist")

Basically my code here imports a file of students and formats the layout so they are all neatly aligned in columns of name,regnum,degreescheme,year which is shown below
Simpson,Bart                   12345      G400  2
Simpson,Lisa                   12346      GH46  1
J Simpson,Homer                12347      G401  2
Grainger,Hermione              12348      H610  4
Potter,Harry                   12349      G400  3
Shmoikel Krustofski,Herschel   12350      G402  1

However, now i'm try to ask the user to input a year for example "2" and this should then only print:
Simpson,Bart                   12345      G400  2
J Simpson,Homer                12347      G401  2

A: import re
print re.findall(r"^.*[ ]"+str(x)+"[ ]*$,p)

You can try this.See demo.
https://regex101.com/r/iY3eK8/7
Or
import re
print [k for k in p.splitlines() if re.split(r" {2,}",k)[3]==str(x)]

A: x = input("Enter a Filename: ")
try:
    o = open(x, "r")
    p = o.read()
    y = tuple(j.split() for j in p.splitlines())
    for v1, v2, v3, fname, *rest_of_name in y:
            print ("{:<30} {:<10} {:<5} {:<5}.format(''.join(rest_of_name)) + ',' + fname, v1, v3, v2")
    year = input("Enter a year:")
    for v1, v2, v3, fname, *rest_of_name in y:
        if v2 == year:
            print ("{:<30} {:<10} {:<5} {:<5}.format(''.join(rest_of_name)) + ',' + fname, v1, v3, v2")
    o.close()
except IOError as e:
    print ("File Does Not Exist")


text:
Q: Using throws keyword and handling it in the main rather than handling it in the method in which it occurs If I add the throws keyword in the method signature and handle it in my main() inside my TestClass{}, is it a good approach or should I handle the exception in the method in which it occurs fooBar(), which approach is recommended or what are the trade-offs between the two. Sorry this question might seem a little weird, just a newbie in Java.
public class Foo {

    //private fields

    public Foo() {
        //ctor
    }

    //accessors and mutators

    //method that throws exception
    public void fooBar() throws FooBarException {
        throw new FooBarException();
    }

}

A: Generally, the scope of try block should be as small as possible.
public void fooBar(){
        try{
         //Lines that can through error
        }

        catch (FileNotFoundException e) {
            //Handle exception Here
            //e.printStackTrace();

        /*
         other code that will not throw any error
        */
    }

or if the whole block may throw the error then
    public void fooBar() throws FooBarException {

    }
    //Handle in the exception where you calling the method


text:
Q: How to put an image in AlertDialog? I have a ListView which displays list of images. When I click an image in that ListView I want to display the image in AlertDialog.
Using the following code I am able to get and display text form TextView in an AletDialog.
But I don't know how to display an image in an AlertDialog.
I referred many sources.But nothing helped.
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                @Override
                public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

                    TextView c = (TextView) view.findViewById(R.id.textViewname);
                    String value = c.getText().toString();

                    ImageView i = (ImageView) view.findViewById(R.id.imageView_temp);

                    new AlertDialog.Builder(uploadpage.this).
                            setTitle("title").
                            setMessage(value).
                            show();

                    dialog.show();
                }
            });

        }

My question is how to display(inside AlertDialog) the particular Image of a  ListVIew when it is clicked ?
I want to display the image or item which is clicked.
EDIT
01-24 14:31:26.504 17180-17180/com.example.prakash.pix91 E/AndroidRuntime: FATAL EXCEPTION: main
                                                                           Process: com.example.prakash.pix91, PID: 17180
                                                                           java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.res.Resources$Theme android.content.Context.getTheme()' on a null object reference
                                                                               at android.support.v7.app.AlertDialog.resolveDialogTheme(AlertDialog.java:108)
                                                                               at android.support.v7.app.AlertDialog$Builder.<init>(AlertDialog.java:285)
                                                                               at com.example.prakash.pix91.uploadpage$6.onItemClick(uploadpage.java:507)
                                                                               at android.widget.AdapterView.performItemClick(AdapterView.java:310)
                                                                               at android.widget.AbsListView.performItemClick(AbsListView.java:1145)
                                                                               at android.widget.AbsListView$PerformClick.run(AbsListView.java:3073)
                                                                               at android.widget.AbsListView$3.run(AbsListView.java:3910)
                                                                               at android.os.Handler.handleCallback(Handler.java:746)
                                                                               at android.os.Handler.dispatchMessage(Handler.java:95)
                                                                               at android.os.Looper.loop(Looper.java:148)
                                                                               at android.app.ActivityThread.main(ActivityThread.java:5443)
                                                                               at java.lang.reflect.Method.invoke(Native Method)
                                                                               at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:728)
                                                                               at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:618)

A: Create one layout file for your image and this to your alert dialog
 AlertDialog.Builder   alertdialog = new AlertDialog.Builder(getActivity());
     LayoutInflater inflaterr = (LayoutInflater)getActivity().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        View  viewtemplelayout= inflaterr.inflate(R.layout.imagefile, null);
      ImageView i = (ImageView) viewtemplelayout.findViewById(R.id.imageView_temp);//and set image to image view

         alertdialog.setView(viewtemplelayout);//add your view to alert dilaog
         alertdialog.show()

A: Your AlertDialog's layout should include an ImageView to display the image. When you instantiate your dialog, you will pass it the image view from the ListView.
ImageView image = new ImageView(getContext());
// Set the resource for the image view
// image.setBitmap(someImageBitmapFromListView);
// You can also set a drawable using setImageResource(Drawable drawable) on the ImageView
AlertDialog aDialog = new AlertDialog.Builder(getActivity())
        .setView(image)
        .setPositiveButton(android.R.string.ok,null)
        .setNegativeButton(android.R.string.cancel, null);
        .create();
aDialog.show();

Extracting the image from the ListView should be simple enough. If you only need to display the image, then the above code should get you started. If you want to display more then take a look at the official guide for creating custom dialogs.

A: You should create your custom layout like this.

AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(this);
LayoutInflater inflater = this.getLayoutInflater();
View dialogView = inflater.inflate(R.layout.your_custom_layout, null);
dialogBuilder.setView(dialogView);

ImageView imageview= (ImageView) dialogView.findViewById(R.id.edittext);
imageview.setImageResource(R.id.image1);
AlertDialog alertDialog = dialogBuilder.create();
alertDialog.show();

That's it.


text:
Q: $\frac{\mathbb Z[x]}{(x^2)}$ is a local ring? I would like to prove if $\frac{\mathbb Z[x]}{(x^2)}$ is local ring.  I think it do is a local ring, since $x^2 $ might be a maximal idea, but I do not how to express it, since I am trying to explore localization by myself. So I will really appreciate any help.  Thank you so much.

A: I like thinking of maximal ideals as maps to fields (this is really just a restatement of @KCd's comment). Any map out of $\mathbb{Z}[x]/(x^2)$ is determined where $1$ and $x$ are sent. Can you think of any maps from this ring to, say, a finite field? Is the size of the finite field relevant?


text:
Q: How do I check for valid images paths in jquery script? They aren't showing up I'm trying to use a zoom plugin for interactive maps
I put everything into the site and as far as I can tell the scripts are all working. There are no console errors so I'm guessing the problem is that the image paths are not correct because nothing except the containing div is showing up. Looking at it through firebug all I can see is the containing div and referenced css. . . Can someone tell me 1. what can I use to diagnose this? and 2. Why isn't anything showing up?
My page is here

A: You can use a HTTP traffic tool to figure out if the images are requested and served.
https://addons.mozilla.org/en-US/firefox/addon/6647/

A: The first thing I noticed was this error in firebug:
$("#map").zoommap is not a function

And to me, it looks like the map is the only thing not showing up.


text:
Q: RAID6 scrubbing mismatch repair? You can initiate a scrub of a mdadm array with echo 'check' > /sys/block/mdX/md/sync_action, and if a bad sector is found, it'll rewrite it automatically (from a mirror or from parity information for RAID5/6).
However if all blocks read successfully but are found to not be consistent, then this is regarded as a mismatch. In this case repair is complicated because mdadm cannot tell which mirror contains the correct data (RAID1/10) or whether it is data or parity that is corrupted (RAID5).
In theory this is not the case with RAID6 if I understand RAID6 correctly. Because double-parity exists, it should be possible to pinpoint where a single corruption is, whether it is data or parity.

*

*Is my understanding correct, should this be possible in theory?

*If correct, is mdadm able to repair this inconsistent data without guessing which block is corrupted?

A: It is possible in theory: the data+parity gives you three opinions on what the data should be; if two of them are consistent, you can assume the third is the incorrect one and re-write it based on the first two.
Linux RAID6 does not do this.  Instead, any time there is a mismatch, the two parity values are assumed to be incorrect and recalculated from the data values.  There have been proposals to change to a "majority vote" system, but it hasn't been implemented.
The mdadm package includes the raid6check utility that attempts to figure out which disk is bad in the event of a parity mismatch, but it has some rough edges, is not installed by default, and doesn't fix the errors it finds.

A: The raid6check utility from mdadm includes a repair mode since version 3.3 (released on 2013-09-03) (more precisely since this commit: https://git.kernel.org/pub/scm/utils/mdadm/mdadm.git/commit/?id=8a63c73123b9d022107c82bd684e17bf87bc081e)


text:
Q: How to load wordpress sidebar using AJAX I am using responsive design on my website. Everything is fine except for the fact that on a mobile phone, my website is just too long. There is just too much content for a mobile screen - too much vertical space gets taken up by the sidebar which contains a lot of widgets like popular posts and recent comments and many others.
To make the website smaller, I want the sidebar to not load at all if viewed from a small screen. And I don't want to apply display:hidden to the sidebar container. That would be stupid.
So the most efficient way would be to load the sidebar using AJAX and exclude it if the viewport is less than 800px wide.
Could anybody please tell me if this possible? If this can be done please give some examples and links to some tutorials. I have googled a lot for this but found just one tutorial which I think is not enough as I want to learn from several examples.

A: You can simply use WordPress function wp_is_mobile() in your theme, like so
<?php if( !wp_is_mobile() ) get_sidebar(); ?>


text:
Q: Transform Large XML files with XSLT I have a program that outputs reports in HTML format. On average, they are about 5-10 MB, but I have seen extreme cases where they are 500 MB. These reports are purely client side, there is no server involved here.
The problem is that the browser will hang until all the content is loaded, and sometimes will not even load the content. I am trying to find a solution where someone opening the report can always open it. The people opening the reports should be able to open them using the browser and any technology available in it.
I have come up with a solution that will open a report that was previously 100MB by having our program output xml, then transform it to html via xslt, but the user still needs to wait for the entire thing to load into memory. All the content is within these diff nodes are loaded into 2 rows of a table, and the order of them does not matter.
XML:
    <diff>
        <parent loc="some string"/>
        <right> content</right>
        <left> content </left>
    </diff>

The XSLT to do this transformation is below:
<xsl:for-each select="./diff">

    <xsl:value-of select="./parent/@loc"/>

    <xsl:if test="./left/text()">
        <xsl:value-of select="./left/text()"/>
    </xsl:if>
    <xsl:if test="not(./left/text())">
         <xsl:variable name="left">
             <xsl:apply-templates select="./left/*" mode="serialize"/>
         </xsl:variable>
         <xsl:value-of select="$left"/>
    </xsl:if>

    <xsl:if test="./right/text()">
        <xsl:value-of select="./right/text()"/>
    </xsl:if>
    <xsl:if test="not(./right/text())">
        <xsl:variable name="right">
            <xsl:apply-templates select="./right/*" mode="serialize"/>
        </xsl:variable>
    <xsl:value-of select="$right"/>
    </xsl:if>

</xsl:for-each>

I am wondering if there is a way to either load the file more quickly or to not wait for the whole table to get loaded into memory before displaying the page.
I do not want to load a javascript library to do this, as we don't want to worry about connectivity while viewing these reports and do not want to install a bunch of files on everyone's machine, but I can use some script within the xslt.
I know this is an odd scenario and isn't the ideal way to structure the app, but we do not have time to change the way we generate these reports.

A: My initial thought is to output a directory of html files. So if we begin with
/supersize500MB.html

To:
/container
    /first10percent.html
    /second10percent.html
    /third10percent.html
    ...

Then within the HTML you produce you can hardcode things like:
Last Page
Next Page

XSLT 2.0 has the capability to output several documents from a single input. A quick google gave this. The XSLT processor will have to load the entire input XML into memory but I assume that the output HTML will be produced in sequence. The overall effect should be that the browser does not have to load a 500meg source file, but a 50meg snippet of the whole.