text:
Q: Communicating with an external service: internal server error 500 I'm trying to make a GET request to an HTTPS service ( https://broker.bronos.net ). This service is an API that communicates with a client on my LAN. I can't get it to work via functions.https.get(URL, (s,ss) => {});
Please help -- I'm very new to web development, let alone google actions.
I'm using the apiai-starter-app as the base, which functions perfectly fine until I add the line above which returns internal server error 500.
Note: I've tried before adding billing to the project and after as well. Neither work.
Edit:
using this
        const https = require('https');

https.get('https://broker.bronos.net/v1/CLIENT_ID/ROOM_NAME/ACTION/PARAM', (resp) => {
  let data = '';

  // A chunk of data has been recieved.
  resp.on('data', (chunk) => {
    data += chunk;
  });

  // The whole response has been received. Print out the result.
  resp.on('end', () => {
            if (requestSource === googleAssistantRequest) {
        sendGoogleResponse(JSON.parse(data).explanation); // Send simple response to user
      } else {
        sendResponse(JSON.parse(data).explanation); // Send simple response to user
      }
  });

}).on("error", (err) => {
                if (requestSource === googleAssistantRequest) {
        sendResponse("Error: " + err.message); // Send simple response to user
      } else {
        sendResponse("Error: " + err.message); // Send simple response to user
      }
});

A: Firebase's functions have limited access to external APIs on the free tier. By upgrading to Blaze or Flame plans you will be able to make external API calls.
Enabling Firebase Blaze plan + the following code worked
        const https = require('https');

https.get('https://broker.bronos.net/v1/CLIENT_ID/Living%20Room/volume/20', (resp) => {
  let data = '';

  // A chunk of data has been recieved.
  resp.on('data', (chunk) => {
    data += chunk;
  });

  // The whole response has been received. Print out the result.
  resp.on('end', () => {
            if (requestSource === googleAssistantRequest) {
        sendGoogleResponse(JSON.parse(data).explanation); // Send simple response to user
      } else {
        sendResponse(JSON.parse(data).explanation); // Send simple response to user
      }
  });

}).on("error", (err) => {
                if (requestSource === googleAssistantRequest) {
        sendResponse("Error: " + err.message); // Send simple response to user
      } else {
        sendResponse("Error: " + err.message); // Send simple response to user
      }
});


text:
Q: access - Only append unique results I have a system where new users can be added, and i want to make a query that checks to see if there are duplicate results with the same Name_ID and only adds the unique results. (More explained below)
Table1
Name_ID ¦ Name
-------------------
1       ¦ Michael
2       ¦ Rebecca
3       ¦ Sammy

Table2
Name_ID ¦ Name
-------------------
1       ¦ Michael
2       ¦ Rebecca

These are in two separate database files as Table2 is supposed to be an archive.
What i want to do is to use a query ONLY to append the Name_ID's that are unique from table1 to table2, i.e. only appending 3 but leaving out Name_ID 1 and 2.
One last thing, i dont want to use SQL for this solution but would like to know if MS-Access has any in-built features that can solve this.
EDIT: Apparently there is no solution for without SQL so how would this be achieved with SQL?

A: You should use this query:
INSERT INTO Table2(Name_ID, Name)
SELECT Name_ID, Name
FROM Table1 LEFT JOIN Table2 ON Table1.Name_ID = Table2.Name_ID
WHERE Table2.Name_ID IS NULL

either, make a query or use Docmd.RunSQL command

A: The MS Access built-in feature to prevent duplicates is a No Duplicates index on the field.
A primary key is a type of such an index. These indexes will prevent insertion of a record in case of a duplicate value on the indexed field.
Please see more here

redpajama_set_name: RedPajamaStackExchange


text:
Q: Android Studio SQL Server connection with a table showing nothing I was doing a simple application that can register users and post like articles made by users.
As the code of the class that register the user works perfectly, the post one doesn't work.
With the post class I can save the title and the description of the post into the database, but no error and nothing is displayed in the database.
Here is my posts code (CrudPost.java):
package com.example.newsapp4;

import androidx.appcompat.app.AppCompatActivity;

import android.annotation.SuppressLint;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.StrictMode;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import com.example.newsapp4.Connection.ConnectionClass;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.Statement;

public class CrudPost extends AppCompatActivity {

    EditText etTitle, etDesc;
    Button btnPost, btnBack;

    //Conexion con SQL Server
    Connection con;
    Statement stmt;

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

        etTitle = findViewById(R.id.etTituloPost);
        etDesc = findViewById(R.id.etDescPost);
        btnPost = findViewById(R.id.btnPostear);
        btnBack = findViewById(R.id.btnAtras);

        btnBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });

        btnPost.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                new CrudPost.makePost().execute("");
            }
        });
    }

    public class makePost extends AsyncTask<String, String, String>{
        String z = "";
        Boolean isSuccess = false;

        @Override
        protected void onPreExecute() {
            Toast.makeText(CrudPost.this, "Sending post to database", Toast.LENGTH_SHORT).show();
        }

        @Override
        protected void onPostExecute(String s) {
            Toast.makeText(CrudPost.this, "Data sent!", Toast.LENGTH_SHORT).show();
            etTitle.setText("");
            etDesc.setText("");
        }

        @Override
        protected String doInBackground(String... strings) {
            try {
                con = connectionClass(ConnectionClass.ip.toString(), ConnectionClass.port.toString(),ConnectionClass.db.toString(),ConnectionClass.un.toString(),ConnectionClass.pass.toString());
                if(con == null){
                    z = "Check your Internet Connection";
                }else{
                    //Inserta lo que escribimos en los campos del usuario, contraseña y email.
                    String sql = "INSERT INTO articles (Title, Descri) VALUES ('"+ etTitle.getText()+"', '"+etDesc.getText()+"')";
                    stmt = con.createStatement();
                    stmt.executeUpdate(sql);
                }
            }catch(Exception e){
                isSuccess = false;
                z = e.getMessage();
            }
            return z;
        }
    }

    //Conexion a la base de datos de SQL Server
    @SuppressLint("NewApi")
    public Connection connectionClass(String server, String port, String database, String username, String pass){
        StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
        StrictMode.setThreadPolicy(policy);
        Connection connection = null;
        String connectionURL = null;
        try{
            //Obtencion del driver jtds para la conexion con la base de datos
            Class.forName("net.sourceforge.jtds.jdbc.Driver");
            connectionURL= "jdbc:jtds:sqlserver://"+ server + ":" +port+ ";"+ "databaseName="+ database +";user="+username+";password="+pass+";";
            connection = DriverManager.getConnection(connectionURL);
            System.out.println(connectionURL);
        }catch (Exception e){
            Log.e("SQL Connection Error : ", e.getMessage());
            System.out.println(connectionURL);
        }

        return connection;

    }

}

And I'm using a connectionClass.java that has got the attributes that connects to the database:
package com.example.newsapp4.Connection;

public class ConnectionClass {
    public static String ip = "My IP";
    public static String un = "My username";
    public static String pass = "My password";
    public static String db = "My database";
    public static String port = "My port";
}

As I said, in the register class that is the MainActivity.java class everthing works perfectly:
This is my MainActivity.java class:
package com.example.newsapp4;

import androidx.appcompat.app.AppCompatActivity;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.StrictMode;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.VideoView;

import com.example.newsapp4.Connection.ConnectionClass;
import com.google.android.gms.auth.api.signin.GoogleSignIn;
import com.google.android.gms.auth.api.signin.GoogleSignInAccount;
import com.google.android.gms.auth.api.signin.GoogleSignInClient;
import com.google.android.gms.auth.api.signin.GoogleSignInOptions;
import com.google.android.gms.common.SignInButton;
import com.google.android.gms.common.api.ApiException;
import com.google.android.gms.tasks.Task;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.Statement;

public class MainActivity extends AppCompatActivity {

    Button botonInicio, botonRegistro;
    VideoView videoBack;
    EditText pass, email, username;
    Intent intencion;

    //Conexion con SQL Server
    Connection con;
    Statement stmt;

    //TextView
    TextView status;

    //Google SignIn Button
    int RC_SIGN_IN = 0;
    SignInButton signInButton;
    GoogleSignInClient mGoogleSignInClient;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        videoBack = (VideoView) findViewById(R.id.vvBack);

        //btnRegistro
        botonRegistro = (Button) findViewById(R.id.btn_registro);

        //TextView
        status = (TextView) findViewById(R.id.tvRegister);

        //editText
        email = (EditText) findViewById(R.id.etEmail);
        pass = (EditText) findViewById(R.id.etPass);
        username = (EditText) findViewById(R.id.etUsername);

        //Google
        signInButton = findViewById(R.id.googleSignInBtn);

        //El boton de Google, una vez checkeado que es un inicio de sesion correcto, ejecutrá el metodo signIn()
        //el cual
        GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN).requestEmail().build();
        mGoogleSignInClient = GoogleSignIn.getClient(this, gso);
        signInButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                signIn();
            }
        });

        botonRegistro.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                    new MainActivity.registerUser().execute("");
            }
        });

        botonInicio = (Button) findViewById(R.id.btn_inicioSesion);

        String path ="android.resource://com.example.newsapp4/"+R.raw.mix;
        Uri u = Uri.parse(path);
        videoBack.setVideoURI(u);
        videoBack.start();

        videoBack.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
            @Override
            public void onPrepared(MediaPlayer mp) {
                mp.setLooping(true);
            }
        });
        //Intent that redirects the user to the login activity
        botonInicio.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intencion = new Intent(MainActivity.this, LoginActivity.class);
                startActivity(intencion);
                finish();
            }
        });
    }

    //Google Register (dont affect the SQL Server connection)
    private void signIn(){
        Intent signInIntencion = mGoogleSignInClient.getSignInIntent();
        startActivityForResult(signInIntencion, RC_SIGN_IN);
    }

    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        GoogleSignInClient getSignInIntent
        if (requestCode == RC_SIGN_IN){
            Task<GoogleSignInAccount> task = GoogleSignIn.getSignedInAccountFromIntent(data);
            handleSignInResult(task);
        }
    }

    private void handleSignInResult(Task<GoogleSignInAccount> completedTask) {
        try{
            GoogleSignInAccount account = completedTask.getResult(ApiException.class);
            startActivity(new Intent(MainActivity.this, menuContent.class));
        }catch(ApiException e){
            Log.w("Google Sign In Error", "SignInResult: failed code=" + e.getStackTrace());
            Toast.makeText(this, "Failed", Toast.LENGTH_SHORT).show();
        }
    }

    protected void onStart(){
        GoogleSignInAccount account = GoogleSignIn.getLastSignedInAccount(this);
        if (account != null){
            startActivity(new Intent(MainActivity.this, menuContent.class));
        }
        super.onStart();
    }

