text:
Q: Why the content of  is not refreshed afterb Ajax Action I am trying to update the contents of the dataTable after updating AJAX (triggering an Update request on DB)
in my program the user clicks on a commandLink or on a  to update an "odm.valide_manag1" field in the database (the request is executed with The Datatable changes the image (bullet) from red to green by testing this field unfortunately, this phase is not executed correctly the test always remains unchecked (no updating of the getter of the field)
I invoke the regeneration of the listodm object in the @PostConstruct, In the Getter, in the validation method, I changed the Scope without success
@ManagedBean
@ViewScoped // or RequestScoped
public class listeOdm {
    public static Logger log=  LogManager.getLogger(listeOdm.class.getName());
    private List<odm> listOdm= new ArrayList<odm>() ; // a changer vers ListDataModel

    private odmService odmservice = new odmServiceImpl();
    FacesContext fc = FacesContext.getCurrentInstance();
    HttpSession httpsession = (HttpSession) fc.getExternalContext().getSession(false);
    private String n_odm;
    private String operation;
    private HtmlDataTable dataTable;

    @PostConstruct
    public void initMyBean()
    {   listOdm=null;
        log.info("1- debut PostConstruct   :   "  );
        listOdm = odmservice.findByMatricule("1000"); /*(String) httpsession.getAttribute("Matricule")*/
        //listOdm = odmservice.findAll();
        log.info("1- PostConstruct NOMBRE DES ODM  :   " + listOdm.size()+ "   The Object Is "+ listOdm.hashCode());
        RequestContext.getCurrentInstance().update("basicDT");
        /*  if("edit".equals(getParam("operation")))
        {
            editOdm();
        }*/
    }

    public String getParam(String name)
    {
        Map<String, String> params=fc.getExternalContext().getRequestParameterMap();
        return params.get(name);
    }
    public void onValid_manag(RowEditEvent event)
    {
        odmservice.validManager(((odm) event.getObject()).getNum_odm());
       FacesMessage msg = new FacesMessage("Odm validée", ((odm) event.getObject()).getNum_odm());
       FacesContext.getCurrentInstance().addMessage(null, msg);
       // ((odm) event.getObject() ).setValide_manag1("2");
       // listOdm.clear();
       // listOdm = odmservice.findAll();
       listOdm = odmservice.findByMatricule("1000");
       log.info("2- on valid Method la nouvelle valeur de Valide_manage1 est :" + ((odm) event.getObject()).getValide_manag1());
       log.info("2- on valid Method  :   " + listOdm.size()+ "   The Object Is "+ listOdm.hashCode());
        RequestContext.getCurrentInstance().update("basicDT");
    }

        public void onCancel_manag(RowEditEvent event) {
              FacesMessage msg = new FacesMessage("Odm Non validée", ((odm) event.getObject()).getNum_odm());
            FacesContext.getCurrentInstance().addMessage(null, msg);
        }
    public void editOdm()
    {  // setN_odm(getParam("numOdm"));
       // setOperation(getParam("operation"));
        log.info("0- edit methode  :     "+getParam("numOdm"));
     odmservice.validManager(getParam("numOdm"));
        //listOdm = odmservice.findByMatricule("1000"); /*(String) httpsession.getAttribute("Matricule")*/
        log.info("edit de l'ODM  N°:   ");
       listOdm = odmservice.findByMatricule("1000");
    }
    public void modif()
    {    log.info("on Expand Start ");
         listOdm = odmservice.findByMatricule("1000");
    }
    public void printOdm()
    {}
    public List<odm> getListOdm() {
        log.info("getter list odm"+this.listOdm.hashCode());
        if (FacesContext.getCurrentInstance().getRenderResponse()) {
            log.info("getter list odm"+this.listOdm.hashCode());
            listOdm = odmservice.findByMatricule("1000");
        }
        return listOdm ;//= odmservice.findByMatricule("1000");
    }

    public void setListOdm(List<odm> listOdm) {
        this.listOdm=listOdm ;
    }

    public String getN_odm() {
        return n_odm;
    }

    public void setN_odm(String n_odm) {
        this.n_odm = n_odm;
    }

    public String getOperation() {
        return operation;
    }

    public void setOperation(String operation) {
        this.operation = operation;
    }

    public HtmlDataTable getDataTable() {
         dataTable.clearInitialState();
        return dataTable;
    }

    public void setDataTable(HtmlDataTable dataTable) {
        this.dataTable = dataTable;
    }

}

the Xhtml
<?xml version="1.0" encoding="ISO-8859-1" ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<h:head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1" />
<link href="//netdna.bootstrapcdn.com/font-awesome/4.0.3/css/font-awesome.css" rel="stylesheet"></link>
<title>Insert title here</title>

</h:head>
<h:body>
    <ui:debug />

     <h:form id="formulaire1">
     <h:inputHidden value="#{listeOdm.n_odm}" />
     <h:inputHidden value="#{listeOdm.operation}" />

    <h:dataTable  id="basicDT"    var="odm" value="#{listeOdm.listOdm}" binding="#{listeOdm.dataTable}"      >

       <h:column headerText="Etat" id= "bulet">

         <h:panelGroup rendered="#{odm.valide_manag1 eq '2'}">
         <h:graphicImage   library="img" name="if_bullet-green_44189.png" width="24" height="24" style="border-style: none"/>
         </h:panelGroup>
         <h:panelGroup rendered="#{odm.valide_manag1+odm.valide_manag2 eq '1'}">
          <h:graphicImage   library="img" name="orange.gif" width="24" height="24" style="border-style: none"/>
         </h:panelGroup>
          <h:panelGroup rendered="#{odm.valide_manag1+odm.valide_manag2 eq '0'}">
          <h:graphicImage   library="img" name="if_bullet-red_44191.png" width="24" height="24" style="border-style: none"/>
         </h:panelGroup>
         </h:column>
           <h:column headerText="valid">
            <h:outputText value="#{odm.valide_manag1}" />
        </h:column>
        <h:column headerText="Num Odm">
            <h:outputText value="#{odm.num_odm}" />
        </h:column>
        <h:column headerText="Client">
            <h:outputText value="#{odm.client}" />
        </h:column>
        <h:column headerText="Station">
            <h:outputText value="#{odm.station}" />
        </h:column>
         <h:column headerText="Destination">
            <h:outputText value="#{odm.destination}" />
        </h:column>
        <h:column headerText="date dep">
            <h:outputText value="#{odm.date_dep}" pattern="dd/MM/yyyy"/>
        </h:column>
        <h:column headerText="date retour">
            <h:outputText value="#{odm.date_ret}" pattern="dd/MM/yyyy"/>
        </h:column>
        <h:column headerText="Cient">
            <h:outputText value="#{odm.client}" />
        </h:column>
         <h:column headerText="Edit" width="24">

               <h:commandLink
                    actionListener="#{listeOdm.editOdm}" update=":formulair1:basicDT"   ajax="true">
                    <f:param name="numOdm" value="#{odm.num_odm}"></f:param>
                    <f:param name="operation" value="edit"></f:param>
                    <h:graphicImage   library="img" name="118805-128.png" width="24" height="24" style="border-style: none"/>

                </h:commandLink>
                <h:commandLink
                    actionListener="#{listeOdm.printOdm}" update="formulaire1">
                    <f:param name="numOdm" value="#{odm.num_odm}"></f:param>
                    <f:param name="operation" value="edit2"></f:param>
                    <h:graphicImage   library="img" name="Print-2-128.png" width="24" height="24" style="border-style: none"/>

                </h:commandLink>
        </h:column>

    </h:dataTable>

    </h:form>

</h:body>

JSF2.2.9 Tomcat 8.5

A: I have solved my problem  !!!!!.
I want to share this experience with beginners, because for an expert it is  obvious.
the rows of the DataTable are Objects, the execution of the  listner or the  command

 updates the record in the DB without updating the Datatable Row.
public void onValid_manag(RowEditEvent event)
{
   odmservice.validManager(((odm) event.getObject())); // herer was my error, before i passed a string  instead of the object  event.getObject().getNum_Odm
   listOdm = odmservice.findByMatricule("1000");
}

and in the methode invoking Hibernate Update i updated the record in the DB like this
public void validManager(String num_odm)
  {

     session.beginTransaction();
     Query q = session.createQuery("update odm set valide_manag1='2' where num_odm = :num_odm");
     q.setParameter("num_odm",num_odm);
     q.executeUpdate();
      session.getTransaction().commit();
    }

the correct method is :
public void validManager(odm odm) { //object in the selected row as parameter
     session.beginTransaction();
// updating the object in memory
     odm.setValide_manag1("2");
//hibernate execute the update query  in DB
     session.save(odm);
     session.getTransaction().commit();
}


text:
Q: A function whose declared type is neither 'void' nor 'any' must return a value. Returning a value from subscribe How it possible to return a value from subscribe? Below code throws exception

A function whose declared type is neither 'void' nor 'any' must return a value.

getNotificationType(_activatedRouter: ActivatedRoute):Observable<number>{
  _activatedRouter.params.subscribe(params => {
      const menuId = params['id'];
      if (menuId) {
         return this.masterDataService.getNotTypeByMenu(menuId).subscribe(res => {
             if (res){
              return res.notificationType;
             }
          })
      }
  });
}

A: First of all: It is not possible, since you are dealing with async operations.
One way to help you would be to asign the value to a field of your class inside the subscription and make your function of type void.
You seem to have a misunderstanding about Observables.
The Observable return type of your function does mean, that you need to return something that can be subscribed to, not the emitted value of your subscription.
If you do want to get the number in question you should first of all avoid subscribing to an observable inside an subsccription, since that is the perfect source for extensive memory leak. Maybe look into something like switchmap. Your code might first of all be changed into something like:
getNotificationType$(_activatedRouter: ActivatedRoute):Observable<number>{
   return _activatedRouter.params.pipe(
      switchmap(params => {
          const menuId = params['id'];
          if (menuId) {
             return this.masterDataService.getNotTypeByMenu(menuId);
          } else {
             throwError() // or whatever you need to do in your specific case possibly include a catch
          }
      }));
}

Since you are working with Observables it is best to subscribe as few times as humanly possible, since that eases your cleanup in the end.
For your specific case it would be helpful to know how you are using the number your want to receive.

*

*Is it fetched after it was already loaded before? ==> ShareReplay

*Is it displayed in your template? ==> Async pipe
...

Would you be so kind to share your specific use so we can tailor a specific solution for you?

redpajama_set_name: RedPajamaStackExchange


text:
Q: Bash loop for detecting equal folder sizes I would like to detect when the transfer of a large amount of files is completed. I would like to accomplish this by detecting the size of the folder with a time delay.
Below is what I have done,
  #!/bin/bash

firstSize= du -s /Users/test/Desktop/folder | cut -f1

sleep 3
newSize= du -s /Users/test/Desktop/folder | cut -f1

until [ $firstSize -eq $newSize ]
do
    firstSize=$newSize
    sleep 3
    newSize= du -s /Users/test/Desktop/folder | cut -f1

done

echo 'Done'

The until loop is not working because even when the firstSize and the newSize are not equal the loop completes. I am not familiar with writing Bash scripts so I am just making mistakes. This loop is ported over from an applescript I had wrote for the same purpose but I need something more reliable.

A: You messed the commands syntax. The script should look like:
#!/bin/sh -
firstSize=$(du -s /Users/test/Desktop/folder | cut -f1)
until
  sleep 3
  newSize=$(du -s /Users/test/Desktop/folder | cut -f1)
  [ "$firstSize" -eq "$newSize" ]
do
    firstSize=$newSize
done
echo 'Done'


text:
Q: How to save image in ImageView to DB and recall the image when activity starts I have an app where the user draws a picture and returns to my ImageView in my app.  The image is displayed and working. I then have a save button to save the entire form (with the Image), but when I click save and reopen the app the text is displayed but not the image.
Here is the code to enter the text in the database:
MainActivity.Class
EditText myName;
ImageView myImage;
EditText myJob;
byte[] myProf;
....

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    personID = getIntent().getIntExtra(FragmentJob.KEY_EXTRA_CONTACT_ID, 0);
    setContentView(R.layout.activity_edit);
    verifyStoragePermissions(this);

    DIRECTORY = Environment.getExternalStorageDirectory().getPath() + "/MYForm/";
    pic_name = new SimpleDateFormat("yyyyMMdd_HHmmss", Locale.getDefault()).format(new Date());
    StoredPath = DIRECTORY + pic_name + ".png";

....

myName = (EditText) findViewById(R.id.editMyName);
myImage = (ImageView) findViewById(R.id.myProfImage);
myJob = (EditText) findViewById(R.id.myJobAgeWorked);

....

dbHelper = new MyDBHelper(this);

    if (personID > 0) {
        saveButton.setVisibility(View.GONE);
        buttonLayout.setVisibility(View.VISIBLE);

        rs = dbHelper.getPerson(personID);
        rs.moveToFirst();
        String myNameIs = rs.getString(rs.getColumnIndex(MyDBHelper.MY_NAME));
        myProf = rs.getBlob(rs.getColumnIndex(MyDBHelper.MY_PROFILE));

   .....

int myAge = rs.getInt(rs.getColumnIndex(MyDBHelper.MY_JOB));
        if (!rs.isClosed()) {
            rs.close();
        }

        myName.setText(cmyNameIs);
        myName.setFocusable(false);
        myName.setClickable(false);

//I don't know if the below code works or not for "myImage"

        myImage.setImageDrawable(Drawable.createFromPath(myProf + StoredPath));
        myImage.setFocusable(true);
        myImage.setClickable(false);

        myJob.setEnabled(true);
        myJob.setFocusableInTouchMode(true);
        myJob.setClickable(true);

....

@Override
public void onClick(View view) {
    switch (view.getId()) {
        case R.id.saveButton:
            persistPerson();
            return;
        case R.id.editButton:
            saveButton.setVisibility(View.VISIBLE);
            buttonLayout.setVisibility(View.GONE);

            myName.setEnabled(true);
            myName.setFocusableInTouchMode(true);
            myName.setClickable(true);

            myImage.setEnabled(false);
            myImage.setFocusableInTouchMode(false);
            myImage.setClickable(false);

            myJob.setEnabled(true);
            myJob.setFocusableInTouchMode(true);
            myJob.setClickable(true);

....

//This is where I think I am going wrong

public void persistPerson() {
    if (personID > 0) {
        if (dbHelper.updatePerson(personID,
                myName.getText().toString(), //WORKS
                StoredPath.getBytes().toString(), //Not Sure that this is
                                                    correct
                Integer.parseInt(myJob.getText().toString()))) {

....

} else {
        if (dbHelper.insertPerson(
                myName.getText().toString(), //WORKS
                StoredPath.getBytes().toString(), //Not Sure that this is
                                                    correct
                Integer.parseInt(myJob.getText().toString()))) {

....

private static final int REQUEST_EXTERNAL_STORAGE = 1;
private static String[] PERMISSIONS_STORAGE = {
        Manifest.permission.READ_EXTERNAL_STORAGE,
        Manifest.permission.WRITE_EXTERNAL_STORAGE
};

 ***EDIT***
//persmission method.
public static void verifyStoragePermissions(Activity activity) {
    // Check if we have read or write permission
    int writePermission = ActivityCompat.checkSelfPermission(activity, Manifest.permission.WRITE_EXTERNAL_STORAGE);
    int readPermission = ActivityCompat.checkSelfPermission(activity, Manifest.permission.READ_EXTERNAL_STORAGE);

    if (writePermission != PackageManager.PERMISSION_GRANTED || readPermission != PackageManager.PERMISSION_GRANTED) {
        // We don't have permission so prompt the user
        ActivityCompat.requestPermissions(
                activity,
                PERMISSIONS_STORAGE,
                REQUEST_EXTERNAL_STORAGE
        );

    }
}

//THEN BELOW CODE IS FROM THE DRAWING PAD

mGetSign.setOnClickListener(new View.OnClickListener() {

        public void onClick(View v) {

            Log.v("tag", "Panel Saved");
            view.setDrawingCacheEnabled(true);
            mSignature.save(view, StoredPath);
            dialog.dismiss();
            Toast.makeText(getApplicationContext(), "Successfully Saved", Toast.LENGTH_SHORT).show();
            File f = new File(StoredPath);
            ImageView mImgView1 = (ImageView)findViewById(R.id.editMyName);
            Bitmap bmp = BitmapFactory.decodeFile(f.getAbsolutePath());
            mImgView1.setImageBitmap(bmp.createScaledBitmap(bmp, 620, 620, false));
        }
    });

This will show the text entered and image when the user selects get "drawing" button and drew a picture.  After this step when hitting the "save" button the text is saved and the image not.
The error is:
E/BitmapFactory: Unable to decode stream: java.io.FileNotFoundException: [B@cdfe4dd/storage/emulated/0/MYForm/20170615_114018.png: open failed: ENOENT (No such file or directory)

For my MyDBHelper.class
public static final String DATABASE_NAME = "SQLiteExample.db";
private static final int DATABASE_VERSION = 2;

public static final String PERSON_TABLE_NAME = "person";
public static final String PERSON_COLUMN_ID = "_id";
public static final String MY_NAME = "myfullname";
public static final String MY_PROFILE = "myprofileimage";

....

public ExampleDBHelper(Context context) {
    super(context, DATABASE_NAME, null, DATABASE_VERSION);
}

@Override
public void onCreate(SQLiteDatabase db) {
    db.execSQL(
            "CREATE TABLE " + PERSON_TABLE_NAME +
                    "(" + PERSON_COLUMN_ID + " INTEGER PRIMARY KEY, " +
                    MY_NAME + " TEXT, " +
                    MY_PROFILE + " BLOB, " +
                    MY_JOB + " INTEGER)"
    );
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
    db.execSQL("DROP TABLE IF EXISTS " + PERSON_TABLE_NAME);
    onCreate(db);
}

public boolean insertPerson(String mynameis,
                            String myprofimage,
                            int jobnumber) {

    SQLiteDatabase db = this.getWritableDatabase();
    ContentValues contentValues = new ContentValues();

    contentValues.put(MY_NAME, mynameis);
    contentValues.put(MY_PROFILE, myprofimage);
    contentValues.put(MY_JOB, jobnumber);

    db.insert(PERSON_TABLE_NAME, null, contentValues);
    return true;
}

 public int numberOfRows() {
    SQLiteDatabase db = this.getReadableDatabase();
    int numRows = (int) DatabaseUtils.queryNumEntries(db, PERSON_TABLE_NAME);
    return numRows;
}

public boolean updatePerson(Integer id,
                            String mynameis,
                            String smyprofimage,
                            int jobnumber) {

    SQLiteDatabase db = this.getWritableDatabase();
    ContentValues contentValues = new ContentValues();
    contentValues.put(MY_NAME, customername);
    contentValues.put(MY_PROFILE, signature);
    contentValues.put(MY_JOB, jobnumber);
    db.update(PERSON_TABLE_NAME, contentValues, PERSON_COLUMN_ID + " = ? ", new String[]{Integer.toString(id)});
    return true;
}

.....

I hope i made sense here :-)
Could some help me?

A: Add this permission in Android Manifest.
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

A:     you can save image as byte[] in database. take bitmap from your imageview and convert it to byte[] and then save in database.

    ex :

    yourimageView.buildDrawingCache();
    Bitmap bitmap = yourimageView.getDrawingCache();

    ByteArrayOutputStream stream=new ByteArrayOutputStream();
    byte[] imageData=stream.toByteArray();

now you can save imageData in database


text:
Q: Trying to get DB2 to enumerate databases I am trying to use DB2DataSourceEnumerator.GetDataSources("db2.windward.net", null, "username", "password") to return all databases on that server. When I make the call it takes about 10 seconds to return and then throws the following exception:

A connection attempt failed because the connected party did not
  properly respond after a period of time, or established connection
  failed because connected host has failed to respond 104.42.24.172:523

The documentation says:

To be visible, the remote database server instances must have a
  running database administration server (DAS), which is configured to
  respond to Search and Known Discovery requests.

I'm assuming that is the problem. How do I set this for the DB2 server? We have version 11 running on Windows.

A: You will have to have admin rights on your computer and the use these instructions to create DAS:

Enter db2admin create. If a specific user account is desired, you must use /USER: and /PASSWORD: when issuing db2admin create.

You can then see current config with command:
db2 get admin cfg

and update it with
update admin cfg

command.
Sources:
[1] http://www.ibm.com/support/knowledgecenter/SSEPGG_9.7.0/com.ibm.db2.luw.admin.gui.doc/doc/t0004960.html
[2] https://www.ibm.com/support/knowledgecenter/SSEPGG_9.7.0/com.ibm.db2.luw.admin.gui.doc/doc/t0005173.html
[3]
https://www.ibm.com/support/knowledgecenter/SSEPGG_9.7.0/com.ibm.db2.luw.admin.cmd.doc/doc/r0002023.html


text:
Q: MongoDB aggregation - grouping results by containing text I have objects of the following type:
"name":string,
"title": string,
"body": string

I need to perform aggregation query which looks for objects that contain specific text in one of fields. The results should be grouped by the following rules:

*

*First objects that their name contains text.

*Then objects that their title contains text.

*Then objects that their body contains text.

The first stage of the aggregation looks like this:
"$match" : {
                "$or" : [
                    {
                        "name" : /.*hellow world.*/i
                    },
                    {
                        "title" : /.*hellow world.*/i
                    },
                    {
                        "body" : /.*hellow world.*/i
                    }
                ]
            }

*

*Also, I'm using paging.

*The query being requested from node.js server.
My first problem is I still did not figure out whether it is possible at all to perform such a grouping in aggregation pipeline.
Also, I'm trying to perform three queries first to get results that their name contains term, then those that their title and then body. Using this method I have few other problems: three queries to a server not so efficient and also managing paging adds complexity to whole process.

A: You can use $facet to apply your criteria separately and then run $concatArrays to merge the results:
db.col.aggregate([
    {
        $facet: {
            name: [ { $match: { "name" : /.*hello world.*/i } } ],
            title: [ { $match: { "title" : /.*hello world.*/i } } ],
            body: [ { $match: { "body" : /.*hello world.*/i } } ],
        }
    },
    {
        $project: {
            data: {
                $concatArrays: [ "$name", "$title", "$body" ]
            }
        }
    }
])


text:
Q: What is the additive analogue of the word "factor"? When we have a bunch of numbers multiplied together like
$$b=a_1\,a_2\,a_3\,a_4,$$
we say that each $a_i$ is a factor of $b$.
What is the additive analogue of this terminology? That is, if
$$b=a_1+a_2+a_3+a_4,$$
how is $a_i$ called?

A: The additive analogue for multiplicative factors is summand.
An augend + addend = sum / total
Also summand + summand = sum
The equivalent of factorization could be called as summandization
For more information, check this out (https://en.wiktionary.org/wiki/summand)


text:
Q: Ошибка при парсинге Json с Retrofit 2 ApiInterface apiInterface = ApiClient.getClient().create(ApiInterface.class);
    Call<AdvertListResponse> call = apiInterface.getAdvertList();
    call.enqueue(new Callback<AdvertListResponse>() {
        @Override
        public void onResponse(Call<AdvertListResponse> call, Response<AdvertListResponse> response) {
            Log.i("ssss",""+response.body());
            AdvertListResponse listResponse = response.body();
            DataAdvertList dataAdvertList = listResponse.getDataAdvertLists().get(0);
            List<InfoAdvertList> advertList = dataAdvertList.getInfoAdvertLists();
            Log.i("ssss","advert"+advertList);
            boolean succes = dataAdvertList.isSuccess();
            if(succes){
                Log.i("ssss",""+succes);
                Realm realm = Realm.getDefaultInstance();
                realm.beginTransaction();
                realm.copyToRealmOrUpdate(advertList);
                realm.commitTransaction();
            }else {
                String error = dataAdvertList.getErrors().get(0);
                Toast.makeText(AdvertActivity.this,"error"+error,Toast.LENGTH_SHORT).show();
            }
        }

        @Override
        public void onFailure(Call<AdvertListResponse> call, Throwable t) {
            Log.i("ssss",t.toString());
            Toast.makeText(AdvertActivity.this,t.toString(),Toast.LENGTH_SHORT).show();
        }
    });

public class AdvertListResponse {
@SerializedName("data")
@Expose
private List<DataAdvertList> dataAdvertLists = new ArrayList<DataAdvertList>();

public List<DataAdvertList> getDataAdvertLists() {
    return dataAdvertLists;
}

public void setDataAdvertLists(List<DataAdvertList> dataAdvertLists) {
    this.dataAdvertLists = dataAdvertLists;
}

}
public class DataAdvertList {

@SerializedName("success")
@Expose
private boolean success;
@SerializedName("object")
@Expose
private List<InfoAdvertList> infoAdvertLists;
@SerializedName("errors")
@Expose
private List<String> errors;

public boolean isSuccess() {
    return success;
}

public void setSuccess(boolean success) {
    this.success = success;
}

public List<InfoAdvertList> getInfoAdvertLists() {
    return infoAdvertLists;
}

public void setInfoAdvertLists(List<InfoAdvertList> infoAdvertLists) {
    this.infoAdvertLists = infoAdvertLists;
}

public List<String> getErrors() {
    return errors;
}

public void setErrors(List<String> errors) {
    this.errors = errors;
}

}
public class InfoAdvertList extends RealmObject{
@PrimaryKey
@SerializedName("id")
@Expose
private String id;
@SerializedName("cat_id")
@Expose
private String catId;
@SerializedName("is_dogovornaja")
@Expose
private String isDogovornaja;
@SerializedName("is_obmen")
@Expose
private String isObmen;
@SerializedName("description")
@Expose
private String description;
@SerializedName("email")
@Expose
private String email;
@SerializedName("city_id")
@Expose
private String cityId;
@SerializedName("address")
@Expose
private String address;
@SerializedName("phone1")
@Expose
private String phone1;
@SerializedName("phone2")
@Expose
private String phone2;
@SerializedName("phone3")
@Expose
private String phone3;
@SerializedName("phone4")
@Expose
private String phone4;
@SerializedName("phone5")
@Expose
private String phone5;
@SerializedName("coords")
@Expose
private String coords;
@SerializedName("is_new")
@Expose
private String isNew;
@SerializedName("mark_id")
@Expose
private String markId;
@SerializedName("model_id")
@Expose
private String modelId;
@SerializedName("user_id")
@Expose
private String userId;
@SerializedName("price")
@Expose
private String price;
@SerializedName("created")
@Expose
private String created;
@SerializedName("status")
@Expose
private String status;
@SerializedName("is_favourite")
@Expose
private Integer isFavourite;
@SerializedName("modelname")
@Expose
private String modelname;
@SerializedName("markname")
@Expose
private String markname;
@SerializedName("photos")
@Expose
private RealmList<PhotoAdvert> photos;

public String getId() {
    return id;
}

public void setId(String id) {
    this.id = id;
}

public String getCatId() {
    return catId;
}

public void setCatId(String catId) {
    this.catId = catId;
}

public String getIsDogovornaja() {
    return isDogovornaja;
}

public void setIsDogovornaja(String isDogovornaja) {
    this.isDogovornaja = isDogovornaja;
}

public String getIsObmen() {
    return isObmen;
}

public void setIsObmen(String isObmen) {
    this.isObmen = isObmen;
}

public String getDescription() {
    return description;
}

public void setDescription(String description) {
    this.description = description;
}

public String getEmail() {
    return email;
}

public void setEmail(String email) {
    this.email = email;
}

public String getCityId() {
    return cityId;
}

public void setCityId(String cityId) {
    this.cityId = cityId;
}

public String getAddress() {
    return address;
}

public void setAddress(String address) {
    this.address = address;
}

public String getPhone1() {
    return phone1;
}

public void setPhone1(String phone1) {
    this.phone1 = phone1;
}

public String getPhone2() {
    return phone2;
}

public void setPhone2(String phone2) {
    this.phone2 = phone2;
}

public String getPhone3() {
    return phone3;
}

public void setPhone3(String phone3) {
    this.phone3 = phone3;
}

public String getPhone4() {
    return phone4;
}

public void setPhone4(String phone4) {
    this.phone4 = phone4;
}

public String getPhone5() {
    return phone5;
}

public void setPhone5(String phone5) {
    this.phone5 = phone5;
}

public String getCoords() {
    return coords;
}

public void setCoords(String coords) {
    this.coords = coords;
}

public String getIsNew() {
    return isNew;
}

public void setIsNew(String isNew) {
    this.isNew = isNew;
}

public String getMarkId() {
    return markId;
}

public void setMarkId(String markId) {
    this.markId = markId;
}

public String getModelId() {
    return modelId;
}

public void setModelId(String modelId) {
    this.modelId = modelId;
}

public String getUserId() {
    return userId;
}

public void setUserId(String userId) {
    this.userId = userId;
}

public String getPrice() {
    return price;
}

public void setPrice(String price) {
    this.price = price;
}

public String getCreated() {
    return created;
}

public void setCreated(String created) {
    this.created = created;
}

public String getStatus() {
    return status;
}

public void setStatus(String status) {
    this.status = status;
}

public Integer getIsFavourite() {
    return isFavourite;
}

public void setIsFavourite(Integer isFavourite) {
    this.isFavourite = isFavourite;
}

public RealmList<PhotoAdvert> getPhotos() {
    return photos;
}

public void setPhotos(RealmList<PhotoAdvert> photos) {
    this.photos = photos;
}

public String getModelname() {
    return modelname;
}

public void setModelname(String modelname) {
    this.modelname = modelname;
}

public String getMarkname() {
    return markname;
}

public void setMarkname(String markname) {
    this.markname = markname;
}

}
Вот такая ошибка выходить
com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected BEGIN_OBJECT but was STRING at line 1 column 38 path $.data[0].object[0]
Вот json ответ
{"data":[{"success":true,"object":[{"id":"2","cat_id":"1","is_dogovornaja":"1","is_obmen":"1","description":"\u043e\u043f\u0438\u0441\u0430\u043d\u0438\u0435 \u0442\u043e\u0432\u0430\u0440\u0430","email":"test@gmail.com","city_id":"1","address":"\u0433. \u0410\u043b\u043c\u0430\u0442\u044b, \u0443\u043b. \u0428\u0430\u0448\u043a\u0438\u043d\u0430 54","phone1":"(777)123-4567","phone2":"(777)423-3567","phone3":"(777)523-2567","phone4":"(777)323-1567","phone5":"(777)723-0567","coords":"44.2536545, 46.525656332","is_new":"1","mark_id":"1","model_id":"1","user_id":"54","price":"100000","created":"1481446357","status":"1","is_favourite":0,"modelname":"Samsung Galaxy S7","markname":"Samsung","photos":[{"id":"1","url":".\/uploads\/ob\/3ece2520bd8a1f36a16983ffc52d8ad8_0.jpg"},{"id":"2","url":".\/uploads\/ob\/3ece2520bd8a1f36a16983ffc52d8ad8_1.jpg"}]}],"errors":[]}]}

A: У вас data это один объект DataAdvertList, вы пытаетесь добыть массив.
Вместо
public List<DataAdvertList> getDataAdvertLists() {
    return dataAdvertLists;
}

и
@SerializedName("data")
@Expose
private List<DataAdvertList> dataAdvertLists = new ArrayList<DataAdvertList>();

и
DataAdvertList dataAdvertList = listResponse.getDataAdvertLists().get(0);

Напишите так:
public DataAdvertList getDataAdvertLists() {
    return dataAdvertLists;
}

и
@SerializedName("data")
@Expose
private DataAdvertList dataAdvertLists;

и
DataAdvertList dataAdvertList = listResponse.getDataAdvertLists();


text:
Q: Why is RSI calculation with python ta library changes depending on starting position? I have a DataFrame and I want to calculate the RSI on the Close column with a window of 14 like so:
from ta.momentum import RSIIndicator
import pandas as pd

data = pd.read_csv()
output = RSIIndicator(data.Close, 14).rsi()
print(output.head(20))

This works and I get the following RSI result:
0           NaN
1           NaN
2           NaN
3           NaN
4           NaN
5           NaN
6           NaN
7           NaN
8           NaN
9           NaN
10          NaN
11          NaN
12          NaN
13    30.565576
14    30.565576
15    30.565576
16    36.847817
17    53.471152
18    53.471152
19    59.140918

But If I start the RSI at another arbitrary position, example on data.iloc[1:], I understand that since I shifted a position by 1, the 13th index is now going to be NaN and RSI will start at the 14th. But why does this change the values?
t = RSIIndicator(data.Close.iloc[1:], window).rsi()
print(t(20))

1           NaN
2           NaN
3           NaN
4           NaN
5           NaN
6           NaN
7           NaN
8           NaN
9           NaN
10          NaN
11          NaN
12          NaN
13          NaN
14    31.481498
15    31.481498
16    37.849374
17    54.534367
18    54.534367
19    60.171078
20    44.372719

Shouldn't the RSI be the same value no matter where you start. The only thing that is needed is the previous 14 values right? so why does the RSI change if the oldest 15th value is not there?
This is important because I would like to calculate the RSI on the fly meaning as data comes in, I would pass the previous 14 data points to the RSI function and get the next value. But it seems like I always need to pass the whole dataset from beginning.


text:
Q: Representing vector as a column vector with respect to two bases I have never done anything like this and the only examples I can find online basically tell me how to do the change of basis for "change-of-coordinates matrix from $B$ to $C$". If anyone is able to help me solve this, I would be very grateful. I really don't know where to start.
This is the problem:
Represent the vector as a column vector with respect to each of the two bases.
$$..\vec{v}=\begin{pmatrix}\begin{array}{r}
3\\
-1
\end{array}\end{pmatrix}\quad B_{1}=\left<\begin{pmatrix}\begin{array}{r}
1\\
-1
\end{array}\end{pmatrix},\begin{pmatrix}\begin{array}{r}
1\\
1
\end{array}\end{pmatrix}\right>,\;\quad B=\left<\begin{pmatrix}\begin{array}{r}
1\\
2
\end{array}\end{pmatrix},\begin{pmatrix}\begin{array}{r}
1\\
3
\end{array}\end{pmatrix}\right>$$..

A: You seem to be confused.  When you talk about the matrix, I take you to mean a matrix whose columns are the basis vectors.  In the case of $B_1$ that would be $$M :=\begin{pmatrix}1&1\\-1&1\end{pmatrix}$$  If we multiply a vector $\begin{pmatrix}a\\b\end{pmatrix}$ by $M$, we get
$$\begin{pmatrix}1&1\\-1&1\end{pmatrix}\begin{pmatrix}a\\b\end{pmatrix}
=\begin{pmatrix}a+b\\-a+b\end{pmatrix}=a\begin{pmatrix}1\\-1\end{pmatrix}+b\begin{pmatrix}1\\1\end{pmatrix}$$
Expressing $\begin{pmatrix}1\\-1\end{pmatrix}$ as a linear combination of the basis vectors means to find $a$ and $b$ such that $$\begin{pmatrix}3\\-1\end{pmatrix}=a\begin{pmatrix}1\\-1\end{pmatrix}+b\begin{pmatrix}1\\1\end{pmatrix}\tag1$$
That is, you don't want to multiply the given vector by the matrix; you want to find a matrix which, when multiplied by the vector, produces the given vector.  In other words, you need to solve $(1)$ for $a$ and $b$.  This simply means solving a system of two linear equations in two unknowns.


text:
Q: Dual rail DC-DC converter with higher Vout than specified I have a TBA 2-0522 from Traco Power supposed to output +/- 12 VDC from +5 VDC as input but instead I'm measuring +/- 19~20 V even under a dummy load. Any idea?
Datasheet: https://www.mouser.com/datasheet/2/687/tba2_datasheet-3049804.pdf


text:
Q: Spring create a method controller that executes in every page Currently , I am implementing the hreflang meta tag in my site and I am facing a problem , I need to create a method that must be executed in every page (in order to load the hreflangs into the model and pass them to the JSP) of my site and this method must have this parameters HttpServletRequest request, HttpServletResponse response.
I tried with this :
@RequestMapping(value = {"/*"})
public class GLobalPageController  {

    @ModelAttribute
    public void setupHreflangs(Model model, HttpServletRequest request, final HttpServletResponse response) {
        //code
    }

}

But its not working , any idea about how can I achieve this ?


text:
Q: Back button of Searchview I'm using Toolbar and SearchView for the ActionBar. After submit query text, It's changed like the picture below. How to set OnClick to the back button?

Edit 1: Here are involve code
menu.xml
 <item
        android:id="@+id/action_search"
        android:orderInCategory="100"
        android:title="@string/action_settings"
        android:icon="@drawable/ic_search_white"
        app:showAsAction="always|collapseActionView"
        app:actionViewClass="android.support.v7.widget.SearchView"/>

In my Fragment class
@Override
    public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
        inflater.inflate(R.menu.menu_main, menu);
        final MenuItem myActionMenuItem = menu.findItem(R.id.action_search);
        final SearchView searchView = (SearchView) MenuItemCompat.getActionView(myActionMenuItem);
        final ImageView mCloseButton = (ImageView) searchView.findViewById(android.support.v7.appcompat.R.id.search_close_btn);
        searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
            @Override
            public boolean onQueryTextSubmit(final String query) {
                if (!searchView.isIconified()) {
                    searchView.setIconified(true);
                }
                mCloseButton.performClick();
                return false;
            }
...

A: Simply add android:showAsAction="always|collapseActionView" in your menu item.
Example menu.xml
<?xml version="1.0" encoding="utf-8" ?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">
  <item
    android:id="@+id/menu_search"
    android:icon="@drawable/ic_search_white_24dp"
    android:showAsAction="always|collapseActionView"
    android:actionViewClass="android.widget.SearchView" />
</menu>


text:
Q: BaseApplicationCustomizer throws errors So today I was updating one of our SPFX extensions to use the latest spfx framework (1.16) with node (16.13) and after finishing my updates I got the following inside my code:

I am not exactly sure why these are not coming in, I suspect the newest version of spfx moves these classes out of sp-application-base, but why? and where is the documentation for it? Because there is this link that is only 6 months old and explains to use this code for the top and bottom headers.
I was expecting this code to remain in sp-application-base, but it appears it isn't in that package.

A: It is still there. What version of @microsoft/sp-application-base is in your project? Should be 1.16.1 I believe. I will say that I am new to all of this as well, but I am using the latest framework and VS is not flagging any issues with these.

A: How did you perform the upgrade? I highly recommend using the Microsoft 365 CLI to upgrade projects, as the developers of that app do thier best to cover every part of the project that needs to change.  Learn more at https://pnp.github.io/cli-microsoft365/cmd/spfx/project/project-upgrade/
Here are the commands to run from the root of your project
npm install -g @pnp/cli-microsoft365
m365 spfx project upgrade --output text

This will give a list of npm commands and code update instructions to follow. See the above documentation for other options for output and use whatever works best for you.


text:
Q: Jenkins : Use "Build after other projects are built" and "Build periodically" at the same time I have two jobs, p1 and p2.
Conditions that trigger p2:

*

*p1 build is completed

*Every Monday

But I know "Build after other projects are built" and "Build periodically" do not trigger at the same time.
Is there any way to solve this?

A: Yes: Make a job p3 than just triggers job p2 when p1 is completed. And schedule p2 to run periodically.


text:
Q: Is there any replacement for kafka connect kinesis? I am trying to find the api that connects kinesis to kafka.
The API listed on the kafka connecter website is dead.
see https://github.com/jcustenborder/kafka-connect-kinesis
Any suggested replacement?

A: This connector will be included in the Confluent Enterprise connector program, and will be available for download soon from https://confluent.io


text:
Q: Reductive subgroup and its derived subgroup with an irreducible represenation Could you please answer the following question: Let $V$ be a faithful irreducible representation of a connected reductive group $H$ defined over $\mathbb{R}$ Is it true that the derived group of $H$, which is semisimple, also acts irreducibly on $V$?. For example $H = U(p/2,q/2) \subseteq SO(p,q)$, with $p,q$ both even, and $V$ is the natural representation of $SO(p,q)$.

A: You should give a bit more motivation as to why you are asking this; it feels like an exercise in a book.
Anyway, this is not true: for a trivial example, take $G=SO(2)$ acting irreducibly on ${\mathbb R}^2$; the derived subgroup is trivial and does not act irreducibly.
If you want a truly semi-simple example, take $G=SO(n)\times SO(2)$ acting irreducibly on the exterior tensor power of the standard representations of $SO(n)$ and $SO(2)$: namely $V={\mathbb R}^n\otimes {\mathbb R}^2$, with $n\geq 3$. The derived group is $SO(n)$ and does not irreducibly on $V$.


text:
Q: R, fread CSV - how to maintain line breaks in cell values? I've got a CSV file that I am reading into an R script using fread. The resulting variable is a vector, which is what I need for the next step in my process. There are values in my CSV file such as 'Energy \nElectricity', and the intention is that these will be labels for a chart, with a line break between (in this case) 'Energy' and 'Electricity' for formatting reasons.
When I manually code the vector to be
myVec <- c('Energy \nElectricity'), this works fine and the line break is maintained.
When I read the data in using fread, however, the resulting vector is effectively c('Energy \\nElectricity'), i.e. the process has inserted an extra escape character and the formatting is lost.
My question is as follows:

*

*Is there a way to use fread to maintain these line breaks at all?

*If not, can I format them differently in my csv file?

*If not, can I use gsub or similar to remove the extra line break once the file has been read into a vector?

I have tried all manner of ways to implement gsub (and sub), but they either get rid of both escape characters, such as gsub("\\\\", "\\", myVec) which gives
[1] "Energy nElectricity", or they throw an error. I think I am missing something obvious. Any help appreciated.

A: If nobody comes up with a better solution, this is how you would clean it using gsub:
gsub("\\n", "\n", "Energy \\nElectricity", fixed = TRUE)

The fixed option ignores all regex characters and is also considerably faster than fixed = FALSE.


text:
Q: Conditional Serialization of class based on class property value I have a class called Wizard, that I want to serialize. That class contains an Array/List/Observablecollection of instances of a subclass called Queryas property.
Currently each Queryinstance is serialized like this:
    /// <summary>
    /// Queries array property
    /// </summary>
    [XmlArray("Queries"), XmlArrayItem(typeof(Query), ElementName = "Query")]
    public ObservableCollection<Query> Queries {
        get { return queries; }
        set { queries = value; }
    }

What I want to do now, is only serialize those instances of the Queryclass, where a certain property of the class has the desired value, somewhat like this:
querytoserialize.QueryStatus = QueryStatus.Valid

Is this possible using [Xml]-tags on the property (or any other convenient way)?

A: Just select those using the linq and serialize them:
YourQueires.Where(q=> q.CertailProperty == DesiredValue);


text:
Q: using kronecker's theorem can we prove there's some power of two yielding a number whose initial digits equal my social security number? I just watched the "Great Courses" series of lectures in number theory, in which Professor Burger stated that
using Kronecker's theorem

for any irrational number r, the sequence ({n * r})  where n >= 0 is
  dense in the interval [0,1)

we can prove there's some power of two yielding a number whose initial digits equal my social security number.
The sketch of the proof given in the course used the fact that  log 2  is an irrational number. I tried to flesh out the whole proof to really understand it and I got stuck.
My attempt at a proof
First assume my social security number is 566...
From Kronecker:
there exists m |   m * log 2   =    X.566...
Since log 2^x  =   x * log 2, we have
m * log 2   =    X.566...
log 2 ^ m = X.566...

What to do next?  Or maybe I need to start on a different
tack ? I'd be very grateful for any tips or guidance.
( kroenecker proof details here )

A: Let $N$ be the integer formed out of the required digits (for instance, your SSN).  We want the first digits of $2^n$ to line up with those of $N$.  Verify for yourself that it is equivalent to check that there exists a (non-negative) integer $k$ such that
$$
10^k \cdot N \leq 2^n \leq  10^k \cdot (N + 1)
$$
Taking the log base $10$ of all of these, we see that $n$ is the exponent we want if there exists an integer $k$ such that we have the inequalities
$$
k + \log_{10} N \leq n \log_{10}2 \leq  k + \log_{10}(N + 1)
$$
Perhaps now you can relate what you're looking for to Kronecker's theorem.


text:
Q: SOQL Query Inner Join Could you please help me with the syntaxis of this SOQL Query? I would like to do an INNER JOIN between A and B on A.FamilyMember=B.ID
SELECT A.FamilyMember__c
FROM A
WHERE A.StartDate__c > TODAY  AND A.EndDate__c < TODAY
AND (SELECT ID FROM B Where Membre__c = True)

A: select Id, FamilyMember__c
from A
where StartDate__c > TODAY
    and EndDate__c < TODAY
    and FamilyMember__c in (
        select Id
        from B
        where Membre__c = true
        )

this SOQL is split into 2 parts:

*

*select Ids of B with condition (Membre__c = True),  this is inner select

*select A with condition (FamilyMember__c is in ids of records from previous step)


text:
Q: How to check if user disable Google text to speech from Application manager I working on text to speech, in some device it does not work because users have disable Google text to speech from application manager, is there any way i can check where user disable app or not before making text to speech request

A: I solve my problem, This not best solution i know, But for me it work
textToSpeech = new TextToSpeech(context.getApplicationContext(), new TextToSpeech.OnInitListener() {
            @Override
            public void onInit(int status) {
                if (status == TextToSpeech.SUCCESS) {
                 // for speak code goes here

                } else {
                    Toast.makeText(context, "tts_failed Error code "+status, Toast.LENGTH_LONG).show();
                    if(status == -1) //
                    {
                        // this is will open play store if use have not install or disable google text to speach
                        try {
                            context.startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("market://details?id=com.google.android.tts")));
                        } catch (android.content.ActivityNotFoundException anfe) {
                            context.  startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("https://play.google.com/store/apps/details?id=com.google.android.tts" )));
                        }
                    }

}


text:
Q: Replacing potentiometer with a Hall sensor in PWM DC motor control module I have a DC motor speed controller (PWM) that uses a 100 kΩ potentiometer to adjust motor speed. I also have an electronic throttle pedal that used a 49E Hall-Effect sensor (+5 V, 0.8-4.2 V signal, 1 K
KΩ). I want to use this pedal with this speed controller.
I measured the voltage drop across the potentiometer and it is 5 V. I confirmed that the pedal's signal changes from 0.8 V (released) to 4.2 V (fully pressed) when given 5 V.
What would be a right way to replace the potentiometer in the speed control unit with a Hall-effect sensor? Note that I would prefer to preserve full speed control range (from 0% to 100%).
If you're curious about my application: replacing binary on/off throttle in kids ride on car.
UPDATE 1
PWM controller built-in potentiometer works like this:

*

*Max speed: GND to wiper = 0 V, wiper to V+ = 5 V

*Min speed: GND to wiper = 5 V, wiper to V+ = 0 V

And Hall-effect pedal is opposite:

*

*Max speed (fully pressed): GND to signal = 4.2 V

*Min speed: GND to signal = 0.8 V

So as a drop-in replacement pedal it will behave more like a break pedal :)
UPDATE 2
On further examination, it appears that the potentiometer's GND (I mean, one of its legs that I referred above as GND) is connected directly to input GND of the PWM controller (where the negative terminal from battery goes). So, from a practical standpoint, it's probably safe to assume that I also have GND - Xv at my disposal (Xv however is variable, since it's coming from an unregulated battery).
But I think this extra voltage source makes this question less general and less useful for other people.

A:
simulate this circuit – Schematic created using CircuitLab
This won't reverse it. Will continue to look at it tommorrow. I'm not sure I can do it without a negative supply.
https://www.falstad.com/circuit/circuitjs.html?ctz=CQAgjCAMB0l3BWEA2AzNA7ATi8gHACxhaKTJYgIaWWQBQAhiAEx57hbMgGpfFfswSALRDw8eFGi5myBGDxyCyMs1QUYM5GhwZlYDAlbiJdAO4s24MF1aCMyKOe68OXHnxtOATpcFePay5IcAR4Ol8bf1srMC8QsFNfOxZIdhTmBEcEsLg6AHM-Fiyi1EgCHyLmNLdU9gTTAHkXPk5uXFqQ+gAHWurBNszsqCdC-mLHcbKK+gA3cGMhhfSakIqCBMwWaCQunYLlicPmDGCDqPAVQ4Ns5wv+vtW6VBnoPAA1AB0AZwAvAFMAHb-XybDBgHhGPD8aHwZj-YTUELBN50X7XK4XOK2KQfH4A4HeCLXLwXAj1EDqPIAJUO5IxIzWIV2jP2AHsQBRkDNuJAsOwkbB4FgHFlMiMwHQOexuSMNvzxFIJMwCEQNshxRBJUA


text:
Q: The number $2^{3^n}+1$ is divisible by $3^{n+1}$ and is not divisible by $3^{n+2}$. Old question:
The number $2^{3^n}+1$ is divisible by $3^{n+1}$ and not divisible by $3^{n+2}$.
However, I don't understand the answer from the question.
I know how to prove why it is divisible by $3^{n+1}$, but not divisible by $3^{n+2}$.
Prove it is divisible: https://math.stackexchange.com/a/1591199.
Can someone please show me step by step how to prove is not divisible?


text:
Q: Set target when open .html file via terminal on MacOS There is this solved topic about opening .html files via command line.
I use the solution and it works well for using
open ./myfile.html

However, it opens the file always in a new tab. I would like to open it always in the same tab (using the browser target). This is an easy thing to do in JavaScript, but I can't figure out a way to do it in combination with the above mentioned code.
My assumption for now is, that there must be a way to pass the target as a parameter to the open command. The man open reveals the following for the parameter --args:

All remaining arguments are passed to the opened application in the
  argv parameter to main().  These arguments are not opened or
  interpreted by the open tool.

So I tried the following:
open ./myfile.html --args target=myfile_target   # still opens in new tab
open ./myfile.html --args target="myfile_target" # still opens in new tab
open ./myfile.html --args target:myfile_target   # still opens in new tab

I am not sure if this even works but I think there must be a way to do this.
Edit: for now it is enough to make this work with chrome.

A: This Bash script incorporates a bit of AppleScript in order to open a browser window with a reference that the script can keep track of and continue to target with ongoing URL requests.
You ought to be able to copy-n-paste it into a text editor and save it as whatever you wish to call this replacement open function.  I saved it as url, in one of the directories listed in my $PATH variable.  That way, I could simply type url dropbox.com from the command-line, and it would run.
You will have to make it executable before you can do that.  So, after it's saved, run this command:
chmod +x /path/to/file

Then you should be good to go.  Let me know if you encounter any errors, and I'll fix them.
    #!/bin/bash
    #
    # Usage: url %file% | %url%
    #
    # %file%: relative or absolute POSIX path to a local .html file
    # %url%: [http[s]://]domain[/path/etc...]

    IFS=''

    # Determine whether argument is file or web address
    [[ -f "$1" ]] && \
        _URL=file://$( cd "$( dirname "$1" )"; pwd )/$( basename "$1" ) || \
            { [[ $1 == http* ]] && _URL=$1 || _URL=http://$1; };

    # Read the value on the last line of this script
    _W=$( tail -n 1 "$0" )

    # Open a Safari window and store its AppleScript object id reference
    _W=$( osascript \
        -e "use S : app \"safari\"" \
        -e "try" \
        -e "    set S's window id $_W's document's url to \"$_URL\"" \
        -e "    return $_W" \
        -e "on error" \
        -e "    S's (make new document with properties {url:\"$_URL\"})" \
        -e "    return id of S's front window" \
        -e "end try" )

    _THIS=$( sed \$d "$0" ) # All but the last line of this script
    echo "$_THIS" > "$0"    # Overwrite this file
    echo -n "$_W" >> "$0"   # Appened the object id value as final line

    exit
    2934


text:
Q: c++: truth assignment warning with arguments? I use the following to work with arguments in my programs, but it seems to just hand me a warning (just a warning): "warning: suggest parentheses around assignment used as truth value"
The beginning of the code is as follows:
   while((++argv)[0] && argv[0][0]=='-'){
      while(c =* ++argv[0])

The while(c =* ++argv[0]) part being where the warning persists. The code works fine, but what does this warning mean opposed to what is used?
I think the code is c = *++argv[0], using the pointer. So why does the single = work and what is really recommended to be used?

A: The compiler is unsure whether you intended
while(c == whatever)

instead. It's a common error to misuse assignment instead of comparison inside the conditional expression. Sometimes you do want assignment, sometimes not and the compiler gives a warning. To make the compiler see that you really want assignment and not emit the warning use:
while((c =* ++argv[0]) != 0)

A: you need to double the parenthesis to explicitly state that you really mean to test the value of c:
while( (c =* ++argv[0]) )

A: The compiler warns because you might accidently have written a statement instead of an expression. By embedding the statement in parentheses you tell the compiler your intention and stop him warning.


text:
Q: Firebase function admin sdk getting download url of Cloud Storage object: permission denied exports.test = functions.https.onRequest(async (req, res) => {
  const file = await admin
    .storage()
    .bucket("XXX")
    .file("YYY");
  await file.makePublic();
  const url = await file.publicUrl();
});

I currently have images set up on Cloud Storage. Because I need to go through the Google Cloud Node.js client library to get access to these, the above code is my current setup. Unfortunately, when running this code, I get the following error:
{
  "error": {
    "code": 401,
    "message": "Anonymous caller does not have storage.objects.getIamPolicy access to the Google Cloud Storage object.",
    "errors": [
      {
        "message": "Anonymous caller does not have storage.objects.getIamPolicy access to the Google Cloud Storage object.",
        "domain": "global",
        "reason": "required",
        "locationType": "header",
        "location": "Authorization"
      }
    ]
  }
}

I'm a little confused because of the following from this (https://firebase.google.com/docs/storage/admin/start) Firebase reference:

You can use the bucket references returned by the Admin SDK in
conjunction with the official Google Cloud Storage client libraries to
upload, download, and modify content in the buckets associated with
your Firebase projects. Note that you do not have to authenticate
Google Cloud Storage libraries when using the Firebase Admin SDK.
The bucket references returned by the Admin SDK are already authenticated with the credentials used to initialize your Firebase
app.

Why do I have to worry about security rules then? More importantly, how do I fix this?
How I initialize the admin SDK:
const serviceAccount = require("./[my-project-name]-8a2aa8e3eedc.json");
admin.initializeApp({ credential: admin.credential.cert(serviceAccount) });

EDIT: added security rules and IAM roles.
My security rules:
rules_version = '2';
service firebase.storage {
  match /b/{bucket}/o/images {
    match /listings/{listingId}/{photo} {
      allow read, write: if true;
    }
    match /users/{userId}/{photo} {
      allow read: if true;
      allow write: if request.auth.uid == userId;
    }
  }
}

A: While the Firebase Admin SDK is not subject to Storage Rules the service account attached to the function running the code still needs to have IAM Storage Permissions, these are separate things. Make sure that the service account for the function has the "Storage Object Admin" IAM role.
On another matter, when trying to reproduce the issue I found out that the method file.publicUrl() is not currently working so you would need to use the getSignedUrl method instead, which by the way is the recommended approach with regards to security concerns. Alternatively (though highly discouraged) you may handcraft the uri yourself.


text:
Q: routing a different root index I am new to rails and want to do a simple routing to root operation. My file path is app/views/slots/index.html.erb. When I go in my routes.rb file and see:
You can have the root of your site routed with "root"
just remember to delete public/index.html.
root :to => 'welcome#index'

I change the 'welcome#index' to "slots#index', I get this error from localhost:3000:
No route matches [GET] "/"

In the terminal, I use ctrl c to exit server and $ rails server to restart and still get the error. I watched my instructor do the same exact simple steps yet I get this error. Anyone know what I did wrong?

A: Edit : my bad, indeed the error is not corresponding to the solution I described below.

It seems you didn't create the slots controller.
You have to create a controller to display files. app/views/slots/index.html.erb is just a view, corresponding to an action of a controller.
So create the file app/controller/slots.rb
    class SlotsController < ApplicationController
      def index
      end
    end
You can do this faster with generator. In your terminal, cd to your application path and then
    rails generate controller Slots index
To learn Rails I recommend you some reading here : http://guides.rubyonrails.org/getting_started.html


text:
Q: Basic jQuery Slider does not display properly on page load (Responsive setting) I'm using the latest bjqs and jquery versions. I'm not editing ANY bjqs css. The issue is when the page loads, the second image is in the view. The slides continue this as they slide in where the other image is visible. However if I resize the window in any way the bjqs does what it is supposed to do and it resizes the images so only one is visible.
I get this: http://i.imgur.com/zUtwK7F.jpg
This is my markup.

<-- slider in here -->

#container {max-width: 1600px;}

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

$('#banner-slide').bjqs({
animtype      : 'slide',
height        : 520,
width         : 1600,
responsive    : true,
});
});

A: I'm reproducing something similar here: http://jsfiddle.net/Ru5vp/2
html:

css:
ul.bjqs{position:relative; list-style:none;padding:0;margin:0;overflow:hidden; display:none;}
li.bjqs-slide{position:absolute; display:none;}
ul.bjqs-controls{list-style:none;margin:0;padding:0;z-index:9999;}
ul.bjqs-controls.v-centered li a{position:absolute;}
ul.bjqs-controls.v-centered li.bjqs-next a{right:0;}
ul.bjqs-controls.v-centered li.bjqs-prev a{left:0;}
ol.bjqs-markers{list-style: none; padding: 0; margin: 0; width:100%;}
ol.bjqs-markers.h-centered{text-align: center;}
ol.bjqs-markers li{display:inline;}
ol.bjqs-markers li a{display:inline-block;}
p.bjqs-caption{display:block;width:96%;margin:0;padding:2%;position:absolute;bottom:0;}
#container {max-width: 1600px;}

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

    $('#banner-slide').bjqs({
        animtype      : 'slide',
        height        : 520,
        width         : 1600,
        responsive    : true,
    });
});

The dimensions of the images are different from what is declared in the js height and width. If I change the dimensions to be equal to the actual dimensions, it works fine.
I notice that if I use height: 826, width: 1600, which scales the images proportionally, the images are setup similar to what your image shows. If I resize the result window, the images resize like what you are describing.


text:
Q: Magento 2 - detect orders that are placed via REST API Is there a way to detect orders that are placed via API? I want to add to those orders a different order number prefix.
I have already created an observer that is changing the prefix based on payment method of the order and I want to extend it to change the prefix based on order placed on web or API.
Event for observer now is sales_order_place_after
I have an observer that is doing that and I want to fix it in observer but what I need to take into consideration are the prefix for:

*

*web orders paid by card

*web orders with bank transfer

*API orders paid by card

*API orders with bank transfer

Basically I need 4 types of prefix.
Because of this, the functionality that I need now is a way to detect when an order comes from API vs orders that comes from web
Can someone please help me?

A: To identify the order placed on website or via API, you can check the HTTP Origin of the request (HTTP_ORIGIN). If the order placing on the website, the HTTP Origin will return the website base URL, otherwise, it will return an empty string.
Implementation of the Observer class:
<?php

namespace Vendor\Module\Observer;

use Magento\Framework\App\RequestInterface;
use Magento\Framework\Event\Observer;
use Magento\Framework\Event\ObserverInterface;

class ChangeOrderPrefix implements ObserverInterface
{
    /**
     * @var RequestInterface
     */
    private $request;

    public function __construct(RequestInterface $request)
    {
        $this->request = $request;
    }

    /**
     * Change the order prefix based on ...
     *
     * @param Observer $observer
     * @return $this
     */
    public function execute(Observer $observer)
    {
        /** @var \Magento\Sales\Model\Order $order */
        $order = $observer->getEvent()->getOrder();
        // If HTTP_ORIGIN has value that means the order placed on website
        if ($this->request->getServer('HTTP_ORIGIN')) {
            // Code for the order placed on website
        } else {
            // Code for the order placed via API
        }
        // Your customize code goes here

        return $this;
    }
}

A: I think their is no way to check if order was placed via API or browser by using Magento Events sales_order_place_after because by Default on browser the javascript also place order via API payment-information

*

*In this case i think you has to implement a javascript code which adding an additional information to payment-info on the browser which this information allow you tracking which order was placed on Browser.

A hit for you: Adding a hook to place-order-hooks.js which allow you update the payload before submit to server.


text:
Q: won't post in django rest framework when i try to post a house instance it tells me the data is valid but won't save it knowing that it was working before i added the user attribute , the problem i think is in the "id" attribute
class houseSerializers(serializers.ModelSerializer):
    class Meta:
        model = House
        fields =('id','user','title','city','type','address','rooms','beds','price')

the representation of the serializer
    >>> print(repr(serializer))
houseSerializers():
    id = IntegerField(label='ID', read_only=True)
    user = PrimaryKeyRelatedField(queryset=User.objects.all())
    title = CharField(max_length=50)
    city = CharField(max_length=50)
    type = CharField(max_length=50)
    address = CharField(max_length=50)
    rooms = IntegerField()
    beds = IntegerField()
    price = IntegerField()
>>>

@api_view(['POST'])
def houseCreate(request):
        serializer = houseSerializers(data=request.data)
        if serializer.is_valid():
                serializer.save

        return Response(serializer.data)


text:
Q: Only able to access grub menu through windows advanced startup The grub menu doesn't show up during regular boot and I can only access it through advanced startup in windows recovery, after selecting start up from a device or disc. How do I make it appear while booting?
If it matters, I actually installed Ubuntu, deleted the partitions in windows (didn't do anything with EFI partition) then installed again. But only one 'Ubuntu' shows in grub menu (while accessing from windows recovery). You'd think there would be 2 entries there.

A: As usual, the boot order can be set in UEFI settings > Boot menu by choosing "Ubuntu" instead of "Windows bootloader manager".
After booting Ubuntu, Grub can and often should be updated with sudo update-grub. Disabling the Fast Startup feature in Windows is must when dual-booting and should be disabled already when updating Grub otherwise the other OS may not be correctly identified.
From comments,

Also I noticed that there's 3 options in the boot priority list (1 Windows and others Ubuntu)

due to multiple Ubuntu installation attempts. EFI boot entries can be easily managed from Ubuntu with the help of efibootmgr:
sudo efibootmgr #display the current settings; take note of BootCurrent

BootCurrent shows the working Ubuntu boot entry you're currently running. Notice that typically the entries are numbered as 000X as mentioned in the examples in the manual page of the command but can be different in some cases. Then the non-working Ubuntu entry can be deleted with
sudo efibootmgr -b X -B or sudo efibootmgr -b 000X -B (or specifying the 4 digits number if different; X represent an order number previously obtained when listing).


text:
Q: Async HTTP Server receiving spurious request I converted a synchronous HTTP Server (using .NET's HttpListener) to asynchronous following this example. It works, but for every request I issue from Google Chrome, be it hitting enter at the address bar or pressing F5, I get two requests. The first one is perfectly handled, and the response is rendered fine in the browser.
However, the second request, which shouldn't even appear, has an empty query string (my server is a console application so I see all this happening using Console.WriteLine).
None of this happened when the server was synchronous, so I must have messed something up when moving to the async model.
Here's the code:
using System;
using System.Diagnostics;
using System.Net;

namespace MyWebServer{

    internal static class MyHTTPServer {
        private static int mPortNumber = 7091;
        private static HttpListener mListener;
        private static MyCustomHttpHandler mHttpHandler;

        //Omitted some auxiliary methods to print stuff to Console,
        //like WriteError and WriteRequestHeaderInformation

        public static void Main( String[] pArg ) {
            AppDomain.CurrentDomain.UnhandledException += UnhandledExceptionTrapper;
            HttpHandler = new MyCustomHttpHandler();
            mPortNumber = Convert.ToInt32( pArg[0] );
            Console.WriteLine( "Starting the HttpListener on port:{0}", mPortNumber );
            InitialiseListener();
            Console.WriteLine( "Listener started on port: {0}, waiting for requests.", mPortNumber );
            Console.WriteLine( "Listening. Press Enter to stop." );
            Console.ReadLine();
            if( mListener.IsListening )
                mListener.Stop();
        }

        private static void InitialiseListener() {
            try {
                mListener = new HttpListener {
                    AuthenticationSchemes = AuthenticationSchemes.Basic
                };
                string prefix = string.Format( "http://+:{0}/", mPortNumber );
                mListener.Prefixes.Add( prefix );
                mListener.AuthenticationSchemes = AuthenticationSchemes.Anonymous;
                mListener.Start();
                mListener.BeginGetContext( RequestReceived, null );
            } catch( Exception ex ) {
                WriteError( ex.Message );
            }
        }

        private static void RequestReceived( IAsyncResult result ) {
            var timer = new Stopwatch();
            Console.WriteLine( "---Request Received----" );
            timer.Reset();
            timer.Start();
            //Retrieve context; on error, print message and wait for another request
            HttpListenerContext context = null;
            try {
                context = mListener.EndGetContext( result );
            } catch( HttpListenerException e ) {
                WriteError( e.ToString() );
                if( mListener.IsListening )
                    mListener.BeginGetContext( RequestReceived, null );
                return;
            }
            //Process request and send response
            mListener.BeginGetContext( RequestReceived, null );
            try {
                WriteRequestHeaderInformation( context );
                CreateResponseDocument( context );
            } catch( Exception ex ) {
                WriteError( ex.Message );
            }
            Console.WriteLine( "----Request processed in {0} milliseconds ----", timer.ElapsedMilliseconds );
        }

        private static void CreateResponseDocument( HttpListenerContext pHttpListenerContext ) {
            try {
                byte[] htmlOutput = HttpHandler.ProcessRequest( pHttpListenerContext.Request.Url.LocalPath.Replace( "/", "" ), pHttpListenerContext.Request.Url.Query.Replace( "?", "" ) );
                if( htmlOutput != null && pHttpListenerContext.Response.OutputStream.CanWrite ) {
                    pHttpListenerContext.Response.Headers.Add( "Access-Control-Allow-Origin", "*" );
                    //pHttpListenerContext.Response.ContentType = "image/jpg";
                    pHttpListenerContext.Response.ContentType = "text/plain";
                    pHttpListenerContext.Response.OutputStream.Write( htmlOutput, 0, htmlOutput.Length );
                }
                pHttpListenerContext.Response.Close();
            } catch( Exception ex ) {
                WriteError( ex.Message );
            }
        }
    }
}

A: It seems that this happens only when the response is just a bunch of bytes (representing a jpeg image in this case). If instead of entering the http request directly in the address bar I open an HTML page like this...
 <html>
     <head/>
        <body>
            <img src="http://localhost:serverPort/queryParametersGoHere" />
        </body>
</html>

... one and only one request is received by my server. (I anonymized my port and parameters; where it says queryParametersGoHere, I actually had ?param1=value1&param2=value2, etc.


text:
Q: How do I customize a form based on XML data? I'm making a simple to-do list and want to store the tasks in an XML file. My XML file looks like this:
    <Task>
        <Title>Make a List</Title>
        <Description>I should make a List!</Description>
        <Done>false</Done>
    </Task>

Every task is in the <Task> tag which stores the title, description and if it's done.
When the form loads, I want to generate a checkbox for each task with
Text    = <Title>
 ToolTip = "<Description>"
 Checked = <Done>
Right now my code looks like this:
    void MainFormLoad(object sender, EventArgs e)
    {
        var doc = XDocument.Load(Application.StartupPath + "\\tasker.xml");

        var Title       = doc.Root.Descendants().Single(d => d.Name == "Title").Value;
        var Description = doc.Root.Descendants().Single(d => d.Name == "Description").Value;
        var Done        = doc.Root.Descendants().Single(d => d.Name == "Done").Value;

        MessageBox.Show(Title.ToString() + Environment.NewLine + Description.ToString() ); // Just for Testing
    }

This works great, but only works for one task.  How can I add checkboxes for more than one task?

A: Well, firstly you'd need multiple tasks in your XML file, e.g.
<Tasks>
    <Task>
      ...
    </Task>
    <Task>
      ...
    </Task>
</Tasks>

Then you could iterate over all the tasks like this:
var doc = XDocument.Load("...");
var tasks = doc.Root.Elements("Task")
               .Select(x => new {
                          Title = (string) x.Element("Title"),
                          Description = (string) x.Element("Description"),
                          Done = (bool) x.Element("Done");
                       });

foreach (var task in tasks)
{
    // Use task.Title etc
}

You don't have to use a separate local variable for that, but it looks simpler to me. You might want to create a named class for a task as well, rather than using the anonymous type that I've created here.
Note that an alternative to elements would be to use attributes for the data for each task.

A: First you can create a Tasks Main Element wrapping any Task Element and then iterate through each.
Then the XML would looks like:
 <Tasks>
  <Task>
    <Title>Make a List</Title>
    <Description>I should make a List!</Description>
    <Done>false</Done>
  </Task>
  <Task>
    <Title>Make a Second List</Title>
    <Description>I should make a Second List!</Description>
    <Done>false</Done>
  </Task>
</Tasks>

After loading the XDocument the iteration is just a for each:
        foreach (var child in doc.Root.Descendants("Task"))
        {
            var Title = child.Descendants().Single(d => d.Name == "Title").Value;
            var Description = child.Descendants().Single(d => d.Name == "Description").Value;
            var Done = child.Descendants().Single(d => d.Name == "Done").Value;

        }

Hope that helps you.


text:
Q: ProductInsert() does not exist in current context protected void Btn_CheckOut_Click(object sender, EventArgs e)
{
    int result = 0;

    Payment user = new Payment(txt_CardNumber.Text, txt_CardHolderName.Text, txt_ExpirationDate.Text, txt_Cvv.Text);
    result = ProductInsert();
   /* Session["CardNumber"] = txt_CardNumber.Text;
    Session["CardHolderName"] = txt_CardHolderName.Text;
    Session["ExpirationDate"] = txt_ExpirationDate.Text;
    Session["Cvv"] = txt_Cvv.Text;*/

    Response.Redirect("Payment Sucessful.aspx");
}

public int ProductInsert()
{
    int result = 0;
    string queryStr = "INSERT INTO CustomerDetails(CardNumber, CardHolderName, ExpirationDate, Cvv)"
                      + "values (@CardNumber,@CardHolderName, @ExpirationDate, @Cvv)";
    try
    {
        SqlConnection conn = new SqlConnection(connStr);
        SqlCommand cmd = new SqlCommand(queryStr, conn);
        cmd.Parameters.AddWithValue("@CardNumber", this.CardNumber);
        cmd.Parameters.AddWithValue("@CardHolderName", this.CardHolderName);
        cmd.Parameters.AddWithValue("@ExpirationDate", this.ExpirationDate);
        cmd.Parameters.AddWithValue("@Cvv", this.Cvv);
        conn.Open();
        result += cmd.ExecuteNonQuery(); // Returns no. of rows affected. Must be > 0
        conn.Close();
        return result;
    }
    catch (Exception ex)
    {
        return 0;
    }
  }
}

I am trying to store credit card informations into database. I have created a productInsert() method and now I am trying to insert whatever values into the database.
This code is giving the error:

ProductInsert() does not exist in current context


text:
Q: Show the last post by date from a custom taxonomy in the WordPress loop I have a custom taxonomy which I use to bundle posts in series (a series is a term in that taxonomy). What I would like is to treat those bundled posts as special cases when executing the WordPress loop.
Only the first post in the series (the one with the most recent date) should display and all other posts not belonging to a term in the custom taxonomy should be treated as normal posts. Apart from the custom series taxonomy, the posts can also be tagged or categorised (so a maximum of three taxonomies, including the custom one). The loop should contain a fixed number of posts (e.g. the number of posts on the front page set in the WordPress backend).
I'm at a loss on how to group these posts, partly because all the data is in different tables and because each entry can belong to multiple taxonomies. Of course looping over the posts array, discarding the older posts in the series after the MySQL call is a possibility, but in that case the fixed number of posts is hard to maintain without making extra queries to the database.
So I would like to implement a pure SQL solution. I've been experimenting using the posts_clauses hook. This query below returns the post with the highest ID, not the date, in a series and is rather taxing on the database, I believe.
$clauses['fields'] .= ", $wpdb->posts.ID AS postID, (SELECT $wpdb->terms.term_id
   FROM $wpdb->posts, $wpdb->term_taxonomy, $wpdb->term_relationships, $wpdb->terms
   WHERE $wpdb->posts.ID=postID
     AND $wpdb->term_taxonomy.taxonomy='post-series'
     AND $wpdb->term_relationships.term_taxonomy_id=$wpdb->term_taxonomy.term_taxonomy_id
     AND $wpdb->posts.ID=$wpdb->term_relationships.object_id
     AND $wpdb->terms.term_id=$wpdb->term_taxonomy.term_id
   ORDER BY $wpdb->posts.post_date DESC
   LIMIT 0,1) AS uniqueID";

$clauses['groupby'] = "IFNULL(uniqueID,$wpdb->posts.ID)";

Based on the clauses above WordPress constructs the following SQL query:
SELECT SQL_CALC_FOUND_ROWS  wp_posts.*, wp_posts.ID AS postID,
  (SELECT wp_terms.term_id FROM wp_posts, wp_term_taxonomy, wp_term_relationships, wp_terms
    WHERE wp_posts.ID=postID
      AND wp_term_taxonomy.taxonomy='post-bundles'
      AND wp_term_relationships.term_taxonomy_id=wp_term_taxonomy.term_taxonomy_id
      AND wp_posts.ID=wp_term_relationships.object_id
      AND wp_terms.term_id=wp_term_taxonomy.term_id
    ORDER BY wp_posts.post_date DESC LIMIT 0,1)
  AS uniqueID FROM wp_posts
WHERE 1=1
AND wp_posts.post_type = 'post'
AND (wp_posts.post_status = 'publish' OR wp_posts.post_status = 'private')
GROUP BY IFNULL(uniqueID,wp_posts.ID)
ORDER BY wp_posts.post_date DESC
LIMIT 0, 10

I've also read this tutorial, but I'm not sure it applies in this case.
So to summarise: In the loop I only want to show the latest post (ordered by post_date) belonging to a term from a custom taxonomy and exclude other posts in that taxonomy in the loop. The loop also contains regular posts not part of the custom taxonomy and both types may belong to multiple categories and have tags.

A: Ok here is my answer ( it's more a suggestion)
My aproach would be first select every id from the posts that's the most recent in their term and belongs to the taxonomy post-series.
select * from wp_posts where ID in(
select ID from
(
select wp_posts.ID , wp_posts.post_date, d.name from wp_posts as a
join wp_term_relationships as b on ( a.ID = b.object_id)
join wp_term_taxonomy as c on (b.term_taxonomy_id = c.term_taxonomy_id)
join  wp_terms as d on (c.term_id = d.term_id)
where c.taxonomy = 'post-series'
group by d.name
having (wp_posts.post_date = max(wp_posts.post_date))
)tmp)

i grouped by d.name because you want one entry for that name and use having because you want the one entry that has the max post_date
then i select all the id's that come up from that query and use them in the where ID in () clause
I couldn't test this but this is how i would solve it in mysql.


text:
Q: How to pass numpy array inside of struct to ctypes function? I'm trying to wrap some third-party code from a library in my Python application. Essentially, the function I would like to call takes a struct as input that houses (among other things) pointers to double arrays. A simplified example would be:
myfunc.h:
typedef struct mystruct_t {
    int n;
    double *x;
} mystruct_t;

double myfunc(mystruct_t* data);

myfunc.c:
#include "myfunc.h"

double myfunc(mystruct_t* data) {
    double result = 0.;
    for(int i = 0; i < data->n; i++) {
        result += data->x[i];
    }
    return result;
}

Makefile:
CC = gcc
CFLAGS = -g -Wall -fPIC -lm -std=gnu99

all: libmyfunc.so

m.PHONY : clean

libmyfunc.so: myfunc.o
    gcc -shared -Wl,-soname,$@ -o $@ $^

%.o: %.c
    $(CC) -c $(CFLAGS) $<

clean:
    rm -vf libmyfunc.so *.o

I would like to wrap myfunc using NumPy, ctypes.Structure and numpy.ctypeslib so that I can pass NumPy arrays to myfunc as attributes of mystruct_t. So far I've been trying the following:
myfunc.py:
#!/usr/bin/env python
import numpy as np
import numpy.ctypeslib as npct
import ctypes
import os

array_1d_double = npct.ndpointer(dtype=np.double, ndim=1, flags='C_CONTIGUOUS')

class MyStruct(ctypes.Structure):
    _fields_ = [
        ('n', ctypes.c_int16),
        ('x', array_1d_double)
    ]

libmyfunc = npct.load_library('libmyfunc', os.path.dirname(__file__))
libmyfunc.myfunc.restype = ctypes.c_double
libmyfunc.myfunc.argtypes = [
    ctypes.POINTER(MyStruct)
]

x = np.array([1.0, 2.0, 3.0, 4.0])

mystruct = MyStruct()
mystruct.n = len(x)
mystruct.x = x

res = libmyfunc.myfunc(mystruct)

However, this fails with the following error message:
$ python myfunc.py
Traceback (most recent call last):
  File "./myfunc.py", line 26, in <module>
    mystruct.x = x
TypeError: cannot be converted to pointer

How do I define my function signatures correctly so that type conversion can happen? Or do I need to convert x somehow before assigning it to mystruct.x?
Unfortunately I cannot change the signature of the method I would like to call and I would like to not have to write wrapper C code unless it is absolutely necessary. The other questions and resources that I've found on this only deal with either ctypes.Structures or numpy.ctypeslib, but can you make them work together?
I've uploaded my reduced example as a gist so you can use it as a starting point.
Many thanks in advance!

A: You can remove array_1d_double. It is not needed.
The struct should be declared like this:
class MyStruct(ctypes.Structure):
    _fields_ = [
        ('n', ctypes.c_int),
        ('x', ctypes.POINTER(ctypes.c_double))
    ]

I've changed both types. You had c_int16, but the type you used in the C code is int. That maps to c_int. And likewise for the array, that is double*. In ctypes that is POINTER(ctypes.c_double).
The struct should be initialised like this:
mystruct = MyStruct()
mystruct.n = len(x)
mystruct.x = npct.as_ctypes(x)

With these changes, your code works as intended.


text:
Q: Tool or code to take a graphQL schema + set of operations and produce a schema subset? Let's say I've got the following:

*

*A giant GraphQL schema for some service (in .graphql or introspection json format)

*A set of operations that my code wants to perform against that query.

I'd really like to generate a "subset schema": just the pieces (types/enums/etc) of that big schema that my service actually uses. Is there a tool or a piece of code that can do this today easily?
The reason I want this is that we want to mock graphql services to write isolated tests of particular microservices, and we want to mock out just the bits we actually use, and keep track of any changes in our schema usage over time.

A: I never found a solution to this, so eventually I wrote one!
https://github.com/xometry/graphql-code-generator-subset-plugin - this tool is a plugin to the graphql-code-generator tool which will product a schema subset.


text:
Q: How do I store only the folder names as an array and not the while path (C#) So I know how to store the full path but not just the end folder names, for example I've already got an array but is there any method to remove certain characters from all arrays or just get folder names from a path?
Edit: string[] allFolders = Directory.GetDirectories(directory);
      That's what I use to get all folder names but that gets me the whole path
Edit:They need to be stored in an Array
Edit: sorry , I need an array with values such as "mpbeach","blabla","keyboard" and not E:\Zmod\idk\DLC List Generator\DLC List Generator by Frazzlee\ , so basically not the full path

A: This works.
string[] allFolders = Directory.EnumerateDirectories(directory)
            .Select(d => new DirectoryInfo(d).Name).ToArray();

This also works. Difference is we are using List<string> instead of string[]
List<string> allFolders = Directory.EnumerateDirectories(directory)
                          .Select(d => new DirectoryInfo(d).Name).ToList();

Example 1: Uses string[] allFolders
Test Folder

In VS IDE, in Debug Mode

Example 2: Uses List<string> allFolders
Test Folder

In VS IDE, in Debug Mode

Example 2: Uses string[] allFolders

A: No need for string operations... Just use DirectoryInfo class
var allFolders = new DirectoryInfo(directory).GetDirectories()
                .Select(x => x.Name)
                .ToArray();

A: NOTE I'm taking your question to mean how to extract the last folder name from a file URL. Others are reading this as how to extract the names of folders in a directory. If I'm wrong, it's because I'm misinterpreting your question.
Split by backslash to get folders. The next-to-last value is the last folder:
string folder = @"c:\mydrive\testfolder\hello.txt";
string[] parts = folder.Split('\\');
string lastFolder = parts[parts.Length - 1];
//Yields "testfolder";

Moving that forward to what you want:
 private string[] foldersOnly(){
  List<string> folders = new List<string>();
  string[] allFolders = Directory.GetDirectories(directory);
  foreach(string folder in allfolders){
       string[] parts = folder.Split('\\');
       folders.Add(parts[parts.Length-1]);
  }
  }
  return folders.ToArray();


text:
Q: ESM Error Occurs ONLY on Sever (Not in Development) I have a Node/Express application that I start with: node -r esm index.js (ie. I'm using the esm package to enable import syntax in my app).
In my dev environment, my app starts up great.  However, on my AWS (Ubuntu) server ... with the exact same code, and the exact same Node version (16.16.0) I get the error:
/home/ubuntu/project/admin/server/index.js:1
Error [ERR_REQUIRE_ESM]: require() of ES Module /home/ubuntu/project/admin/server/node_modules/lodash-es/lodash.js not supported.
Instead change the require of lodash.js in null to a dynamic import() which is available in all CommonJS modules.
    at Object.<anonymous> (/home/ubuntu/project/admin/server/index.js:1)
    at Generator.next (<anonymous>) {
  code: 'ERR_REQUIRE_ESM'
}

From what I can tell this is some kind of require vs. import issue, but what I can't understand is why I would have such an issue only on my server.
Can anyone explain how this could be possible?  I can't think of any environmental factor that could be responsible, other than Node itself (which again is at the same version).


text:
Q: JDBC Connectivity for Data Source in AWS Glue We are trying to bring oracle table catalogs into glue . But unable to read the data from source
We have tried to give all the possibilities in include path parameter but unable to bring the data
Anyone tried oracle as JDBC data store for AWS Glue ? Please help us to fix the issue


text:
Q: A working example of fancytabs I tried fancytabs by the example given in its manual as
\documentclass{scrbook}
\usepackage{scrpage2}
\usepackage{fancytabs}
\usepackage{lipsum}
% Capture chapter head
\let\oldchapter\chapter
\newcommand\temphead{}
\newcommand\chaphead{}
\renewcommand\chapter[2][\temphead]{%
\renewcommand\temphead{#2}%
\renewcommand\chaphead{#2}%
\oldchapter[#1]{#2}}
% Set central right header to display tab
% for both scrplain and scrheadings
\cohead[\fancytab{\chaphead}{\thechapter}]
{\fancytab{\chaphead}{\thechapter}}

\renewcommand*{\chapterpagestyle}{scrplain}
\pagestyle{scrheadings}
\begin{document}
\chapter{A chapter}
\lipsum
\lipsum
\end{document}

but it does not show the vertical lab displayed in the manual document or HERE. I just copied the exact example from manual. Where did I do wrong?

A: The package fancytabs uses the package TikZ to draw the tabs. To compute the correct position of the tabs TikZ needs two compilation runs of (pdf)latex.


text:
Q: How to import tfrecord files in a pandas dataframe? I have a tfrecord file and would like to import it in a pandas dataframe or numpy array.
I found tools to read tfrecords but they only work inside a tensorflow session, which is not the use case I have...
Thanks for any help I could get !

A: In Colab you can type (or on your cmd without !)
!pip install pandas-tfrecords

After installation you can use:
import pandas as pd
import pandas_tfrecords as pdtfr
pdtfr.tfrecords_to_pandas(file_paths=r'/folder/file.tfrecords')

Good luck!


text:
Q: Creating new column with values from multiple other columns I hope someone can help me with this one!
I have the following dataset and want to create a new column where the values of aver1, aver2 and aver3 are represented.
I tried it with rowSums but this did not work for me because when i put na.rm = TRUE also those rows who have only empty columns have 0 as their sum and I can not differentiate these from the ones that actually do have 0 as their value.
What I have:

count
aver1.
aver2.
aver3.

X
NA
1
NA

Y
1
NA
NA

X
NA
NA
0

What I want:

count
aver1.
aver2.
aver3.
aver_all

X
NA
1
NA
1

Y
1
NA
NA
1

X
NA
NA
0
0

the dput output:
structure(list(count = c(0,
0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 1, 1, 0, 0, 1, 0, 0, 0,
1, 1, 0, 1, 1, 0, 0, 1, 0, 0, 0, 1, 0, 0, 1, 0, 1, 0, 0, 0, 0,
0, 1, 0, 1, 0, 0, 1, 1, 0, 1, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 1,
1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 1, 0, 0, 0, 0, 1, 0, 1, 0,
0, 0, 1, 0, 0, 1, 0, 1, 0, 1, 0, 0, 0, 0, 1, 0, 1, 0, 1, 1, 1,
1, 0, 0, 0, 0, 0, 1, 0, 1, 1, 0, 1, 0, 0, 1, 0, 1, 1, 0, 1, 0,
1, 1, 1, 0, 1, 0, 0, 1, 0, 1, 1, 0, 0, 0, 0, 1, 0, 1, 0, 0, 0,
1, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1, 0,
1), start = c(NA, NA, NA, 5, NA, NA, NA, NA, 1, NA, NA, NA, NA,
1, 1, 1, NA, NA, 9, NA, NA, NA, 3, 4, NA, 11, 1, NA, NA, 1, NA,
NA, NA, 6, NA, NA, 5, NA, 5, NA, NA, NA, NA, NA, 1, NA, 3, NA,
NA, 3, 1, NA, 13, NA, 0, NA, NA, NA, NA, 1, NA, NA, NA, 12, 1,
NA, NA, NA, NA, NA, NA, NA, NA, 1, 1, NA, 1, NA, NA, NA, NA,
2, NA, 2, NA, NA, NA, 2, NA, NA, 1, NA, 3, NA, 3, NA, NA, NA,
NA, 10, NA, 1, NA, 0, 0, 1, 1, NA, NA, NA, NA, NA, 1, NA, 2,
7, NA, 1, NA, NA, 3, NA, 2, 6, NA, 3, NA, 1, 8, 1, NA, 1, NA,
NA, 0, NA, 0, 1, NA, NA, NA, NA, 3, NA, 0, NA, NA, NA, 1, NA,
NA, 0, NA, NA, NA, NA, NA, 2, NA, NA, 0, NA, NA, NA, NA, NA,
NA, 1, NA, 4), aver1 = c(NA, NA, NA, 0.5, NA, NA, NA, NA, NA,
NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA,
NA, NA, NA, NA, 0.166666666666667, NA, NA, NA, NA, NA, NA, NA,
NA, NA, NA, NA, NA, NA, NA, 0.133333333333333, NA, NA, NA, NA,
NA, NA, NA, NA, NA, 0, NA, NA, NA, NA, 0.266666666666667, NA,
NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA,
NA, NA, NA, NA, 0.566666666666667, NA, NA, NA, NA, NA, NA, NA,
NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA,
NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA,
NA, NA, 0.266666666666667, NA, NA, NA, NA, NA, NA, NA, NA, NA,
NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA,
NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA,
NA, NA, NA, NA, NA), aver2 = c(NA, NA, NA, NA, NA, NA, NA, NA,
NA, NA, NA, NA, NA, 0.333333333333333, 0.416666666666667, NA,
NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, 0.25, NA, NA, NA, NA,
NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, 0.916666666666667,
NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA,
NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, 0.472222222222222,
NA, NA, NA, NA, NA, NA, 0.388888888888889, NA, NA, NA, 0.0833333333333333,
NA, NA, NA, NA, 0.0555555555555556, NA, 0.111111111111111, NA,
NA, NA, NA, NA, NA, NA, NA, 0.305555555555556, NA, 0.861111111111111,
NA, NA, NA, NA, NA, NA, NA, NA, 0.194444444444444, NA, NA, NA,
NA, NA, 0.611111111111111, NA, NA, NA, NA, 0, NA, 1, NA, 0.694444444444444,
NA, NA, NA, NA, 0.5, NA, 1, NA, NA, NA, NA, NA, 0.0277777777777778,
NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, 0.138888888888889,
NA, NA, 0.583333333333333, NA, NA, NA, NA, NA, NA, 0.194444444444444,
NA, NA), aver3 = c(NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA,
NA, NA, NA, NA, 0, NA, NA, NA, NA, NA, NA, NA, 0.514285714285714,
NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA,
NA, NA, NA, NA, NA, NA, NA, NA, NA, 1, 0.0285714285714286, NA,
NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA,
NA, NA, NA, NA, NA, 1, 0.214285714285714, NA, NA, NA, NA, NA,
NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, 0.0142857142857143, NA,
NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA,
NA, NA, NA, NA, 0.614285714285714, NA, NA, NA, NA, 0.371428571428571,
NA, NA, NA, NA, 0, NA, NA, NA, NA, NA, NA, NA, NA, 0, NA, NA,
NA, NA, NA, 0.9, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, 0.0571428571428571,
NA, NA, 0.128571428571429, NA, NA, NA, NA, NA, NA, NA, NA, NA,
NA, NA, NA, NA, NA, NA, NA, NA, 0.1)), row.names = c(NA, -170L
), class = c("tbl_df", "tbl", "data.frame"))

A: This is an example that allows you to sum your selected variables from your data-frame (let's call this data-frame: 'df').
df$aver_all <- apply(df[, c("aver1", "aver2", "aver3")], 1, function(x) sum(x, na.rm=TRUE))

It will add 0s to rows where there are only NAs for aver1-2-3.
The next code will replace by NAs, the rows with full NAs.
df$aver_all <- apply(df[, c("aver1", "aver2", "aver3")], 1, function(x) ifelse(FALSE %in% is.na(x), sum(x, na.rm=TRUE), NA))

A: Given that you have said that you also have rows where all column values are NAs, I will create an additional row in your dataset that fulfills this condition:
dataset <- tibble(count = c("X", "Y", "X", "Z"), aver1. = c(NA, 1, NA, NA),
                  aver2. = c(1, NA, NA, NA), aver3. = c(NA, NA, 0, NA))

You can use the conditional case_when (https://dplyr.tidyverse.org/reference/case_when.html), which will allow you to set values depending on the conditions you choose for each row. In this case, you could use:
dataset$aver_all <- case_when(is.na(aver1.) & is.na(aver2.) & is.na(aver3.) ~ NA_real_,
                              aver1. | aver2. | aver3. ~ 1,
                              TRUE ~ 0)

Here the first condition sets rows where all values are NA to NA, the second sets a 1 if at least one of the three values of a row is a 1; and finally if none of these conditions is satisfied, a 0 is set.


text:
Q: Does $xy > xz$ imply $y > z$? $xy > xz$
We don't know the sign of $x$.
Can we conclude $y>z$ from above?

A: No, because if $x<0$ then we have
$$xy>xz\implies y<z$$
as the direction of the inequality changes when multiplied by a negative number.
If x is on the other hand positive we have
$$xy>xz\implies y>z$$
as the inequality remains
Very simple example is $x=-1$