//Here stars the SQL Server connection to the database code

    //Store the posts that the user writes in the app
    public class registerUser extends AsyncTask<String, String, String>{
        String z = "";
        Boolean isSuccess = false;

        @Override
        protected void onPreExecute() {
            status.setText("Sending data to Database");
        }

        @Override
        protected void onPostExecute(String s) {
            status.setText("Registration Succesfull");
            username.setText("");
            email.setText("");
            pass.setText("");
        }

        @Override
        protected String doInBackground(String... strings) {
            try {
                con = connectionClass(ConnectionClass.ip.toString(), ConnectionClass.port.toString(),ConnectionClass.db.toString(),ConnectionClass.un.toString(),ConnectionClass.pass.toString());
                if(con == null){
                    z = "Check your Internet Connection";
                }else{
                    //Insert all the data into the database.
                    String sql = "INSERT INTO users (Username, Pass, Email) VALUES ('"+ username.getText()+"', '"+pass.getText()+"','"+email.getText()+"')";
                    stmt = con.createStatement();
                    stmt.executeUpdate(sql);
                }
            }catch(Exception e){
                    isSuccess = false;
                    z = e.getMessage();
            }
            return z;
        }
    }

    //SQL Server connection to the database
    @SuppressLint("NewApi")
    public Connection connectionClass(String server, String port, String database, String username, String pass){
        StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
        StrictMode.setThreadPolicy(policy);
        Connection connection = null;
        String connectionURL = null;
        try{
            //Obtencion del driver jtds para la conexion con la base de datos
                Class.forName("net.sourceforge.jtds.jdbc.Driver");
                connectionURL= "jdbc:jtds:sqlserver://"+ server + ":" +port+ ";"+ "databaseName="+ database +";user="+username+";password="+pass+";";
                connection = DriverManager.getConnection(connectionURL);
                System.out.println(connectionURL);
        }catch (Exception e){
            Log.e("SQL Connection Error : ", e.getMessage());
            System.out.println(connectionURL);
        }

        return connection;

    }

    //Metodos para que el video en el fondo funcione.
    protected void onResume(){
        videoBack.resume();
        super.onResume();
    }
    protected void onPause(){
        videoBack.suspend();
        super.onPause();
    }
    protected void onDestroy(){
        videoBack.stopPlayback();
        super.onDestroy();
    }
}

There are some methods that do other things like onResume(), onPause() and onDestroy() or the Google Register methods that don't affect the SQL Server connection.
And here is the interesting part of the code, it displays no error!, but nothing is saved in the database.
At this point I don't know what should I do.
Thanks for your time!


text:
Q: How can i change the directory in this VBA code? VBA "Excel to TXT or CSV" I really want to change the directory of this code in Application.ActiveWorkbook.Path but i don't know where to put it.
Public Sub CharacterSV()
    Const DELIMITER As String = "|"
    Dim myRecord As Range
    Dim myField As Range
    Dim nFileNum As Long
    Dim sOut As String

    nFileNum = FreeFile
    Open ActiveWorkbook.Name & ".txt" For Output As #nFileNum
    For Each myRecord In Range("A1:A" & _
                Range("A" & Rows.Count).End(xlUp).Row)
        With myRecord
            For Each myField In Range(.Cells, _
                    Cells(.Row, Columns.Count).End(xlToLeft))
                sOut = sOut & DELIMITER & myField.Text
            Next myField
            Print #nFileNum, Mid(sOut, 2)
            sOut = Empty
        End With
    Next myRecord
    Close #nFileNum
End Sub

I tried to figure it out, and really want to learn VBA, but i couldn't get it to work.
Thanks in advance!

A: Add this to your code:
Dim fname as string
fname = "c:\documents and settings\desktop\"
Open fname & ActiveWorkbook.Name & ".txt" For Output As #nFileNum
Replace desktop with your directory and the open will open the new file in your directory, take care to write a real and correct path in fname.

A: Thank you for the inspiration.
I just passed by another code that made it way more easy.
Cause i just wanted to add the file in the directory were i'm working from, but wanted to make the vba dynamic.
So i used ActiveWorkbook.FullName instead of ActiveWorkbook.Name.
I also added the name from the sheet to it in " - " & ActiveSheet.Name &
This is the final code (also added name of sheet):
Public Sub Worksheet_naar_TXT_Pipe_delimiter()
    Const DELIMITER As String = "|"
    Dim myRecord As Range
    Dim myField As Range
    Dim nFileNum As Long
    Dim sOut As String

    nFileNum = FreeFile
    Open ActiveWorkbook.FullName & " - " & ActiveSheet.Name & ".txt" For Output As #nFileNum
    For Each myRecord In Range("A1:A" & _
                Range("A" & Rows.Count).End(xlUp).Row)
        With myRecord
            For Each myField In Range(.Cells, _
                    Cells(.Row, Columns.Count).End(xlToLeft))
                sOut = sOut & DELIMITER & myField.Text
            Next myField
            Print #nFileNum, Mid(sOut, 2)
            sOut = Empty
        End With
    Next myRecord
    Close #nFileNum
End Sub

Thanks for your response, this brought me to the idea!


text:
Q: Splitting an array by performing an arithmetic function in ruby I have an array in Ruby like [3,4,5] and I want to create sub-arrays by diving or multiplying. For example, I want to multiply each number in the array by 2, 3, and 4, returning [[6,9,12],[8,12,16],[10,15,20]]
After that, what's the best way to count the total number of units? In this example, it would be 9, while array.count would return 3.
Thanks

A: The simplest way I could think of was:
[3,4,5].map { |v|
    [3,4,5].map { |w|
        w * v
    }
}

I'm sure there is a more elegant way.
As for the count you can use flatten to turn it into a single array containing all the elements.
[[9, 12, 15], [12, 16, 20], [15, 20, 25]].flatten
 => [9, 12, 15, 12, 16, 20, 15, 20, 25]

A: You might find it convenient to use matrix operations for this, particularly if it is one step among several involving matrices, vectors, and/or scalars.
Code
require 'matrix'

def doit(arr1, arr2)
   (Matrix.column_vector(arr2) * Matrix.row_vector(arr1)).to_a
end

def nbr_elements(arr1, arr2) arr1.size * arr2.size end

Examples
arr1 = [3,4,5]
arr2 = [3,4,5]

doit(arr1, arr2)
  #=> [[ 9, 12, 15],
  #    [12, 16, 20],
  #    [15, 20, 25]]

nbr_elements(arr1, arr2)
  #=> 9

doit([1,2,3], [4,5,6,7])
  #=> [[4,  8, 12],
  #    [5, 10, 15],
  #    [6, 12, 18],
  #    [7, 14, 21]]

nbr_elements([1,2,3], [4,5,6,7])
  #=> 12

Alternative
If you don't want to use matrix operations, you could do it like this:
arr2.map { |e| [e].product(arr1).map { |e,f| e*f } }

Here's an example:
arr1 = [1,2,3]
arr2 = [4,5,6,7]

arr2.map { |e| [e].product(arr1).map { |e,f| e*f } }
  #=> [[4,  8, 12],
  #    [5, 10, 15],
  #    [6, 12, 18],
  #    [7, 14, 21]]


text:
Q: Request header field * is not allowed by Access-Control-Allow-Headers in preflight response first of all: I already found similar problems to mine, but due to the fact that I am an absolute beginner in react and javascript, I was not able to both fully understand and solve my problem with the given tips and explanations.
My Problem: I want to make a fetch request via a given api (not mine), but get the CORS error written above, when I want to include the "Language" header. It appears that I am not allowed to make this request - the preflight response in the browser also shows that.
Interesting part is: I get an response, if I make a Curl -X get request with the neccessary header in the command window.
So my question is: why am I allowed to make that request in the command window, but not in the browser? Is there any workaround or do I need to make some setting changes for chrome?`
JFYI, my Code - doesn´t work:
export const Items = () => {
  fetch("https://requestedurl", {
    headers: {
      Accept: "application/json",
      Language: "de",
    },
  }).then((res) => res.json())
    .then((res) => console.log(res));
};

Works in command prompt:
curl -X GET -H "Language: de" https://requestedurl
Thanks for your help :)

A: Browsers make a distinction between simple requests and ones that are complex. The distinction mainly boils down to "is it more complex than a <form> tag?".
Because of this, you can't—for example—send a request to a different domain with an Authorization header or in your case Language.
It is the browser that includes this restriction, which is why cURL is not affected. The (API) server can opt-in to allow CORS requests from some or all origins by sending the browser a header.
Properly configured, this will happen:

*

*The browser decides a request is "not simple"

*Instead of your request, it executes a HEAD (not GET/POST) request to the other server and tells the server what your site's domain is and any custom headers that you've set.

*The other server will send if it's okay if your domain (origin) is allowed to send it requests and also a list of (custom) headers that it will accept.

*If the other server gives the green light, the browser will then allow your original GET/POST/(etc) request to go through. Otherwise, you'll see an error like you do currently.

The previously linked article goes in depth on what CORS is. If you have no control over the (API) server, you can't make those changes. One option would be to run a proxy server on your own domain, which will make a request "simple" (as it would no longer be cross origin).


text:
Q: Android Message Counter Hi guys I'm trying to implement an application which will get the contact name and will search for number of messages received from that particular contact name and will display the count. But I'm facing unexpected problem occurred during run of my pgm. here is my code
 package com.mycompany.myapp;

import android.app.*;
import android.net.Uri;
import android.os.*;
import android.view.*;
import android.widget.*;
import android.widget.AdapterView.OnItemClickListener;
import android.media.*;
import android.telephony.*;
import java.util.*;

import android.content.*;
import android.graphics.*;
import android.database.*;
import android.provider.*;

public class MainActivity extends Activity
{
    /** Called when the activity is first created. */
    DatePicker datepicker;
    private static Context context;
    Map contactMap;
    String selection;
    @Override
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);

        setTitle("Tuxian");
        setContentView(R.layout.main);
        MainActivity.context = getApplicationContext();

        GetPeopleList people = null;
        final AutoCompleteTextView txt = (AutoCompleteTextView) findViewById(R.id.autocompletetxtview);

        txt.setOnItemClickListener(new OnItemClickListener() {
            public void onItemClick(AdapterView<?> parent, View view, int position, long rowId) {
                selection = (String)parent.getItemAtPosition(position);
                //TODO Do something with the selected text
            }
        });

        List list = displayContacts(context);
        ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, R.layout.list_item, list);
        txt.setAdapter(adapter);
        txt.setTextColor(Color.GREEN);
        datepicker = (DatePicker) findViewById(R.id.datePicker);
        Button button = (Button) findViewById(R.id.btn);

        button.setOnClickListener(new View.OnClickListener() {

                @Override public void onClick(View v)
                {
                    Toast.makeText(getBaseContext(), "Date : " + (datepicker.getMonth() + 1) + "/" + datepicker.getDayOfMonth() + "/" + datepicker.getYear(), Toast.LENGTH_LONG).show();
                    Toast.makeText(getBaseContext(), "Total : " + msgCnt(selection), Toast.LENGTH_SHORT).show();
                }
            });
    }
    private List displayContacts(Context c) {
        ContentResolver cr = c.getContentResolver();
        Cursor pCur = null;
        contactMap = new HashMap<String, String>();
        Cursor cur = cr.query(ContactsContract.Contacts.CONTENT_URI, null, null, null, null);
        List l = new ArrayList();
        if (cur.getCount() > 0) {
            while (cur.moveToNext()) {
                String id = cur.getString(cur.getColumnIndex(ContactsContract.Contacts._ID));
                String name = cur.getString(cur.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
                if (Integer.parseInt(cur.getString( cur.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER))) > 0) {
                    pCur = cr.query( ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, ContactsContract.CommonDataKinds.Phone.CONTACT_ID +" = ?", new String[]{id}, null);
                    while (pCur.moveToNext()) {
                        String phoneNo = pCur.getString(pCur.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
                        //Toast.makeText(getBaseContext(), "Name: " + name + ", Phone No: " + phoneNo, Toast.LENGTH_SHORT).show();
                        l.add(name);
                        contactMap.put(name, phoneNo);
                    }
                }
            }
        }
        return l;
    }
    private int msgCnt (String phNum) {

         Uri uri = Uri.parse("content://sms/inbox");

         ContentResolver contentResolver = context.getContentResolver();

         String where = "address="+phNum;
         Cursor cursor = contentResolver.query(uri, new String[] { "_id", "thread_id"}, where, null,
                                               null);
         int count = cursor.getCount();

        return count;
    }
}

And I'd added the permission in Manifest file as follows:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.mycompany.myapp"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="11" />
    <uses-permission android:name="android.permission.READ_SMS"/>

    <application

        android:label="@string/app_name" >
        <activity
            android:label="@string/app_name"
            android:name=".MainActivity" >
            <intent-filter >
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>
    <uses-permission android:name="android.permission.READ_CONTACTS"/>
</manifest>

Please somebody help me to figure it out! Thanks in advance

A: What is the problem exactly? I would recommend changing the getMsgCount function to use something along the lines of:
    String str_query = "content://sms/inbox";
    Uri uri = Uri.parse(str_query);
    String where = "address = ?";
    String columns[] = new String[] {"_id", "thread_id", "msg_count"};
    Cursor c = context.getContentResolver().query(uri, columns, where, new String[]{phNum}, null);

Pay attention to this because it really depends a lot of times on the OEM and how their Contacts address book is set up. I believe what you are really trying to do is get the msg_count column.
However I am not sure if address is even the correct column to use. I know that the SMS Inbox is where you should be looking if I am correct.


text:
Q: PHP preg_replace between 2 delimiters Hi I am trying to replace , with | from a long string with in braces [] but the following seems to be failed.
Here is the string.

ID: 3a0dd504341fb10a055xxxxxx, time: Wed Feb 01 12:54:39 EST 2012, client: 10.192.34.13, user: User [ID: 1456xcvererwe, session ID: sdfweerwer234325433 ], action: USER_ACTION_ITEM, action id: 36014, result: FAIL, reason: USER_EXCEPTION, arguments: [abcd, test12 , testing ]

Here is what I want as output.

ID: 3a0dd504341fb10a055xxxxxx, time: Wed Feb 01 12:54:39 EST 2012, client: 10.192.34.13, user: User [ID: 1456xcvererwe | session ID: sdfweerwer234325433 ], action: USER_ACTION_ITEM, action id: 36014, result: FAIL, reason: USER_EXCEPTION, arguments: [abcd | test12 | testing ]

I tried following
$text = preg_replace("/(^[)(.*)(])/U","|",$text);

A: Use preg_replace_callback
$text = 'ID: 3a0dd504341fb10a055xxxxxx, time: Wed Feb 01 12:54:39 EST 2012, client: 10.192.34.13, user: User [ID: 1456xcvererwe, session ID: sdfweerwer234325433 ], action: USER_ACTION_ITEM, action id: 36014, result: FAIL, reason: USER_EXCEPTION, arguments: [abcd, test12 , testing ]';

function rep($r){
    return "[". preg_replace('/\s*,\s*/',' | ', $r[1]). "]";
}
echo preg_replace_callback('/\[([^\]]+)\]/i', 'rep', $text);


text:
Q: Oracle LAG Function for each unique row I have the following query:
SELECT
        EEEV_EMPL_ID,
        EEEV_DT,
        EEEV_CCTR_ID,
        LAG(EEEV_CCTR_ID, 1, ' ') OVER(ORDER BY EEEV_EMPL_ID DESC, EEEV_END_DT ASC) AS prev
FROM
        CDAS.VDWHEEEV1 eeev1
ORDER BY
        EEEV_EMPL_ID

So the table can have multiple rows for each EEEV_EMPL_ID.  I want to lag for each group of unique empl_id's.  I dont want to lag from one empl_id to another.  So if it is the last row of the group, the lag value should be Null or something.  Right now it is just lagging to the next row, even if it is a different empl_id.  How do I accomplish that.  I hope that makes sense.

A: If I understand correctly, you want partition by:
    LAG(EEEV_CCTR_ID, 1, ' ') OVER (PARTITION BY EEEV_EMPL_ID ORDER BY EEEV_END_DT ASC) AS prev


text:
Q: PrincipalPermissionMode | How does different options work Relating to various modes of principlePermissionMode attribute of <serviceAuthorization> element, few queries below -

*

*Can you provide/point me to an example how PrincipalPermission can be used when its mode is selected as "Custom" in configuration?

*What is the significance of "None" and "Always" modes? With "None", does it mean Thread.CurrentPrincipal will be empty?

*With "UseAspNetRoles" mode, my understanding is, the authorization happens with <roleProvider> selected in the config and the "Name" and "Roles" field values of PrincipalPermissionMode are validated against it. If the clientCredentialType is certificate, MSDN shows how it gets validated. Does the settings in <roleProvider> do not play any role here? Since UseAspNetRoles mode is used, it has check the <roleProvider> to get the source against which the roles is to be checked. How does certificate credential type relates to <roleProvider> in this case and what should be the setting required in <roleProvider> for this credential type?

Thanks!


text:
Q: How i prevent calling nested then method? Basically, I have login api and nested then function is there, my question is how I stop from calling as certain condition, pasting my code:
login(values.email, values.password)
  .then((res) => {
    if (res?.value?.data?.unverified) {
      console.log('>>> in', res, RESEND_VERIFICATION_EMAIL_DIALOG);
    } else getMe(true);
  })
  .then(() => ...)

So, if it comes in the above if I have to stop calling nested then and all code.
Any help would be appreciated, thanks in advance :).

A: you'd better use .then, .catch
login(values.email, values.password)
.then((res) => {
    if (res?.value?.data?.unverified) {
      console.log('>>> in', res, RESEND_VERIFICATION_EMAIL_DIALOG);
    } else getMe(true);
}).catch(function(e) {
    console.log(e); // "oh, no!"
});

PS: I found a good resource about stopping the promise chain which I hope would help you


text:
Q: In .NET, is finally equivalent to try-catch-throw? I am writing a static analysis tool for CIL. Control flow analysis would be simplified if finally blocks could be interpreted as try-catch blocks with a rethrow inside the catch.
In C#, I fail to see the difference between
try
{
    // ...
}
finally
{
    // finally code here
}

and
try
{
    // ...
}
catch
{
    // finally code here
    throw;
}

or between
try
{
    // ...
}
catch(Exception e)
{
    // catch code here
}
finally
{
    // finally code here
}

and
try
{
    try
    {
        // ...
    }
    catch (Exception e)
    {
        // catch code here
    }
}
catch
{
    // finally code here
    throw;
}

There are even a finally block and endfinally instructions in the CIL. There must be a difference, is there?

A: No - a finally block is executed even if no exception is thrown, and also even if another catch block catches the exception. (That's true whether the catch block then throws an exception itself or not.)
Oh, and a finally block will also be executed if the try block returns from the method.
Basically, if you want code to always execute when execution leaves the statement, finally is what you want. Although in C# I find I rarely write an explicit finally block - a using statement nearly always makes the code simpler.

A: To add to Jon's -- correct, of course -- answer: you are actually describing a try-fault block. That is, a try-fault block is equivalent to try followed by catch-everything and automatic re-throw.
C# does not support try-fault blocks but CIL does, so if you're ever reading IL and you see a fault block, now you know what it is.
Also, it is correct to say that
try{}
catch {}
finally {}

is equivalent to
try
{
    try { }
    catch { }
}
finally { }

And in fact inside the C# compiler that's what it does; all try-catch-finally blocks are rewritten into a nested try-catch inside a try-finally. That is a simplifying assumption that can help when writing a static analyzer.


text:
Q: Search for which Stack Exchange site to use I would like to be able to search on the Stack Exchange gateway for a subject and get a list of the most relevant sites (possibly Google instant style, filtering the normal list). Searching is often a lot faster than scrolling through a list, and this one is growing all of the time. If there are several similar sites it could also help seeing the difference without reading through several FAQs first. This could be a good answer to "where should I post this question?".
The search should probably be based more on the tags and the site FAQ/description then on the actual questions.

A: Not exactly what you want, but Stack Exchange already has a search feature which searches all Stack Exchange sites. This should give you a good idea where to post your subject.
Here's an answer with a helpful image by Jeff.

But wait, there is more.
To fine-tune the search, you can set up a filter on Stack Exchange site (tag-filters here corresponds to this feature) to limit which sites and which tags (among other conditions) are searched.

A: Since all of the Stack Exchange sites are all on one page in the sites list you can use Ctrl + F to search for the terms you are looking for. However, your keywords might not be found. So you will have to use other similar search terms manually, instead of with the help of a search engine, to find out where questions should be asked.


text:
Q: changing an angularjs application url before loading I'm using an instagram api which the result is redirecting to my app. problem is here that instgram doesn't accept the url including #
for example :http://localhost:3000/#/functionalists is not accepted because of /#/
my app is using angularjs which uses this url style for routing . is there any way to change the url redirected by instagram to a compatible on with my app??

A: i think it would be easier to change the way you redirect in your app.
If You're using $locationprovider yo can set the html5mode to true, and then change your base to '/' that way the '#' simbol would not be used.


text:
Q: copy constructor for a linked list classes So I want to copy a whole linked list classes, I have trouble figuring it out how to do so,
class list{
   public:
  list(const list &t);
private:
  struct Node{
    int x;
    Node *next;
  }*p;

I started with something like this:
list::list(const list &t){
  Node* q;
  q=new Node;
  while (p!=NULL){
    q->x= p->x;}
}

but I'm not sure if I am on the right track or what. I also have trouble how should I test such a copy constructor? For example I have list l1, then i insert couple integers into a list and then how I can copy it?

A: In your example it never will work if you initialized p or will work forever if p != NULL. You must allocate new nodes while traversing through t list:
  p = NULL;
  Node* copy = l.p;
  Node* insert = p;
  Node* inserted_el = NULL;
  while (copy){
     insert = new Node();
     insert->x = copy->x;
     insert->next = NULL;
     if (inserted_el) {
         inserted_el->next = insert; //copy memory pointer to next element
     } else {
         p = insert; //copy memory pointer to list head
     }
     copy = copy->next;
     inserted_el = insert;
  }

This is basic idea. Also don't forget to implement assign operator and destructor.
Usage:
list t1;
//insert nodes
list t2(t1);

A: The biggest trouble in your code is that you do not duplicate each node of the list while you need to do so.
Here is the code of the ctor:
list::list(const list &t)
{
  p = NULL;            // Init the head of the list this is vital important.

  // Loop over the elements of the passed list if any.
  Node *pt = t.p;
  Node *last_local_element = NULL;
  while (pt != NULL)
  {
     // Allocate a new node and set the fields there.
     Node *q = new Node;
     q->x= pt->x;
     q->next = NULL;

     // Add new node to the local list.
     if (last_local_element != NULL) {
         last_local_element->next = q;
     } else {
         p = q;
     }

     last_local_element = q;

     // Shift the loop variable along the passed list.
     pt = pt->next;
  }
}

There are 2 most often cases when the copy ctor is called:
list my_list1;

list my_list2(my_listl);           // Explicit call.
list my_list3 = my_listl;          // Assignment in the definition statement.

A: With your design of class, you need to be careful with memory management. This is the code:
list::list(const list& t) {
  Node* n = t.p;
  Node* m = p;
  while (n) {
    if (!m) {
      m = new Node(); // Allocate memory.
      if (!p) p = m;
    }
    m->x = n->x;
    m = m->next;
    n = n->next;
  }

  if (m) { // Original list is longer, delete the rest of the list.
    Node * tmp = m;
    m = m->next;
    delete tmp;
  }
}


text:
Q: How to convert action from Quotation to Sales order when sale confirm For odoo 10 I am entering data in Quotation screen and i want that when i confirm sale for this Quotation than screen should be move to Sales Order menu. Firstly i got the action id for both action(Quotation and Sales order). But i facing problem that how to pass this action id in action_confirm method? Is there any solution for this type problem?
This is my code:
@api.multi
def action_confirm(self):
    if self.partner_id.pet_names:
        for record in self.partner_id.pet_names:
        if record == self.pet_names_info:
            if self.order_line:
                for s in self.order_line:
                    if s.product_id:
                        if self.ser1 or self.ind_ser1:
                            self.confirm_rental_service()  # Rental service
                            self.confirm_rental_service_history()  # Rental history maintain
                        break
                res = super(sale_order_pet, self).action_confirm()
                if res:
                    self.confirm_email_template()
                action = self.env.ref('sale.action_orders').read()[0]
                action['res_id'] = self.ids[0]
                action['name'] = 'Sales Order'
                return action
            else:
                raise ValidationError("Please Add Products in Order Lines")

Thanks in advance

A: sale.action_orders action invocation looks fine to me.
Have you tried to debug your code or just try to see whether it passes through all the if/else statements required to reach the action = self.env.ref('sale.action_orders').read()[0] statement?
What does Odoo return when you try to confirm the quotation / order?
According to your code, I guess that res.partner's pet_names might be a one2many field: is sale.order's pet_names_info a record belonging to the same class of pet_names? pet_names_info suggests something like a text field, not a one2many field.
Furthermore, comparing two records in conditional statement sounds a bit weird IMHO.
PS: by the way - naive question - is the first "if" statement closed by an "else" code chunk?


text:
Q: How to generate multivariate random variables given probability distribution? Suppose you can generate uniformly distributed random numbers $x_i\in[a,b]$. To shape probability distribution of these numbers as you like using inverse transform sampling.
But what if you need to get tuples of numbers $v_i=\{v_{i1},v_{i2},...,v_{iN}\}$, distributed by a given multivariate probability distribution $f:\mathbb R^N\to[0,\infty)$? How to shape tuples of uniformly distributed numbers to distribution of $f$?
I've devised the following procedure, and it intuitively seems to be correct. But I'm not sure how to prove it.
For simplicity, consider 3-tuple case, i.e. $v_i=\{x_i,y_i,z_i\}$.

*

*Introduce probability distribution of $x$: $f_x(x)=\int_\mathbb R\int_\mathbb R f(x,y,z)\,\mathrm dy\,\mathrm dz$.

*Generate value of $x=x_0$ using inverse transform sampling for $f_x$.

*Introduce probability distribution of $y$: $f_y(y)=C_1\int_Vf(x_0,y,z)\,\mathrm dz$. This is something like "if $x=x_0$, then $y$ is distributed as $f_y(y)$".

*Generate value of $y=y_0$ as in step 2 using $f_y$.

*Introduce probability distribution of $z$: $f_z(z)=C_2f(x_0,y_0,z)$.

*Generate value of $z=z_0$ as in step 2 using $f_z$.

*The tuple $\{x_0,y_0,z_0\}$ is the generated variable.
The coefficients $C_1$ and $C_2$ above are meant to be chosen so that $f_y$ and $f_z$ had total probability of 1.
Is the above procedure actually correct? If yes, then how to prove that $\{x_0,y_0,z_0\}$ is indeed distributed as given by $f$?


text:
Q: Magnet and its orientation Do magnets always points north pole without considerable deviation? Do magnets points to correct north pole or whether it points 23.1/2° right or left to it due to tilt of earth's axis?

A: Magnets tends to align to the field lines of a magnetic field. Earth possesses a magnetic field whose axis does not coincide with the rotation one but differs of about 11° (see here), so in ideal conditions (no other local magnetic fields but only that of the Earth) magnets would point to the magnetic north pole that is defined as the intersection between the Earth surface and the magnetic axis (which differs from the geographic north pole).
Be also careful when talking about the tilt of the Earth axis. As far as I know, usually it is referred to the angular difference between the rotation axis and the orbital one (which, in the case of the Earth, is about 23°). And this has nothing to do with the orientation of the magnetic field.


text:
Q: How do I clear a leaflet map in react so I can map fresh data? I am attempting to clear a leaflet map in react when fetching new data to map, and i am unsure how to approach this. I saw this post but not sure how exactly to apply it.
Right now I have a function that fetches 1 of 2 geojsons I have loaded.
App.js
//SWAP FILES AS EXAMPLE
  fetchData = () => {
    //MAP SHOULD CLEAR EVERYTIME NEW DATA IS FETCHED
    if(this.state.loaded === 1) {
      fetch(
        "https://raw.githack.com/datafaust/raw/main/cruise-prototype/hh_2020112300_2020120623_Saturday_02.geojson"
      )
        .then((response) => response.json())
        .then((geojson) => {
          this.setState({ geojson, loaded: 2 });
        });

    } else {
      fetch(
        "https://raw.githack.com/datafaust/raw/main/cruise-prototype/hh_2020112300_2020120623_Saturday_03.geojson"
      )
        .then((response) => response.json())
        .then((geojson) => {
          this.setState({ geojson, loaded: 1 });
        });
    }
  };

This is merely a test to get the functionality down. Right now if I click the fetch data button after the initial load, leaflet maps the new geojson on top. How would I clear the mapped information so that the new geojson is mapped fresh?
I have a code sand box here:
https://codesandbox.io/s/leaflet-test-forked-8hm3i?file=/src/Leaf.js:550-573

A: Create a variable outside Choro component.
let savedGeojson = {};

Inside useEffect make it equal with the L.choropleth instance. If it exists remove the geojson from the map else save the new one by replacing the last saved.
useEffect(() => {
    if (Object.keys(props.geojson).length > 0) {
      if (savedGeojson) map.removeLayer(savedGeojson);
      savedGeojson = L.choropleth(props.geojson, {
        valueProperty: "DIFF", // which property in the features to use
        scale: ["white", "red"], // chroma.js scale - include as many as you like
        steps: 5, // number of breaks or steps in range
        mode: "q", // q for quantile, e for equidistant, k for k-means
        //style,
        onEachFeature: function (feature, layer) {
          layer.bindPopup(
            "Total " + feature.properties.DIFF + "<br>" //+
            // feature.properties.incidents.toLocaleString() +
            // " incidents"
          );
        }
      }).addTo(map);
    }
  }, [props.geojson]);

  return null;
}

Demo


text:
Q: How can I permanently change the color of an item in a ListView? I have create list a listview
list[0]=CreateWindow(WC_LISTVIEW,L"",WS_DLGFRAME|WS_CHILD|WS_VISIBLE|LVS_REPORT|LVS_SINGLESEL,-,-,-,-,hwnd,NULL,hInstance,NULL);
LVCOLUMN lvcolumn;
lvcolumn.mask = LVCF_FMT|LVCF_TEXT|LVCF_WIDTH;
lvcolumn.fmt = LVCFMT_CENTER;
lvcolumn.pszText = L"a";
lvcolumn.cx = 100;
ListView_InsertColumn(list[0],0,&lvcolumn);
lvcolumn.pszText = L"b";
ListView_InsertColumn(list[0],1,&lvcolumn);
lvcolumn.pszText = L"c";
ListView_InsertColumn(list[0],2,&lvcolumn);
lvcolumn.pszText = L"d";
ListView_InsertColumn(list[0],3,&lvcolumn);

And I use LPNMLVCUSTOMDRAW to insert color item
case WM_NOTIFY:
    if( ((LPNMHDR)lParam)->code == NM_CUSTOMDRAW){
        switch( ((LPNMLVCUSTOMDRAW)lParam)->nmcd.dwDrawStage){
            case CDDS_PREPAINT:
                return CDRF_NOTIFYITEMDRAW;
                break;
            case CDDS_ITEMPREPAINT:
            {
                LPNMLVCUSTOMDRAW customDraw = (LPNMLVCUSTOMDRAW)lParam;

                customDraw->clrText = getcolor();
                return CDRF_NEWFONT;
                break;
            }
            default: return CDRF_DODEFAULT;
        }
    }
    break;

getcolor is function response colorref. Each item have it own text color. But when the parent window is hide and show again the item color is change. So how to keep it not change or we have another way to set text color
One more I create an new listview item by this way (in case someone need it)
ListView_InsertItem(hwndlist,&lvitem);
ListView_SetItemText(hwndlist,i,k,(LPWSTR)strarr[k].c_str());


text:
Q: How do you differentiate -1 from 0xff when reading a byte from a Java FileInputStream? So, I had to take a test for a job interview where I was required to write a mini app that performed simple XOR encryption, and came across this question. I used a FileInputReader to pull each byte in, perform an XOR operation with the key, and pushed the result back out a FileOutputStream. Heres what got me thinking.
FileInputStream returns an int, a 32-bit signed type. When receiving only one byte, you can cast it into a 'byte' type. FileInputStream also returns -1 if it reaches EOF. But, -1 == 0xff in two's complement binary, so what if the byte read is really 0xff, not EOF?
Is 0xff a byte that mathematically won't ever be returned except in special cases (such as EOF)? Or is this a situation that you may have to account for depending on the data you are reading?

A: You could:
int value = is.read();
if (value == -1)
   // the end!
else
{
   byte b = (byte) value;
   // use b
}

Anyway I should use chunk reads (try to read to a byte array) and if the returned byte count is zero, then we are finished:
int count;
byte[] buffer = new byte[8192];
while ((count = is.read(buffer)) > 0) {
   // use buffer from pos 0 to pos count-1
}

A: No, -1 in an int is not 0xff, but 0xffffffff. An int is 32 bits in Java.
Before casting the value to byte, check if it is -1.
The API documentation of the read method of class FileInputStream explains this:

Reads the next byte of data from this input stream. The value byte is returned as an int in the range 0 to 255. If no byte is available because the end of the stream has been reached, the value -1 is returned. This method blocks until input data is available, the end of the stream is detected, or an exception is thrown.

So, if a byte with the value 0xff is found in the input, the read method will return an int with the value 255 (0xff). Only on EOF will it return -1 (which is 0xffffffff when stored in an int).

A: 0xff is only -1 in base 256, you're working in base 2^32 so there is no confusion. Even if you wrote (signed char)-1 (yes I know that's not valid Java, bear with me), it still ends up written as 0xff.
You can safely assume that any negative return is an error, and normal byte values are what's written in the file verbatim.

A: Read method is not implemented in FileInputStream class, it must have a os specific implementation, which will tell how actually EOF handling is checked.


text:
Q: How can I write a Perl script that generates a new log file each time it's run? I am trying to modify a Perl script to create a different/new log file each time I run the script.  I was trying to create each log file by date, but I am having trouble incorporating this concept...  This is what I have so far:
#!perl -w

use WWW::Mechanize;

# What URL shall we retrieve?
$url = "http://www.mediabase.com/whatsong/whatsong.asp?var_s=075068071069045070077";

# Create a new instance of WWW::Mechanize
# enabling autocheck checks each request to ensure it was successful,
# producing an error if not.
my $mechanize = WWW::Mechanize->new(autocheck => 1);

# Retrieve the page
$mechanize->get($url);

# Assign the page content to $page
my $page = $mechanize->content;

# Output the page
#print $page;

# Let's also save the page locally
open LOG, ">>", "102.1_content.txt";

#print LOG $page; #######get error here when run from c++....

close(LOG);
########################################
########################################
# INPUT_FILE
open INPUT_FILE, "<", "102.1_content.txt";
########################################
my $html = join '', <INPUT_FILE>;

my @stuff = $html =~ />([^<]+)</g;
########################################

use Time::localtime;
$tm = localtime;
print "*****", $tm->mon+1, "/", $tm->mday, "/",
      $tm->year+1900, "--", $tm->hour, "::",
      $tm->min, "::", $tm->sec,
      "******************************";
##sec, min, hour, mday, mon, year, wday, yday, and isdst
########################################
# OUTPUT_FILE
open OUTPUT_FILE, ">>", ("PLAYLIST_TABLE_"$tm->mon+1, "/", $tm->mday, "/", tm->year+1900".txt") or die $!;
########################################
print OUTPUT_FILE "******************************",
            $tm->mon+1, "/", $tm->mday, "/", $tm->year+1900,
            "--", $tm->hour, "::", $tm->min, "::", $tm->sec,
            "******************************");

print join ("   ", @stuff), "\n";

print OUTPUT_FILE join ("           ", @stuff), "\n";

print "thats all!\n";

close(INPUT_FILE);
close(OUTPUT_FILE);

I apologize, I know my code is messy, and thanks in advance...
Nick

A: Use File::Spec or Path::Class to manipulate file names and paths:
#!/usr/bin/perl

use strict;
use warnings;

use File::Spec::Functions qw( catfile );

my ($mday, $mon, $year) = (localtime)[3 .. 5];

my $filename = catfile(
    sprintf('PLAYLIST_TABLE_%02d', $mon + 1),
    sprintf('%02d', $mday),
    sprintf('%04d.txt', $year + 1900)
);

print $filename, "\n";

Output (on Windows):

PLAYLIST_TABLE_11\06\2009.txt

However, I would recommend you use:
my $filename = catfile(
    sprintf('%04d.txt', $year + 1900)
    sprintf('PLAYLIST_TABLE_%02d', $mon + 1),
    sprintf('%02d', $mday),
);

so log files from runs close in time remain 'close' in the file system.
Please avoid having really long lines of string concatenations. They make it really hard to see what is going on an hide syntax errors in clutter. Instead, you could use join:
join('/',
    "PLAYLIST_TABLE_" . ($tm->mon + 1),
    $tm->mday,
    ($tm->year + 1900) . '.txt'
);

A: You should use . (dot) to concatenate strings. Here for the filename string it becomes :
open (OUTPUT_FILE, ">> PLAYLIST_TABLE_" . ($tm->mon+1) .  "/" . $tm->mday . "/" . ($tm->year+1900) . ".txt") or die $!;

The , (comma) works only with print AFAIK, and only because the usual transformation of an array in string is concatenation for print.

A: You're forgetting to do error checking, so
use autodie;

We should all prefer a ISO8601 formatted date/time stamp :)
#!/usr/bin/perl --

use strict;
use warnings;

use File::Spec;
use POSIX();

my $thisf = File::Spec->rel2abs(__FILE__);
my $thisl = sprintf '%s-log-%s.txt', $thisf, POSIX::strftime(q!%Y-%m-%d-%H.%M.%SZ!,gmtime);

print "
thisf $thisf
thisl $thisl
";

__END__

$ perl tmp.pl

thisf /home/boy/tmp.pl
thisl /home/boy/tmp.pl-log-2009-11-08-20.35.38Z.txt

$

A: I use a BEGIN block:
BEGIN
{
    open (STDERR,"> $0.txt");
    print STDERR scalar localtime, "\n";
}

The $0 is the name of the current script. So I add '.txt' so it's always easy to find. And the single redirect '>' ensures it doesn't grow if you forget about it. Just use '>>' if you want to append. Apache (or whatever server you run) saves log files as well, but they are all in the same file.


text:
Q: Why am I getting this error when creating a database? # PHASE 1 (FILE I/O and Logic of System)
# Initialization of Current Balance ** Current Balance is the same for all users for the sake of simplicity **
myMoney = open("current_balance.txt")
currentBalance = int(myMoney.readline())

# Imports
import sqlite3

# Creation of Bank Account and Notifying User(s) of Current Balance
class Bank_Account:
    def __init__(self):
        self.balance= currentBalance
        print("Welcome to Your Bank Account System!")
    # If statements for first screen
    def options_1(self):
        ch = int(input("1. Create an Account\n2. Log into Your Account\nEnter a Choice: "))
        if ch == 1:
            self.create()
        if ch == 2:
            self.Log_in()
    def options_2(self):
        ch= int(input("1. Withdraw Money from Your Account\n2. Deposit Money to Your Account\nEnter a Choice: "))
        if ch == 1:
            self.withdraw()
        if ch == 2:
            self.deposit()
    # Function to Create an Account
    def create(self):
        user_create = str(input("Enter a Username:"))
        pin_create = int(input("Enter a Pin Number:" ))
        print("Account successfully created!")
     # Function to Log into Account
    def Log_in(self):
        user = str(input("Enter your Username:"))
        pin = int(input("Enter your Pin Number:"))
        print("Welcome", user, "!")
    # Function to Deposit Money
    def deposit(self):
        amount=float(input("Enter the amount you want to deposit: "))
        self.balance += amount
        print("Amount Deposited: ",amount)
    # Function to Withdraw Money
    def withdraw(self):
        amount = float(input("Enter the amount you want to withdraw: "))
        if self.balance>=amount:
            self.balance-=amount
            print("You withdrew: ",amount)
        else:
            print("Insufficient balance ")

    def display(self):
        print("Net Available Balance=",self.balance)

# Creating an object of class
self = Bank_Account()
# Calling functions with that class
self.options_1()
self.options_2()
self.display()

# PHASE 2 (With Database) SQLite 3

# Define Connection and Cursor
connection = sqlite3.connect('Bank_Users.db')
cursor = connection.cursor()

# Create Users Table
command1 = """ CREATE TABLE IF NOT EXISTS
bank(username TEXT PRIMARY KEY , pin INTEGER )"""
cursor.execute(command1)

# Add to Users/Bank
cursor.execute("INSERT INTO bank VALUES ('Kailas Kurup', 7620)")
cursor.execute("INSERT INTO bank VALUES ('Bethany Watkins', 4638)")
cursor.execute("INSERT INTO bank VALUES ('John Hammond', 3482)")
cursor.execute("INSERT INTO bank VALUES ('Melissa Rodriguez', 3493)")
cursor.execute("INSERT INTO bank VALUES ('Gopalakrishnan Nair', 9891)")

# Get Results / Querying Database
cursor.execute("SELECT * FROM bank")
results = cursor.fetchall()
print(results)

# Format Results
print("username" + "\t\tpin")
print("-------" + "\t\t--------")
for result in results:
    print(result[0] + " " + result[1] + "\t" + result[2])

# Phase 3 (With GUI) Tkinter

** I'm getting an

Integrityerror: datatype mismatch error.

Why is this happening and what do I do to fix it? 'm trying to create a bank account management system where the user can create an account, log in, and withdraw/deposit money from that account. After completing the database portion of this project I plan on adding Tkinter GUI.***

A: The program does NOT create the bank table (because it already exists) and the first column is not TEXT. PK  would care about datatype; not much else does. As a test, you could change the db connection in the program to :memory: to see if it works. Or look at the db with another tool, eg CLI, to see the bank table definition.
This is speculative, though not wild, because the problem can be reproduced with the described condition.


text:
Q: Enable edit mode in datagridview only for certain column c# How do i enable edit mode only for the certain column?
Let's say i have this columns:
Product Code || Quantity || Description || Price
I wanted to enable edit mode only for Quantity column and Price column. The rest cannot be edited.
I already did this below code, but it seems not working:
dataGridView1.EditMode = DataGridViewEditMode.EditOnKeystroke;
dataGridView1.Columns["Quantity"].ReadOnly = false;
dataGridView1.Columns["Price"].ReadOnly = false;

All i can do is disable ReadOnly to false, but it is enabled all of the columns that i don't want to enable them.
Note: By the time program runs for the first time, i already set the ReadOnly to true

A: The out-of-box solution is using attributes on your data model:
public class MyDataModel
{
    // Do not show in data grid view
    [System.ComponentModel.Browsable(false)]
    public virtual int ID { get; protected set; }

    // Set to read-only in data grid view
    [System.ComponentModel.ReadOnly(true)]
    public virtual string Person { get; set; }
}

A: You should set ReadOnly = true to all non-editable column.
By default, column are set to ReadOnly = false

A: this will help you
MSDN DataGridViewColumn

A: foreach (DataGridViewColumn dc in dgvTestParameter.Columns)
        {
            if (dc.Index.Equals(0) || dc.Index.Equals(4))
            {
                dc.ReadOnly = false;
            }
            else
            {
                dc.ReadOnly = true;
            }
        }

A: int EditableCol_index = datagridview["colname"].index;

// if this is true , you wont be able to edit even you set the column readonly=false;
datagridview1.readonly = false;
foreach (datagridviewcolumns c in datagridview1 )
{
   c.readonly = true;
   if( c.index == EditableCol_index )
   {
     c.readonly = false;  // editable
   }
}

A: From design part you just check "Enable Editing" mode in your Datagridview.
this example may help you,

I have added two columns on as readonly purpose(column name is "ReadOnly Column") and another as editable column(column name is "Normal Column").
Code:
dataGridView1.Columns["readOnlyColumn"].ReadOnly = true;

Thank you....


text:
Q: How can I stop Kivy from auto-selecting items modulo n in a RecycleView? The situation: The code below uses Kivy's RecycleView class to spawn a GUI showing a table of data. Each row of this table starts with a red "Ignore" button whose color the user is supposed to be able to toggle between red and green by clicking.
The problem: When I click on a row's "Ignore" button, it not only turns the clicked button green, but also turns many other buttons further down the list green as well! The unwanted selection happens cyclically, that is, it seems that every n-th button turns green.
Why does this happen? How can I get Kivy to stop doing this, and instead select only the button that was clicked?
from kivy.app import App
from kivy.lang import Builder
from kivy.properties import BooleanProperty
from kivy.uix.behaviors import FocusBehavior
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.button import Button
from kivy.uix.recycleboxlayout import RecycleBoxLayout
from kivy.uix.recycleview import RecycleView
from kivy.uix.recycleview.layout import LayoutSelectionBehavior
from kivy.uix.recycleview.views import RecycleDataViewBehavior

Builder.load_string('''
<Row@BoxLayout>:
    orientation: 'horizontal'
    data: [None, None, None, None]
    IgnoreButton:
        text: 'Ignored'  if self.selected else 'Ignore'
        background_normal: ''
        # color green if ignored, otherwise red
        background_color: [0.2, 0.5, 0.1, 1] if self.selected else [0.5, 0, 0.1, 1]
    Label:
        text: str(root.data[1])
    Label:
        text: str(root.data[2])
    Label:
        text: str(root.data[3])
<RV>:
    viewclass: 'Row'
    data: [{'data':[0, x, x+1, x+2]} for x in range(100)]
    SelectableRecycleBoxLayout:
        orientation: 'vertical'
        default_size: None, dp(56)
        default_size_hint: 1, None
        size_hint_y: None
        height: self.minimum_height
        multiselect: True
''')

class SelectableRecycleBoxLayout(FocusBehavior, LayoutSelectionBehavior,
                                  RecycleBoxLayout):
    ' Adds selection and focus behaviour to the view. '

class IgnoreButton(Button, RecycleDataViewBehavior):
    # Add selection support to the Button.
    index = None
    selected = BooleanProperty(False)
    selectable = BooleanProperty(True)

    def on_touch_down(self, touch):
        # Add selection on touch down.
        if super().on_touch_down(touch):
            self.selected = not self.selected

class RV(RecycleView):
    def __init__(self, **kwargs):
        super().__init__(**kwargs)

class TestApp(App):
    def build(self):
        return RV()

if __name__ == '__main__':
    TestApp().run()

A: With a Recycleview,  there are only as many widgets as you can see… they get recycled.  Therefore you can not rely on the widget to store the state.
In Row, I created an NumericProperty, idx, and create an index in the rvdata list.  This corresponds to the index of the 'virtual widget'.
I created a list to store the state of the ToggleButton.
You were treating a Button, like a ToggleButton, so I replaced It with a ToggleButton.  You can add the color changes back.
from kivy.app import App
from kivy.lang import Builder
from kivy.properties import NumericProperty, ListProperty
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.recycleview import RecycleView

Builder.load_string('''
<Row>:
    orientation: 'horizontal'
    data: [None, None, None, None]
    ToggleButton:
        text: 'Ignored'  if app.root.selected[root.idx] == 'normal' else 'Ignore'
        #background_normal: ''
        # color green if ignored, otherwise red
        #background_color: [0.2, 0.5, 0.1, 1] if app.root.selected[root.idx] == 'normal' else [0.5, 0, 0.1, 1]
        state: app.root.selected[root.idx]
        on_state: app.root.selected[root.idx] = self.state
    Label:
        text: str(root.data[1])
    Label:
        text: str(root.data[2])
    Label:
        text: str(root.data[3])
<RV>:
    viewclass: 'Row'
    data: [{'data':[0, x, x+1, x+2], 'idx': x} for x in range(100)]
    RecycleBoxLayout:
        orientation: 'vertical'
        default_size: None, dp(56)
        default_size_hint: 1, None
        size_hint_y: None
        height: self.minimum_height
''')

class Row(BoxLayout):
    idx = NumericProperty()

class RV(RecycleView):
    selected = ListProperty(['normal'] * 100)

class TestApp(App):
    def build(self):
        return RV()

if __name__ == '__main__':
    TestApp().run()


text:
Q: Replacing few characters of string in a Pandas Columns with asterisk I have a pandas table with three set of columns, which would look something like this
data = {
    'col1':['ABCD', 'EFGH', 'IJKL', 'MNOP1', 'QRST25'],
    'col2':['ABCD,1234', 'EFGH,5678', 'IJKL,91011,F1H2I3', 'MNOP,121314', 'MNOP,151617,A1B2C3'],
    'col3':['ABDC,EFGH', 'IJAL,MNIP', 'QURST,UVWY', 'C4GH,MQUR', 'FHGH,QRQP']}

I am looking to mask few character in certain pattern as below
output.data = {
    'col1':['*BCD', '*FGH', '*JKL', '*NOP1', '*RST25'],
    'col2':['*BCD,*234', '*FGH,*678', '*JKL,*1011,*1H2I3', '*NOP,*21314', '*NOP,*51617,*1B2C3'],
    'col3':['****,EFGH', '****,MNIP', '****,UVWY', '****,MQUR', '****,QRQP']}

that is, in column one, I want the first character replaced with * , in column 2 first character of every word separated by comma replaced with * and lastly in the third column all the character in first set of strings that are separated by comma
for the first column, I could think off something like this, but that may not the right way to do it
data["col1"].str.replace([:1], "*")

for rest two columns I have not idea how to do it., help requested.

A: This works but it might not be the most efficient method.
import pandas as pd

data = {
    'col1':['ABCD', 'EFGH', 'IJKL', 'MNOP1', 'QRST25'],
    'col2':['ABCD,1234', 'EFGH,5678', 'IJKL,91011,F1H2I3', 'MNOP,121314', 'MNOP,151617,A1B2C3'],
    'col3':['ABDC,EFGH', 'IJAL,MNIP', 'QURST,UVWY', 'C4GH,MQUR', 'FHGH,QRQP']}

df = pd.DataFrame(data)

df['col1'] = df['col1'].apply(lambda s: '*'+s[1:])

df['col2'] = df['col2'].apply(lambda s: ','.join(['*'+t[1:] for t in s.split(',')]))

df['col3'] = df['col3'].apply(lambda s: s.replace(s.split(',')[0], (s.find(',')+1)*'*' ))

print(df)

A: You can try with:
df['col1'] = df['col1'].apply(lambda x: x.replace(x[0], "*"))
df['col2'] = df['col2'].apply(lambda x: x.replace(x[0], "*"))
df['col2'] = df['col2'].apply(lambda x: x.replace(x[4], "*"))
df['col3'] = df['col3'].apply(lambda x: x.replace(x[:4], "****"))

maybe not very good looking but it works ;D


text:
Q: Getting Error JAR_SIG_NO_MANIFEST: Missing META-INF/MANIFEST.MF when pushing an apk file I am a new developer, I was built an application Android and pushing to google play and appear an error when I pushing a APK file.
It takes 5 days, but not fix this error.
I use visual studio 2017 (xamarin).
Error:

You uploaded an APK with an invalid signature (learn more about signing). Error from apksigner: ERROR: JAR_SIG_NO_MANIFEST: Missing META-INF/MANIFEST.MF

A: Make sure you mark both v1(jar Signature) and V2(full APK signature)
EDIT: By the way, the reason for it to fail if you sign with v2 only, is that v2 was introduced in Android 7.0 (sdk 24) and you are probably targeting an older minSdkVersion.
Therefore, if you target minSdkVersion 23 or below, you need to use signing schemes v1 AND v2 (or only v1), because if the app is installed on Android 6.0 or older, it can only be verified through v1 scheme.
If you target minSdkVersion 24 or above, then you can use v2 on its own, since the app won't be installed on older versions.
You can also check this poorly noted on Android Docs, third paragraph.

A: Follow this process.
select the menu option Build > Package YourAppName.apk
This will create two .apk files in the bin/Release folder.
1.mono.samples.YourAppName-Signed.APK // Deploy this APK in Playstore.
2.mono.samples.YourAppName.APK


text:
Q: Disk Cleanup on Server 2008 R2 is ineffective I have a user profile with ~2.9GB of Error Reports backed up in the ReportQueue folder (C:\Users\UserName\AppData\Local\Microsoft\Windows\WER\ReportQueue). Running DiskCleanup as the administrator does not detect these files and therefore does not clean them up. However, running the utility as the user shows an even larger amount (12.4GB!) of error reporting files. As seen below:

The problem is that after running the cleanup utility the disk spaced used does not decrease by anywhere near 12.4GB and running the utility again detects the same 12.4GB of files.

*

*What is the problem here?

*Alternatively, can I manually delete the files in the ReportQueue folder?

A: I'm not going to lie, I've never ever ran Disk Cleanup on a server in 7 years of managing Windows based networks.
Personally I'd either delete the files manually or just delete the local user profile. I assume this stuff isn't in their roaming profile, if applicable?
I'd be far more concerned as to what has been going wrong to generate 3Gbs of error reporting!

A: You can use a free 3rd party drive space analysis tool to visually see where the space is taken up and find the folders to delete that way.  It's not as user friendly as drive cleanup but it can be useful.  It won't protect you from deleting important files so be sure you know what you are doing.  R-click and run it as admin so it can see in all the hidden folders:
http://www.uderzo.it/main_products/space_sniffer/

A: Use the following cmd as suggested in this blog post.
cd \ProgramData\Microsoft\Windows\WER\ReportQueue
del /s *.tmp.hdmp
del /s *.tmp.mdmp


text:
Q: How do I insert a second level column and value into a Pandas DataFrame, whilst keeping it in line with the first level column? The below code creates the relevant Pandas DataFrame:
import pandas as pd

columns_index = pd.MultiIndex.from_arrays([['Apple','Apple','Banana'], ['Light_Green','Red','Yellow']])
df = pd.DataFrame(data=None,columns=columns_index,index=[1])
df.loc[:,('Apple','Light_Green')] = 10
df.loc[:,('Apple','Red')] = 0
df.loc[:,('Banana','Yellow')] = 5

    Apple           Banana
    Light Green Red Yellow
1   10          0   5

Then I run the following code to insert a new value (and a new first level column header into the DataFrame):
df.loc[:,('Apple','Dark_Green')] = 1

This, however, produces a DataFrame with the data ordered as follows:
    Apple           Banana  Apple
    Light_Green Red Yellow  Dark_Green
1   10          0   5       1.0

How do I insert this value (and new first level column header) into the DataFrame in the most Pythonic way and ensure that the Dark_Green header is within the Apple category, so that the DataFrame is as below:
    Apple                       Banana
    Light_Green Red Dark_Green  Yellow
1   10          0   1           5

Is there a different method to use to insert the data or is this method ok, with some kind of code deployed to re-sort the DataFrame after the best approach?
Note: I specifically need the DataFrame to be adjusted dynamically over and over again, so creating the DataFrame from the outset with the Dark_Green header is not a solution.
Thanks!

A: Doing with sort_index
df=df.sort_index(level=0,axis=1)
       Apple                 Banana
  Dark_Green Light_Green Red Yellow
1        1.0          10   0      5


text:
Q: Java application that uses multiple timers Hi all and thanks for reading this.
i have an application and i want to use multiple timers on it.
it will read from a list of instructions some instructions and will tell you what to do, keeping track of time for each instruction's time and notifying you when timer is over. instruction can include other instructions and goes on.
i m passing the time as : double minutes to each instruction.
So it should work like this.
start instruction1 - start timer1
if it includes other, start instruction1.1 - start timer1.1
start instruction2 - start timer2 .....etc.etc..
every time a timer goes of it should notify me
i would like to get suggestions on how to do this....
any tutorials, examples, links pseudocode, sample code are welcome. Thank you

A: Introducing a simple generalisation of the Java language's Timer class
How to Use Timers
Job Scheduling using Timer and Quartz


text:
Q: Perl's backticks/system giving "tcsetattr: Input/output error" I'm writing a perl script that kicks off a script on several different servers using ssh. The remote script needs to run as long as this script is running:
#!/usr/bin/perl
require 'config.cfg'

#@servers is defined in config.cfg
#Contains server info as [username,hostname]
#
# @servers = ([username,server1.test.com],[username,server2.test.com])
#
foreach $server ( @servers ) {
    my $pid = fork();
    if ( $pid == 0 ) {
        $u = ${$server}[0];
        $h = ${$server}[1];
        print "Running script on $h \n";
        print `ssh -tl $u $h perl /opt/scripts/somescript.pl`;
        exit 0;
    } else {
        die "Couldn't start the process: $!\n";
    }
}
[...]

When I run this script, I get the following output:

./brokenscript.pl
  Running script on server01
  $ tcsetattr: Input/output error
  Connection to server01 closed.

The same result occurs when running with system (and backticks are preferred anyways since I want the output of the script). When I run the exact command between the backticks on the command line, it works exactly as expected. What is causing this?

A: The tcsetattr: Input/output error message comes from ssh when it tries to put the local terminal into "raw" mode (which involves a call to tcsetattr; see enter_raw_mode in sshtty.c, called from client_loop in clientloop.c).
From IEEE Std 1003.1, 2004 (Posix) Section 11.1.4: Terminal Access Control, tcsetattr may return -1 with errno == EIO (i.e. "Input/output error") if the calling process is in an orphaned (or background?) process group.
Effectively ssh is trying to change the setting of the local terminal even though it is not in the foreground process group (due of your fork and, the local script exiting (as evidenced by the apparent shell prompt that comes immediately before the error message in your quoted output)).
If you just want to avoid the error message, you can use ssh -ntt (redirect stdin from /dev/null, but ask the remote side to allocate a tty anyway) instead of ssh -t (add your -l and any other options you need back in too, of course).

More likely, you are interesting in keeping the local script running as long as some of the remote processes are still running. For that, you need to use the wait function (or one of its "relatives") to wait for each forked process to exit before you exit the program that forked them (this will keep them in the foreground process group as long as the program that started them is in it). You may still want to use -n though, since it would be confusing if the multiple instances of ssh that you forked all tried to use (read from, or change the settings of) the local terminal at the same time.
As a simple demonstration, you could have the local script do sleep 30 after forking off all the children so that the ssh command(s) have time to start up while they are part of the foreground process group. This should suppress the error message, but it will not address your stated goal. You need wait for that (If I am interpreting your goal correctly).

A: That probably happens because you are forcing SSH to allocate a tty when stdin/stdout are not really ttys. SSH tries to call some specific tty function on those handlers (probably forwarded from the remote side) and the call fails returning some error.
Is there any reason why you should be allocating a tty?
Is there also any reason to use the obsolete version 1 of the SSH protocol?


text:
Q: Getting data from html file and print using php My scenario is,

*

*Read html page content using php

*Retrieving the required data from the html using DOM parser concept by using php

*Displaying the retrieved data in the same php page (the content as like in html page)
I have done all 3 steps, but while displaying the data i didn't get my required format,
Here is all of my code (html,php):
Html:

<title>data</title>

Place	Temperature

25-08-2011

A	30 c

B	29 c

26-08-2011

A	28 c

B	28 c

Php code:
<?php
include('simple_html_dom.php');
$html = file_get_html('data.html');

$sdate[0]="";
$city[0]="";
$temp[0]="";
$c=0;

foreach($html->find('td[class=date]') as $e)
{
    $sdate[$c]=$e->innertext;
    $c=$c+1;
}

$c=0;
foreach($html->find('td[class=city]') as $e)
{
    $city[$c]=$e->innertext;
    $c=$c+1;
}

$c=0;
foreach($html->find('td[class=temp]') as $e)
{
    $temp[$c]=$e->innertext;
    $c=$c+1;
}
for($i=0;$i<$c;$i++)
{
    echo 'Date:'. $sdate[$i]."
";
    echo 'City:'.$city[$i]  .', Temp:' . $temp[$i]."
" ;
}

?>

Output:
Date:25-08-2011
City:A, Temp:30 c
Date:26-08-2011
City:B, Temp:29 c
Date:
City:A, Temp:28 c
Date:
City:B, Temp:28 c

But, I want to print the result like this format,
Date:25-08-2011
City:A, Temp:30 c
City:B, Temp:29 c
Date:26-08-2011
City:A, Temp:28 c
City:B, Temp:28 c

Please anybody help me...
Thanks,
Nandha

A: You need to rewrite your logic. I already did that for you :)
$tree = array();

foreach ($html->find('td') as $e) {
    if ($e->class == 'date') {
        $date = $e->innertext;
    }

    if ($e->class == 'city') {
        $city = $e->innertext;
    }

    if ($e->class == 'temp') {
        $tree[$date][$city] = $e->innertext;
    }
}

Result will be something like this:
Array
(
    [25-08-2011] => Array
        (
            [A] => 30 c
            [B] => 29 c
        )

    [26-08-2011] => Array
        (
            [A] => 28 c
            [B] => 28 c
        )

)

A: Your problem you are printing in a for loop each element in each of the arrays. It continues until the longest array, thus displaying a date, a city and a temp each time.

A: Try this:
<?php
include('simple_html_dom.php');
$html =  file_get_html('data.html');

foreach($html->find('td') as $e)
{
   if ($e->class == 'date')
      echo 'Date:'.$e->innertext.'
';
   else if ($e->class == 'city')
      echo 'City:'.$e->innertext;
   else if ($e->class == 'temp')
      echo 'Temp:'.$e->innertext.'
';
}
?>


text:
Q: Docker Compose - Shorter Aliases for Commands I have a rails application containerised using docker and docker-compose with production and development environments. Each environment has its own .env and docker-compose.yml files (inheriting from a common compose file, only redefining the env-file attribute).
So, to build the application in development mode:
docker-compose -f docker-compose.yml -f docker-compose.dev.yml --env-file .env.development build

And a similar command for production. I'd like to create an alias to shorten this command as it becomes especially annoying when trying to run rake tasks. I'd prefer to not modify ~/.bashrc (so other collaborators can use the aliases without having to follow a similar process).
Is there a better solution than shell scripts?
I should say that this is really a non-issue, it would just be nice to build my image using something like app:dev build - similar to how it's done using Node.js.

A: I decided to leverage a Makefile instead of a rake task (as suggested by @Mr.):
all: build.prod up.prod
build.dev:
    docker-compose -f docker-compose.yml -f docker-compose.dev.yml --env-file .env.dev build
build.prod:
    docker-compose -f docker-compose.yml -f docker-compose.prod.yml --env-file .env.prod build
up.dev:
    docker-compose -f docker-compose.yml -f docker-compose.dev.yml --env-file .env.dev up
up.prod:
    docker-compose -f docker-compose.yml -f docker-compose.prod.yml --env-file .env.prod up
down:
    docker-compose down
test:
    docker-compose --env-file .env.dev exec web rspec
bash.dev:
    docker-compose --env-file .env.dev exec web sh
bash.prod:
    docker-compose --env-file .env.prod exec web sh
dev: build.dev up.dev

And it gives the functionality I desire

A:
Each environment has its own .env and docker-compose.yml

if you differentiate between each environment files by the environment name, then you can use a rake task as follows
namespace :docker do
  task :build, :env do |tsk, args|
    `docker-compose -f docker-compose.yml -f docker-compose.#{args.env}.yml --env-file .env.#{args.env} build`
  end
end

now you can just simply run rake docker:build[production].
note that, i did not test the code.


text:
Q: UHD TV says mode not recognized for UHD or FHD at 60 Hz on 20.04 Got a 2020 Samsung UHD TV hanging off internal Iris graphics HDMI native res 3840x2160 at 60 Hz either latest Win 10 or vanilla Ubuntu 20.04.
Recently the TV started saying "mode not recognized" when I boot into Ubuntu.
When I switch to a little multi-sync moni on the fly, res is at FHD at 60, which the TV should very well support. (When I boot 20.04 on a >10y old PC the 49" TV goes through all kinds of weird resolutions which must be VGA 640x480,.. scaled to 49" at some point!)
When I start in recovery mode and resume normal boot everything is fine on the TV and it just said it is at UHD 30p.
(And, yes, ****, refresh rate setting GUI is gone on 20.04. ****!)
AFAIK the PC differentiates between monitors, everyone having some UID. There must be some weird setting be stored with the TV when Ubuntu starts normally.
Where can I find this?
When I change settings on the small moni it doesn't help.
Just deleted ~/.config/monitors.xml. Didn't help.
Or what is the culprit?
TIA
G.


text:
Q: Firebase realtime database query on multiple attributes So, we have a contact management system where we store first name, last name and company name. i understand that firebase db cannot do those relational DB style queries using relational operators but is there a creative way to support that search can give results from either if the above 3 attributes.?
As an example:
{
"fName" : "abc",
"lName" : "pqr",
"cName" : "lmn"
},
{
"fName" : "pbc",
"lName" : "aqr",
"cName" : "tmn"
},
{
"fName" : "dbc",
"lName" : "tqr",
"cName" : "amn"
},

The query used currently is:
 this.db.list("/users/" + userKey + "/cards",
ref => ref.orderByChild('fName').startAt('a').endAt('a' +"\uf8ff") )

With above query it will only return 1st record. What I need is to return all 3 as all 3 has at least one property beginning with 'a'
I think the other suggested tricks on other posts like creating another attribute combining values from other attributes wont work here. As they do a equalTo search.

A: With Realtime Database, you can only order and filter on a single child at a time.  So, what you're trying to do isn't possible given your current database structure for a single query.
What you can do instead is issue multiple queries, one for each field you want to check, and merge the results of each of those queries on the client.


text:
Q: MongoDb Indexes - Equal vs In filter and index usage I've the follolowing model of a user
{
  "TenantId":"abc",
  "ContainerId": "xyz",
  "Name": "yyy",
  "Tags": [
      {
            "Key":"key1",
            "Value":"val1".
      }
      .....
  ]
}

TenantId and containerId are in relation 1:n, so for one Tenant there may be multiple ContainerId items.
I've read that in order to get maximum index usage, the first field in index should be most selective, to minimise documents MongoDb needs to scan. What's more, some suggest that it's better to have "equality" filter on that field, instead of a range filter.
Now, I've added 2 indexes:
{
   "ContanerId":1,
   "Tags.Key": 1
}
{
   "TenantId":1,
   "Tags.Key": 1
}

Now executing 2 queries which are equal in the results they return:
find({"TenantId":"abc", "Tags.Key": {$in : ["1","2"]}})
find({"ContainerId":{$in:["abc","xyz",.....]}, "Tags.Key": {$in : ["1","2"]}})

I'd assume, that the first would run much faster, as it needs to examine less elements while scanning the index. However, it seems that results are almost identical.
Can someone help me and explain why the performance of both queries is similar ?
First query stats:
{
   "executionSuccess":true,
   "nReturned":171240,
   "executionTimeMillis":602,
   "totalKeysExamined":171240,
   "totalDocsExamined":171240,
   "executionStages":{
      "stage":"FETCH",
      "nReturned":171240,
      "executionTimeMillisEstimate":579,
      "works":171241,
      "advanced":171240,
      "needTime":0,
      "needYield":0,
      "saveState":1338,
      "restoreState":1338,
      "isEOF":1,
      "invalidates":0,
      "docsExamined":171240,
      "alreadyHasObj":0,
      "inputStage":{
         "stage":"IXSCAN",
         "nReturned":171240,
         "executionTimeMillisEstimate":200,
         "works":171241,
         "advanced":171240,
         "needTime":0,
         "needYield":0,
         "saveState":1338,
         "restoreState":1338,
         "isEOF":1,
         "invalidates":0,
         "keyPattern":{
            "PyraTenantId":1,
            "IsEmpty":1,
            "Tags.KeyValue":1
         },
         "indexName":"PyraTenantIsEmptyTagsKeyValue",
         "isMultiKey":true,
         "multiKeyPaths":{
            "PyraTenantId":[

            ],
            "IsEmpty":[

            ],
            "Tags.KeyValue":[
               "Tags"
            ]
         },
         "isUnique":false,
         "isSparse":false,
         "isPartial":false,
         "indexVersion":2,
         "direction":"forward",
         "indexBounds":{
            "PyraTenantId":[
               "[\"01fbe4f9-77a5-48a2-8a3d-6b105808f6ac\", \"01fbe4f9-77a5-48a2-8a3d-6b105808f6ac\"]"
            ],
            "IsEmpty":[
               "[false, false]"
            ],
            "Tags.KeyValue":[
               "[\"01fbe4f9-77a5-48a2-8a3d-6b105808f6ackey6_ddd_01fbe4f9-77a5-48a2-8a3d-6b105808f6acvalue6\", \"01fbe4f9-77a5-48a2-8a3d-6b105808f6ackey6_ddd_01fbe4f9-77a5-48a2-8a3d-6b105808f6acvalue6\"]"
            ]
         },
         "keysExamined":171240,
         "seeks":1,
         "dupsTested":171240,
         "dupsDropped":0,
         "seenInvalidated":0
      }
   }
}

Second query stats:
 {
        "executionSuccess" : true,
        "nReturned" : 171240,
        "executionTimeMillis" : 456,
        "totalKeysExamined" : 171412,
        "totalDocsExamined" : 171240,
        "executionStages" : {
            "stage" : "FETCH",
            "nReturned" : 171240,
            "executionTimeMillisEstimate" : 410,
            "works" : 171412,
            "advanced" : 171240,
            "needTime" : 171,
            "needYield" : 0,
            "saveState" : 1339,
            "restoreState" : 1339,
            "isEOF" : 1,
            "invalidates" : 0,
            "docsExamined" : 171240,
            "alreadyHasObj" : 0,
            "inputStage" : {
                "stage" : "IXSCAN",
                "nReturned" : 171240,
                "executionTimeMillisEstimate" : 290,
                "works" : 171412,
                "advanced" : 171240,
                "needTime" : 171,
                "needYield" : 0,
                "saveState" : 1339,
                "restoreState" : 1339,
                "isEOF" : 1,
                "invalidates" : 0,
                "keyPattern" : {
                    "ContainerId" : 1,
                    "IsEmpty" : 1,
                    "Tags.KeyValue" : 1
                },
                "indexName" : "ContainerIdIsEmptyTagsKeyValue",
                "isMultiKey" : true,
                "multiKeyPaths" : {
                    "ContainerId" : [],
                    "IsEmpty" : [],
                    "Tags.KeyValue" : [
                        "Tags"
                    ]
                },
                "isUnique" : false,
                "isSparse" : false,
                "isPartial" : false,
                "indexVersion" : 2,
                "direction" : "forward",
                "indexBounds" : {
                    "ContainerId" : [
                        "[\"01ba96f4-2b21-4c66-ba8d-84fab56ab398\", \"01ba96f4-2b21-4c66-ba8d-84fab56ab398\"]",
                        "[\"0295187c-5cbe-490d-ad04-83f51f890aec\", \"0295187c-5cbe-490d-ad04-83f51f890aec\"]",
                        "[\"059ccb9c-0f50-45d7-a126-ad440e3488a2\", \"059ccb9c-0f50-45d7-a126-ad440e3488a2\"]",
                        "[\"05a887dc-7b2f-4fa5-9256-2220d1d8158f\", \"05a887dc-7b2f-4fa5-9256-2220d1d8158f\"]",
                        "[\"0d080dce-5d88-4a9e-bf4a-2f03c3aaa7e0\", \"0d080dce-5d88-4a9e-bf4a-2f03c3aaa7e0\"]",
                        "[\"0d3e9a6a-fa96-40b4-b0ec-23f792c9abcf\", \"0d3e9a6a-fa96-40b4-b0ec-23f792c9abcf\"]",
                        "[\"10fcff07-12aa-4034-b03f-15e6e73cf310\", \"10fcff07-12aa-4034-b03f-15e6e73cf310\"]",
                        "[\"137997b0-edde-4898-80dd-090f49905d17\", \"137997b0-edde-4898-80dd-090f49905d17\"]",
                        "[\"1d663037-28b0-4f37-b1ed-ffdaa237b1b9\", \"1d663037-28b0-4f37-b1ed-ffdaa237b1b9\"]",
                        "[\"25f51039-f3ef-46d8-94b8-a90aa9c8a6d2\", \"25f51039-f3ef-46d8-94b8-a90aa9c8a6d2\"]",
                        "[\"298837cc-889b-4fd8-931f-6b47665158e6\", \"298837cc-889b-4fd8-931f-6b47665158e6\"]",
                        "[\"2ba1fb3c-7d8a-4a28-ba94-631324fc164c\", \"2ba1fb3c-7d8a-4a28-ba94-631324fc164c\"]",
                        "[\"2d96c883-e24d-4566-bc25-19e5a11417d2\", \"2d96c883-e24d-4566-bc25-19e5a11417d2\"]",
                        "[\"349d6cd3-ac21-4a4f-a0af-7706bb7c3022\", \"349d6cd3-ac21-4a4f-a0af-7706bb7c3022\"]",
                        "[\"34fec690-ee08-4eaf-b270-a872972bafe4\", \"34fec690-ee08-4eaf-b270-a872972bafe4\"]",
                        "[\"35814c64-2619-4513-9b0e-f30814b11117\", \"35814c64-2619-4513-9b0e-f30814b11117\"]",
                        "[\"40cd26f4-6fd2-477e-91fa-d2542315b30e\", \"40cd26f4-6fd2-477e-91fa-d2542315b30e\"]",
                        "[\"41a162db-7ba7-4ad9-ace9-1d9bb0536ead\", \"41a162db-7ba7-4ad9-ace9-1d9bb0536ead\"]",
                        "[\"44e2deb1-ad2c-46d0-bed2-5b23b71ddbeb\", \"44e2deb1-ad2c-46d0-bed2-5b23b71ddbeb\"]",
                        "[\"524481fc-d949-4371-b179-63e76d949979\", \"524481fc-d949-4371-b179-63e76d949979\"]",
                        "[\"5ad11ecd-93cf-4166-96c9-6e152ac58667\", \"5ad11ecd-93cf-4166-96c9-6e152ac58667\"]",
                        "[\"5aea2cbe-33da-48fa-a90d-31da2b108c2d\", \"5aea2cbe-33da-48fa-a90d-31da2b108c2d\"]",
                        "[\"5d265d15-a16c-4683-9276-66c592e09ba5\", \"5d265d15-a16c-4683-9276-66c592e09ba5\"]",
                        "[\"6795fd6d-364f-4e63-b656-98b2cf0eed91\", \"6795fd6d-364f-4e63-b656-98b2cf0eed91\"]",
                        "[\"6a1352a7-5986-4fda-8bc6-98630ffbd967\", \"6a1352a7-5986-4fda-8bc6-98630ffbd967\"]",
                        "[\"6d5abb48-5413-4347-8d1d-af722098d803\", \"6d5abb48-5413-4347-8d1d-af722098d803\"]",
                        "[\"702a1754-bc75-4cc8-81bd-d03598b21292\", \"702a1754-bc75-4cc8-81bd-d03598b21292\"]",
                        "[\"71dd628d-e3eb-46e8-ace4-b102cde0e94f\", \"71dd628d-e3eb-46e8-ace4-b102cde0e94f\"]",
                        "[\"76b67664-5fee-45b0-ae4f-4b7f53d69779\", \"76b67664-5fee-45b0-ae4f-4b7f53d69779\"]",
                        "[\"79227dcb-9930-4734-8b8e-efbd4f7ba396\", \"79227dcb-9930-4734-8b8e-efbd4f7ba396\"]",
                        "[\"7d323987-b873-441d-8e5e-9e9124628468\", \"7d323987-b873-441d-8e5e-9e9124628468\"]",
                        "[\"807ebe50-8369-4a8d-8176-4b449cdb2932\", \"807ebe50-8369-4a8d-8176-4b449cdb2932\"]",
                        "[\"8092cc86-1b99-4547-9221-86f97c85bbe7\", \"8092cc86-1b99-4547-9221-86f97c85bbe7\"]",
                        "[\"819dab0e-ba20-4f4e-80c3-c16f4f9a69a7\", \"819dab0e-ba20-4f4e-80c3-c16f4f9a69a7\"]",
                        "[\"84329c2c-3d81-48a8-a879-d376b0141b58\", \"84329c2c-3d81-48a8-a879-d376b0141b58\"]",
                        "[\"88e95e56-861f-4ed3-a745-73f678769a6e\", \"88e95e56-861f-4ed3-a745-73f678769a6e\"]",
                        "[\"9281aea6-8e7a-4f42-8715-2f185c07894d\", \"9281aea6-8e7a-4f42-8715-2f185c07894d\"]",
                        "[\"96d1c8c9-d2e4-47d4-a0da-391fe94a1213\", \"96d1c8c9-d2e4-47d4-a0da-391fe94a1213\"]",
                        "[\"9ed56f80-e34a-4447-b550-6e0f03f809a5\", \"9ed56f80-e34a-4447-b550-6e0f03f809a5\"]",
                        "[\"a41c232f-6014-417f-b321-e66fc2f306a5\", \"a41c232f-6014-417f-b321-e66fc2f306a5\"]",
                        "[\"aab965ce-e656-49c7-b66d-2f13cf26df3f\", \"aab965ce-e656-49c7-b66d-2f13cf26df3f\"]",
                        "[\"af4eb4ec-f8c0-40cb-bc70-09db103c1eb7\", \"af4eb4ec-f8c0-40cb-bc70-09db103c1eb7\"]",
                        "[\"b8825d8b-a662-4c4c-9b38-7f855e795500\", \"b8825d8b-a662-4c4c-9b38-7f855e795500\"]",
                        "[\"bc88917c-1145-4e47-b06b-a15f111a7792\", \"bc88917c-1145-4e47-b06b-a15f111a7792\"]",
                        "[\"bf264dc4-85c8-49db-b43e-cf9d6cc759b0\", \"bf264dc4-85c8-49db-b43e-cf9d6cc759b0\"]",
                        "[\"cc4bc22b-ce9c-4c56-8760-d36ccd5ac446\", \"cc4bc22b-ce9c-4c56-8760-d36ccd5ac446\"]",
                        "[\"ce48aaeb-6f6d-4bd7-b9eb-dc45b9a58032\", \"ce48aaeb-6f6d-4bd7-b9eb-dc45b9a58032\"]",
                        "[\"d0456d39-b3e0-4b86-af46-12d4cbcc7dcd\", \"d0456d39-b3e0-4b86-af46-12d4cbcc7dcd\"]",
                        "[\"d41b7f5e-3ebb-40c6-9a3e-80e925ded2bb\", \"d41b7f5e-3ebb-40c6-9a3e-80e925ded2bb\"]",
                        "[\"d842e6c3-0161-47fa-a725-2fd23bfb3cc8\", \"d842e6c3-0161-47fa-a725-2fd23bfb3cc8\"]",
                        "[\"da991efa-4c25-489f-b813-caed1fb9a202\", \"da991efa-4c25-489f-b813-caed1fb9a202\"]",
                        "[\"db2a6c16-66ba-4de4-8d9b-47817cf1259b\", \"db2a6c16-66ba-4de4-8d9b-47817cf1259b\"]",
                        "[\"e0e81bb6-2972-4ae5-ae1c-cbcc886221ae\", \"e0e81bb6-2972-4ae5-ae1c-cbcc886221ae\"]",
                        "[\"e80403d1-15e7-4bbf-86db-85148b67baa8\", \"e80403d1-15e7-4bbf-86db-85148b67baa8\"]",
                        "[\"f2667a05-b80b-491e-8f56-b0a17f62ff09\", \"f2667a05-b80b-491e-8f56-b0a17f62ff09\"]",
                        "[\"f2e00229-cc20-4201-9548-912ed7d53299\", \"f2e00229-cc20-4201-9548-912ed7d53299\"]",
                        "[\"f4fbd56d-84e5-4fa8-9610-286e779160ff\", \"f4fbd56d-84e5-4fa8-9610-286e779160ff\"]",
                        "[\"fae208a5-97de-465c-8b12-fb7532edadec\", \"fae208a5-97de-465c-8b12-fb7532edadec\"]"
                    ],
                    "IsEmpty" : [
                        "[false, false]"
                    ],
                    "Tags.KeyValue" : [
                        "[\"01fbe4f9-77a5-48a2-8a3d-6b105808f6ackey6_ddd_01fbe4f9-77a5-48a2-8a3d-6b105808f6acvalue6\", \"01fbe4f9-77a5-48a2-8a3d-6b105808f6ackey6_ddd_01fbe4f9-77a5-48a2-8a3d-6b105808f6acvalue6\"]"
                    ]
                },
                "keysExamined" : 171412,
                "seeks" : 172,
                "dupsTested" : 171240,
                "dupsDropped" : 0,
                "seenInvalidated" : 0
            }
        }
    }


text:
Q: css3 transitions - How to make a div grow in height from bottom to top I am trying to make the following to work in IE10.
I have a div with id=footer for whom I am changing the class from class1 to class2.
The HTML code is as follows
<!DOCTYPE html>

        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
        <link rel="stylesheet" type="text/css" href="css/index.css" />
        <title>Test</title>

The CSS code is as follows
body {
    overflow: hidden;
    width:  100%;
    height:  100%;
}

#container {
    overflow:  auto;
    position: absolute;
    width:  100%;
    height:  90%;
    background-color:#808080;
    top:0;
    left:0;
    border-width: 1px;
    border-color: #000;
    border-style: groove;
}

#footer {
    overflow: auto;
    position: absolute;
    left:0;
    width: 100%;
    border-width: 1px;
    border-color:#f00;
    border-style: groove;
    background-color: #ffd800;

    transition-property: top, height;
    transition-duration: 1s, 1s;
    transition-delay: 0, 0;
}

.class1 {
    top: 90%;
    height: 10%;
}

.class2 {
    top: 70%;
    height: 30%;
}

Since I am simultaneously increasing both top and height, I expect the div to just riseup/expand when I am changing from class1 to class2 and just contract when changing from class2 to class1. This works as expected in Firefox.
But in IE10, when I change from class1 to class2, it is as if the transition effects are not obeyed for top. The div immediately shifts up and then the size gradually increases over 1 second.
So, how do I solve this problem and get the expected results in IE10?

A: I didn't experience in IE11 the dynamics you described.
Perhaps a solution would be to first set the height to 30% before changing the top.