text:
Q: How come these two alerts showing the height and offsetheight of the same element don't display the same number? the alerts are as follows:
alert(document.getElementById("col_st_scroll").offsetHeight);
alert(document.getElementById("col_st_scroll").style.height);

now, the col_st_scroll element is fully visible in the web browser, shouldn't that mean offsetHeight and style.height should returnt he same value?
problem solved. The element was resized by another function in the time it took to click ok ont he first alert.

A: This is from MDN:

Typically, an element's offsetHeight is a measurement which includes the element borders, the element vertical padding, the element horizontal scrollbar (if present, if rendered) and the element CSS height.

The style.height property represents the content height only (assuming you're on "strict" rendering mode, not "quirks").


text:
Q: How to make an error message pops up when someone doesnt enter anything into the plain text box? @Override
protected void onCreate(@Nullable Bundle savedInstanceState){
    super.onCreate(savedInstanceState);
    setContentView(R.layout.chat_room);

    btn_send_msg = (Button) findViewById(R.id.button13);
    input_msg = (EditText) findViewById(R.id.editText3);
    chat_conversation = (TextView) findViewById(R.id.textView4);

    user_name = getIntent().getExtras().get("user_name").toString();
    room_name = getIntent().getExtras().get("room_name").toString();
    setTitle("Room - " + room_name);

    root = FirebaseDatabase.getInstance().getReference().child(room_name);

    btn_send_msg.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {

            Map<String, Object> map = new HashMap<String, Object>();
            temp_key = root.push().getKey();
            root.updateChildren(map);

            DatabaseReference message_root = root.child(temp_key);
            Map<String, Object> map2 = new HashMap<String, Object>();
            map2.put("name", user_name);
            map2.put("msg", input_msg.getText().toString());

            message_root.updateChildren(map2);

            input_msg.setText("");
        }
    });

    root.addChildEventListener(new ChildEventListener() {
        @Override
        public void onChildAdded(DataSnapshot dataSnapshot, String s) {
            append_chat_conversation(dataSnapshot);
        }

        @Override
        public void onChildChanged(DataSnapshot dataSnapshot, String s) {

            append_chat_conversation(dataSnapshot);
        }

        @Override
        public void onChildRemoved(DataSnapshot dataSnapshot) {

        }

        @Override
        public void onChildMoved(DataSnapshot dataSnapshot, String s) {

        }

        @Override
        public void onCancelled(DatabaseError databaseError) {

        }
    });
}
private String chat_msg,chat_user_name;
private void append_chat_conversation(DataSnapshot dataSnapshot) {

    Iterator i = dataSnapshot.getChildren().iterator();

    while (i.hasNext()){

        chat_msg = (String) ((DataSnapshot)i.next()).getValue();
        chat_user_name = (String) ((DataSnapshot)i.next()).getValue();

        chat_conversation.append(chat_user_name + " - " + chat_msg + "\n");
    }
}

}
So this feature is for a chat room therefore I would like to be able to make it so users can just send blank messages into the chat room. So I would like an error to occur when a user tries to send a blank message.
Thanks!

A: check for input text and display toast or whatever you want.
 btn_send_msg.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                Map<String, Object> map = new HashMap<String, Object>();
                temp_key = root.push().getKey();
                root.updateChildren(map);

                DatabaseReference message_root = root.child(temp_key);
                Map<String, Object> map2 = new HashMap<String, Object>();
                map2.put("name", user_name);
                map2.put("msg", input_msg.getText().toString());

                message_root.updateChildren(map2);

              String inputMsg= usernameEditText.getText().toString();
              if (inputMsg.matches("")) {
              Toast.makeText(this, "You did not enter a value", Toast.LENGTH_SHORT).show();
        return;
    }
            }
        });

A: please check the message string before performing the data storing functionality of database like :
String str=input_msg.getText().toString().trim();

    btn_send_msg.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

            if(str != null && !str.isEmpty()){
                Map<String, Object> map = new HashMap<String, Object>();
                temp_key = root.push().getKey();
                root.updateChildren(map);

                DatabaseReference message_root = root.child(temp_key);
                Map<String, Object> map2 = new HashMap<String, Object>();
                map2.put("name", user_name);
                map2.put("msg", input_msg.getText().toString());

                message_root.updateChildren(map2);

                input_msg.setText("");
              }else{
               /// show the error msg to the user
              Toast.makeText(getActivity(), "Please enter the message",Toast.LENGTH_LONG).show();
              }

            }
        });

now in the database empty string can't store and also tell the user that need to message to send.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Can headless-chrome cast webgl dashboard to a google cast TV? I have a web-GL based analytics dashboard. The Google Cast device does not render WebGL content internally.
Can chrome-headless running on a local server be used render and cast a dashboard to a google-cast device?
I do not want to have a desktop system for this job, hence my interest in chrome-headless and google cast.

A: Google Cast Receiver apps do support WebGL. However, since it is running on hardware with limited resources, the performance will not be the same as on a desktop.
It is possible to cast a Chrome tab to a Cast receiver. However, this only works with the desktop version of Chrome.

A: For sure you can run google chrome inside Xvfb + VNC (to start and control chrome browser) and cast its tab to google cast device.
Problem with it can be some security issues with access to the server where chrome browser is started. More secure can be to use a separate device to cast like rPi or run it inside docker image.


text:
Q: How to read an excel multiple sheet to store the content of excel sheet into database I am new to java,
Now i have created the code for reading an excel sheet and sending it to the database using apache poi.
I have read the 1st sheet successfully with 1st query and sent it to the database, but i am not knowing how to read the 2nd sheet with the 2nd query and the table.
Here the 2 sheets have 2 different query,how to mention that in prepared statment.
Or is there any other way to do it.
Please do help me out with this issue.
The code is

<meta http-equiv="Content-Type" content="text/html">
<title>Excel</title>

<FORM ENCTYPE="multipart/form-data" ACTION="Excel.jsp" METHOD=POST>

UPLOAD THE FILE

Choose the file To Upload:

 <INPUT NAME="file" TYPE="file" accept=".csv, application/vnd.openxmlformats-  officedocument.spreadsheetml.sheet, application/vnd.ms-excel">

<INPUT TYPE="submit" VALUE="Send File" >

 </FORM>

 <jsp:useBean id="connection" class="DB.DB_Connection" scope="page">
 <jsp:setProperty name="connection" property="*"/>
 </jsp:useBean>

 <%!
   Connection con;
   PreparedStatement ps=null;
   PreparedStatement ps2=null;
   public static ArrayList readExcelFile(String fileName) throws SQLException
   {
     /** --Define a ArrayList
      --Holds ArrayList Of Cells

      */

      ArrayList cellArrayLisstHolder = new ArrayList();

     try{
           /** Creating Input Stream**/
          FileInputStream myInput = new FileInputStream(fileName);

          /** Create a POIFSFileSystem object**/
           POIFSFileSystem myFileSystem = new POIFSFileSystem(myInput);

          /** Create a workbook using the File System**/
           HSSFWorkbook myWorkBook = new HSSFWorkbook(myFileSystem);

          /** Get the first sheet from workbook**/

            HSSFSheet mySheet = myWorkBook.getSheetAt(0);
            HSSFSheet mySheet2 = myWorkBook.getSheetAt(1);

         /** We now need something to iterate through the cells.**/
            Iterator rowIter = mySheet.rowIterator();
            Iterator rowIter1 = mySheet2.rowIterator();
             while(rowIter.hasNext()){
             HSSFRow myRow = (HSSFRow) rowIter.next();
             Iterator cellIter = myRow.cellIterator();
              ArrayList cellStoreArrayList=new ArrayList();

             while(cellIter.hasNext()){
             HSSFCell myCell = (HSSFCell) cellIter.next();

              HSSFCell cell;

          short i= 1;

          do {
              cell = myRow.getCell(i);// Start from first column

              if (cell == null) {
                 break;
              }
              if (cell.getCellType() == HSSFCell.CELL_TYPE_STRING) {
                 // Plain String Cell.
                 System.out.println("The Cell is a String with value : "
                       + cell.getStringCellValue());
              } else if (cell.getCellType() == HSSFCell.CELL_TYPE_NUMERIC) {

                 // Excel stores the Date as a Numeric Contents. POI provides
                 // a Date utility to check
                 // if a particular cell is formatted as a date.
                 if (HSSFDateUtil.isCellDateFormatted(cell)) {

                    Date date = HSSFDateUtil.getJavaDate((double) cell
                          .getNumericCellValue());

                    SimpleDateFormat df = new SimpleDateFormat("dd/mm/yyyy");
                    System.out.println("The cell is a Date : " + df.format(date));
                 } else {
                    // treat the cell as 'double' number
                    System.out.println("The cell is a number : "
                          + cell.getNumericCellValue());
                 }

              } else if (cell.getCellType() == HSSFCell.CELL_TYPE_BLANK) {
                 // Some of the cells will be rendered blank when cells in
                 // Excel are merged... one such cell
                 System.out
                 .println("A Blank Cell Encountered.... any merging happened???");
              } else {
                 System.out.println("The cell is nothing we're interested in ...");
              }
              i++; // increment cell counter!!!
           } while (cell != null);

          cellStoreArrayList.add(myCell);

                    }
      cellArrayLisstHolder.add(cellStoreArrayList);
  }
  while(rowIter1.hasNext()){
      HSSFRow myRow1 = (HSSFRow) rowIter.next();
      Iterator cellIter1 = myRow1.cellIterator();
      ArrayList cellStoreArrayList1=new ArrayList();
      while(cellIter1.hasNext()){
          HSSFCell myCell1 = (HSSFCell) cellIter1.next();
          HSSFCell cell1;
          short i= 1;
          do {
              cell1 = myRow1.getCell(i); // Start from first column
              if (cell1 == null) {
                 break;
              }
              if (cell1.getCellType() == HSSFCell.CELL_TYPE_STRING) {
                 // Plain String Cell.
                 System.out.println("The Cell is a String with value : "
                       + cell1.getStringCellValue());
              } else if (cell1.getCellType() == HSSFCell.CELL_TYPE_NUMERIC) {

                 // Excel stores the Date as a Numeric Contents. POI provides
                 // a Date utility to check
                 // if a particular cell is formatted as a date.
                 if (HSSFDateUtil.isCellDateFormatted(cell1)) {
                    Date date = HSSFDateUtil.getJavaDate((double) cell1
                          .getNumericCellValue());
                    SimpleDateFormat df = new SimpleDateFormat("mm/dd/yyyy");
                    System.out.println("The cell is a Date : " + df.format(date));
                 } else {
                    // treat the cell as 'double' number
                    System.out.println("The cell is a number : "
                          + cell1.getNumericCellValue());
                 }

              } else if (cell1.getCellType() == HSSFCell.CELL_TYPE_BLANK) {
                 // Some of the cells will be rendered blank when cells in
                 // Excel are merged... one such cell
                 System.out
                 .println("A Blank Cell Encountered.... any merging happened???");
              } else {
                 System.out.println("The cell is nothing we're interested in ...");
              }
              i++; // increment cell counter!!!
           } while (cell1 != null);

          cellStoreArrayList1.add(myCell1);

                    }
      cellArrayLisstHolder.add(cellStoreArrayList1);
  }
}catch (Exception e){e.printStackTrace(); }
return cellArrayLisstHolder;
}

%>
<%

 File f = new File("DeptHosp.xls");
   System.out.println(f.getAbsolutePath());

  File file = new File(".");
 for(String fileNames : file.list()) System.out.println(fileNames);
String fileName="D://PROJECT//SOFTWARES//eclipse_Juno//eclipse//DeptHosp.xls";
System.out.println(" path found");
ArrayList dataHolder=readExcelFile(fileName);
//Print the data read
//printCellDataToConsole(dataHolder);

con=connection.getConn();
 System.out.println("Inserting the details");
 String query="insert into   departmentmaster(Dept_id,Dept_Groupid,Dept_Kid,Dept_Groupkid,Dept_Group,Dept_Name,Dept_type,Dept_HospitalId,Dept_datecreated,Dept_datelastrefreshed)values(?,?,?,?,?,?,?,?,?,?)";
  String query1="insert into hospitalmaster(hospital_group,hospital_name)values(?,?)";
   ps=con.prepareStatement(query);
  ps2=con.prepareStatement(query1);
   System.out.println("Database");
  int count=0;
     ArrayList cellStoreArrayList=null;
    Date datevalue=null;

  //For inserting into database
    for (int i=1;i < dataHolder.size(); i++) {
    cellStoreArrayList=(ArrayList)dataHolder.get(i);

   ps.setString(1,((HSSFCell)cellStoreArrayList.get(1)).getStringCellValue());
   ps.setString(2,((HSSFCell)cellStoreArrayList.get(1)).getStringCellValue());
   ps.setString(3,((HSSFCell)cellStoreArrayList.get(2)).getStringCellValue());
   ps.setString(4,((HSSFCell)cellStoreArrayList.get(3)).getStringCellValue());
   ps.setString(5,((HSSFCell)cellStoreArrayList.get(4)).getStringCellValue());
   ps.setString(6,((HSSFCell)cellStoreArrayList.get(5)).getStringCellValue());
   ps.setString(7,((HSSFCell)cellStoreArrayList.get(6)).getStringCellValue());
   ps.setString(8,((HSSFCell)cellStoreArrayList.get(7)).getStringCellValue());
   ps.setString(9,((HSSFCell)cellStoreArrayList.get(8)).getStringCellValue());
   ps.setString(10,((HSSFCell)cellStoreArrayList.get(9)).getStringCellValue());
   count= ps.executeUpdate();
   ps2.setString(1,((HSSFCell)cellStoreArrayList.get(1)).getStringCellValue());
   ps2.setString(2,((HSSFCell)cellStoreArrayList.get(1)).getStringCellValue());
   count= ps2.executeUpdate();

   }

A: Maybe you are mixing things.  You have already solved how to present a JSP, read an Excel file with POI and write rows into a database.  I suggest you to redesign your code to separe those tasks.  Maybe a simple class (Reader.java) which only reads the excel file and produces an ArrayList for each sheet, and then a simple class (Writer.java) with 2 methods, each of which takes an ArrayList and writes them to the database as needed.  That leads to a more simple top-down design, which would be easier to debug.
By the way, you are creating a database connection in your code and not returning it.  You should call the .close() method for every database resource (ResultSets, Statements and Connections) that you use in your application, or use some idiom (try with resources, Spring resources management, whatever) that makes sure to do so.
Bonus track: when you feel more comfortable with java, have a look at
http://en.wikipedia.org/wiki/Connection_pool
This would be the preferred manner to connect to a database in a web application with, potentially, hundreds or thousands of concurrent users.  Your idea, opening a new connection for each access to your page, which is perfectly right for an academic exercise, would lead to efficiency problems in a real environment.  Maybe your application server has a built-in connection pool mechanism (latest version of tomcat, weblogic, websphere have them for example) or maybe you could consider using apache DBCP or C3PO.


text:
Q: Get array values to display inside an object in a @foreach loop using Laravel Blade In a blade template, I have:
@foreach($users as $user)
 {{ $user->id }}  // this displays just fine, the number 1
 {{ $weeklyCallsArray{$user->id} }} // get "Undefined offset:" error
 {{ $weeklyCallsArray{1} }} // this works fine
@endforeach

How can I get the array to display with the corresponding user? I want to use something like:
$weeklyCallsArray{user->id}

Here is my query and return in the controller:
$users = DB::table('users')->get();
foreach ($users as $user) {
    $userId = $user->id;
    $countThisWeek = DB::table('calls')
        ->where('called_by', '=', $userId)
        ->where('calledd_on', '>=', Carbon::now()->startOfWeek())
        ->count();
    $weeklyCallArray[$userId] = $countThisWeek;
}

return view('users')
    ->with(['users' => $users])
    ->with(['weeklyCallsArray' => $weeklyCallsArray]);

A: I think you are using arrays wrong in the view?  I've never seen that syntax before.
$weeklyCallsArray[$user->id]

A: You should use eloquent and you can load calls of the user with the user.
$users = User::with(['calls' => function($q){
     $q->calledd_on >= Carbon::now()->startOfWeek());
}]->whereUserId($id)->get();

Then in your view you can count the calls like this:
@foreach($users as $user)
   {{ $user->id }}
   {{ count($user->calls) }}
@endforeach


text:
Q: Turn a Concatenated Row into a column SELECT
  b_Name+' | '+Entity+' | '+cast(A_Date as varchar) as [top]  -- Colum
  ,b_Name  -- Rows
  ,[Task_Category] -- Rows
  ,[Fcn_Name] -- Rows
  ,[Task]  -- Rows
  ,[Task_ID] -- Rows
  ,[Owner] -- Rows
  ,[RAG_Status] -- Rows
   FROM [Task]

I'm trying to make the concatenated [TOP] into column headings but leave the rest into rows.
I'm still learning SQL so, please be patent with me. lol
  SELECT *
FROM
(
    SELECT
b_Name+' | '+Entity+' | '+cast(A_Date as varchar) as [top]  -- Colum
      ,b_Name  -- Rows
      ,[Task_Category] -- Rows
      ,[Fcn_Name] -- Rows
      ,[Task]  -- Rows
      ,[Task_ID] -- Rows
      ,[Owner] -- Rows
      ,[RAG_Status] -- Rows
     FROM [IntegrationDBdev].[dbo].[Task_Acquisition]
) AS SourceTable PIVOT(AVG(task) FOR ????
IN(
??????

) ) AS PivotTable;

I've tried the above but not sure what to put in the pivot

A: I would not recommend this to have top as some concatenation in Pivot because in 'IN' condition you will have to have the concatenation as well.
but for your code you can have it like
CREATE TABLE Grades(
  [Student] VARCHAR(50),
  [Subject] VARCHAR(50),
  [Marks]   INT
)
GO

INSERT INTO Grades VALUES
('Jacob','Mathematics',100),
('Jacob','Science',95),
('Jacob','Geography',90),
('Amilee','Mathematics',90),
('Amilee','Science',90),
('Amilee','Geography',100)
GO

SELECT * FROM (
  SELECT
    [Student],
    [Subject]+'|'+[Student] as [Test1],
    [Marks]
  FROM Grades
) StudentResults
PIVOT (
  SUM([Marks])
  FOR [Test1]
  IN (
    [Mathematics|Amilee],
    [Science|Amilee],
    [Geography|Amilee],
    [Mathematics|Jacob],
    [Science|Jacob],
    [Geography|Jacob]
  )
) AS PivotTable

I would recommend it to be like
SELECT * FROM (
  SELECT
    [Student],
    [Subject],
    [Marks]
  FROM Grades
) StudentResults
PIVOT (
  SUM([Marks])
  FOR [Subject]
  IN (
    [Mathematics],
    [Science],
    [Geography]
  )
) AS PivotTable

which will give result

Let me know if any more clarificaiton needed.


text:
Q: PowerShell + Exchange Online - Using Where-Object to filter one object against different object? Really pulling my hair out on this one. I'm a bit of a beginner so apologies in advance.
I'm having trouble using the Where-Object cmdlet to basically remove external contacts from a Get-Group query in Exchange Online.
group@domain.com contains 4 members - InternalUser1, InternalUser2, ExternalUser1, ExternalUser2
This is what I have so far, and I've tried numerous different comparators (-notmatch, -notlike, -ne etc.) to no avail:
Input
$x = Get-Contact | Select-Object -ExpandProperty Identity
$y = Get-Group -Identity "group@domain.com" | Select-Object -ExpandProperty Members | Where-Object {$_ -notcontains $x}

Outputs
$x
ExternalUser1
ExternalUser2

$y
ExternalUser1
ExternalUser2
InternalUser1
InternalUser2

Desired Output
$y
InternalUser1
InternalUser2

Excluding the Where-Object part, the outputs are correct so the issue must lie with my use of the Where-Object cmdlet. Any help with this would be greatly appreciated!

A: Assuming your expanded variables contains a list of string, the following worked.
 $y | Where-object {$_ -notin $x}

Applied to your example
$x = Get-Contact | Select-Object -ExpandProperty Identity
$y = Get-Group -Identity "group@domain.com" | Select-Object -ExpandProperty Members | Where-Object {$_ -notin $x}

Complete reproducible standalone example .
$x = @(
'ExternalUser1',
'ExternalUser2'
)

$y = @(
'ExternalUser1',
'ExternalUser2',
'InternalUser1',
'InternalUser2'
)

$y | Where-object {$_ -notin $x}

If this does not work, do a :
$x[0].GetType()
$Y[0].GetType()

If either Member or Identity is a complex object rather than a string, you might need to get the actual string value out of there before using the -notin


text:
Q: what to do for performance when using a slug in an url? I see lots of websites using slugs in URLs, like these:
[catalog-product id="179"] ---> [catalog-product slug="5oz-modelling-hammer"]
I'd like to know: compared to Int search, will String search in MySQL cause performance problems?
I know about indexed fields, but I wonder whether it will cause a problem because the query is run whenever a page is visited.
And what is the best practice in table design or eve what are other back-end techniques I should know about?

A: This kind of question gets asked often in many forms:

*

*What's faster, require or include?

*What's faster, echo $a . $b or echo $a, $b?

*What's faster, DATE or VARCHAR?

*What's faster, number % 2 or number & 1?

Computers as fast enough to make the answer irrelevant. You'd need to do those operations like 1 billion times per page load to make a difference and, in that case, you'd have bigger problems. Performance bottlenecks tend to be fairly obvious:

*

*Link 50MB worth of pictures in your HTML

*Run SQL in loops and flood the DB server with hundreds of identical queries

*Read huge XML files in memory

To sum up, whether to use IDs, slugs or both is basically a design decision that does not depend on how fast the server is.

*

*Just numbers can be unacceptable for an e-commerce site that relies heavily on SEO

*Just slugs can be unacceptable for a community driven site where the page title can be freely modified


text:
Q: How does Thumb Mode work in a more energy-efficient way than ARM? As the Thumb use 16-bit instructions while ARM use 32-bit ones. By what means does the processor make it more energy efficient? By turning off some unit?

A: Everything remaining same, THUMB instructions will cause less amount of reads from RAM (FLASH if XIP), less pressure on the I-Caches for the same amount of compute done using ARM instructions. Since memory consumption is reduced so would your page faults and resulting page-ins from non-volatile storage. That said, if the savings were significant or quantifiable the ARM marketing team would have put out comparison numbers.


text:
Q: Datagridview checkbox column's value I have a DataGridView with a checkbox column. I want to capture the value of the checkbox immediately when user changes it by clicking. I tried several events (CellValueChanged, CellClicked, CurrentCellDirtyStateChanged etc.) but nothing worked.
This is my code:
If dgvIDsTBC.CurrentRow.Cells(2).Value = True Then
    MsgBox("True")
End If

Please help

A: Hope this helps
void dataGridView1_CellValueChanged(object sender, DataGridViewCellEventArgs e)
{
     if (e.ColumnIndex == 3)
        MessageBox.Show(dataGridView1[e.ColumnIndex, e.RowIndex].FormattedValue.ToString());
}

This i presume you would have done, now the catch is unless you move out of the cell the grid considers you are still editing ,So Add this part
void dataGridView1_CellMouseUp(object sender, DataGridViewCellMouseEventArgs e)
{
    if (e.ColumnIndex == 3)
       dataGridView1.EndEdit();
}

This should be fine for you, 3 is the checkbox column you intend it to work for


text:
Q: Page redirection not working for Android device I am working on Captive Portal. So when user join internet login page will come. once user entered credential it will show success page.So success page was loading before.My work was on success page load i need to redirect our url. So i hide all designs and body on load i wrote script for redirection. It works in ios and windows but not working in Android device.It is just loading page for 2 seconds then disappearing automatically.I tried through iframe but it did not work.
<body onload="redirect()">
<div>
<iframe name="iFrameName" src="" frameBorder="0" >
</iframe>
</div>
<script>
function redirect()
{
//   if(navigator.userAgent.match(/Android/i))
//     window.open("http://xxxx.xxx/",'_system')
//   else
//     window.location.replace("http://xxxx.xxx/");
var site = "http://xxxx.xxx/";
document.getElementsByName('iFrameName')[0].src = site;
}
</script>

</body>

Commented code i tried fast, but it did not work.Any help please?

A: JavaScript is disabled in a WebView by default. You need to turn it on:
WebView myWebView = (WebView) findViewById(R.id.webview);
WebSettings webSettings = myWebView.getSettings();
webSettings.setJavaScriptEnabled(true);

A: I hope you give internet permission into android mainfest file like this way..
<uses-permission android:name="android.permission.INTERNET" />

Try this code..
   mWebView = (WebView) findViewById(R.id.activity_main_webview);
    myWebView.getSettings().setJavaScriptEnabled(true);
   mWebView.loadUrl("https://www.bluehost.com/track/businessplan/");


text:
Q: Page on background tab not loading properly I am using Polymer 1.0 with jQuery and have created a small single page app. When I "Open link in new tab", however, the page doesn't load. More specifically, it loads in template form and fires the ajax requests to get the data, but none of that data gets populated into the template. For example, a simplified version:
$(document).ready(function(){
    url = '/ajax/get_data';
    $.post(url, '', function(data) {
      if (data.data.id !== undefined & data.data.id > 0) {
        $('.gt-info-location').text(data.data.name);
        $('.gt-city-population').text(data.population);
        $('.gt-city-timezone').text(data.data.timezone);
        $('.gt-city-county').text(data.data.county);
        $('google-map')[0].latitude = data.data.latitude;
        $('google-map')[0].longitude = data.data.longitude;
        $('#location-frontpage').css('background',"url('pictures/"+data.data.image_file+"') center / cover");
        $('#location-back').css('background',"url('pictures/"+data.data.image_file+"') center / cover");
      }
    });
});

I know the $.post is happening and returning the correct data from the web request log, but none of the .text() or .css() functions are making any changes to the page. And, yes, loading the same page in an open tab works fine.

A: It's a little hacky, but I put everything I'd been doing on .ready() into a function called loadDataAndPopulateToken() and then in addition to running that function on .ready() I also bound it to window focusing:
$(document).ready(function(){
  // initial token load (doesn't work if in background tab)
  loadDataAndPopulateToken();

  // reload the token data whenever the page comes into focus
  window.onfocus = loadDataAndPopulateToken;
});

The downside to this approach is that it reloads all the data whenever the tab passes out of focus and then back into it.


text:
Q: How to Recover Google Chrome User Settings Someone logged in as a user and removed all of the Google Chrome user's apps, extensions, bookmarks, history, and settings. After which, they closed the browser window and restarted it (overwriting the hidden backup file Chrome makes). These changes have already propagated out to the other machines via Google Sync.
How can I recover this data? Ideally, with as much forensic information as possible (date/times deleted, accessed, etc). I need to recover this data ASAP.
I'm digging around on Google now, but I haven't had made any real headway yet. I'll update this thread with any info I find / attempt.

A: By following the instructions from http://shaneamurray.blogspot.com/2011/06/restore-lost-extensions-in-google.html, I was able to recover all of the apps, extensions, bookmarks, et al.
Essentially, from a Windows 7 PC, you can go to the following path:
C:\Users{username}\AppData\Local\Google\Chrome\ and right-click on the "User Data" folder. From there, go to Properties, and then the "Previous Versions Tab" and you will be able to restore to an earlier version when the extensions / settings were available.
NOTE: Make sure that the Google Chrome process is not running (including in the System Tray) when restoring the files or you will receive an error (in which case, simply kill the process and hit the 'Try Again' button on the error prompt).
This will restore everything, it appears, other than the Google Gadgets. Unfortunately, I still have to dig through the Linux box where the settings were originally altered and attempt to find some information to determine the date/time the incident occurred. So, the forensic aspect is still a work in progress, but at least the user data has been restored and they learned an incredibly important lesson... Don't leave your PC unlocked.


text:
Q: Where to put routers.py for database routing in a Django project I am trying to put a routers.py file into a Django project so that my application will use two different databases: one for my external data, the other for the pages in my newly-installed Wagtail CMS.
Where in the file system should I put routers.py?
The file system currently looks like this:
projectname/
    projectname/
        settings.py
        urls.py
        wsgi.py
    app1/
        admin.py
        apps.py
        models.py
        views.py
    app2/
        admin.py
        apps.py
        models.py
        views.py
    somedataloader.py
    requirements.txt
    logfile

A: I put mine in projectname/projectname/, parallel with settings.py, since I see it as a kind of setting. But you refer to it by its Python module path in DATABASE_ROUTERS so you could put it somewhere else if you prefer.


text:
Q: Не удаётся получить длинну VKUsersArray VKUsersArray назвал VKF.
Знаю, что можно получить значение через VKF.get(int)
Например:
VKF.get(7).first_name

выводит строку с именем. Вопрос в следующем, как можно получить его длину?

A: Вопрос решён. Кому интересно:
for(VKApiUserFull userFull : VKF) {
                    data.add(new mainListClass(VKF.get(i).first_name + " " + VKF.get(i).last_name, "Подзаголовок1", "20:00", false));
                    i++;
                }


text:
Q: Optimal lower bounds for the sum of digits in base $b$ Let $b \geq 2$ be an integer and let $s_b(n)$ be the sum of the digits of the base-$b$ representation of the nonnegative integer $n$
(e.g., $s_{10}(726)=7+2+6$). From the weak law of large numbers, it follows that
$$s_b(n) > \left(\tfrac{0+1+\cdots + (b-1)}{b}-\varepsilon\right) \log_b n$$
for almost all the positive integers $n \leq x$, with at most $o(x)$ exceptions, as $x \to +\infty$.
Therefore, if $\{a_k\}_{k=1}^\infty$ is a "generic" monotone increasing sequence of positive integer, it is quite reasonable to expect that
$s_b(a_k) > C \log(a_k)$ for almost all $k$, i.e., with the exception of a set of asymptotic density 0,  where $C$ is a positive constant (depending on the sequence $\{a_k\}_{k=1}^\infty$).
By "generic" I means, informally speaking, that $\{a_k\}_{k=1}^\infty$ has not some trivial properties that makes the statement false (e.g., $a_k := b^k$).
So for example, we can conjecture that
$$s_b(n!) > C_1 n \log n$$
$$s_b(a^n) > C_2 n$$
$$s_b(F_n) > C_3 n$$
for almost all $n$, where $a$ is a positive integer coprime to $b$ and $F_n$ is the $n$-th Fibonacci number.
In [1] and [3] they have been shown the weaker lower bounds $s_b(n!) > C_1 \log n \log \log \log n$ (see also [2]) and $s_b(F_n) > C_2 \log n / \log \log n$, for all integers $n$, respectively. Moreover, in [4] the bound $s_b(a_n) > C \log n$ for almost all $n$, has been proved for any sequence of integers
$$a_n = e^{f(n)} (1 + O(n^{-\alpha}))$$
where $\alpha > 0$ and $f(x)$ is a two times differentiable function satisfying $f(x) \asymp 1/x$ for large x.
My question is: Are there some non(too)trivial example of $\{a_k\}_{k=1}^\infty$ such that the optimal lower bound $s_b(a_k) > C \log(a_k)$, for almost all $k$, has been proved?
Thank you very much for any suggestion/reference.
[1] C. Sanna, On the sum of digits of the factorial, J. Number Theory 147, 2015, 836--841.
[2] F. Luca, The number of nonzero digits of n!, Canad. Math. Bull., 45, 2002, 115--11.
[3] F. Luca, Distinct digits in base b expansions of linear recurrence sequences, Quaest. Math., 23, 2000, 389--404.
[4] J. Cilleruelo, F. Luca, J. Rué and A. Zumalacárregui, On the sums of digits of the some sequences of integers, Cent. Eur. J. Math., 11, 2013, 188--195.

A: The first paper you reference concerns simply the number of non-zero digits of $n!$  and not their sum. Of course that just changes the constant in front. That paper does note that the bound is quite weak compared to what one might expect. For example in the case $b=2$ his bound assures us that $n!$ has at least $7$ non-zero digits provided that $n$ is at least $767$ (by which point $n!$ has many thousand binary digits.) That is enough to allow one to establish that $n=9$ is actually the last case with as few as $6$ bits equal to $1.$ Then $9!=1011000100110000000_2$ So what can be proved is certainly far weaker than what one might expect.
However the case of $n!$ is certainly not generic. It is entirely predictable that there are $\lfloor 9/2 \rfloor+\lfloor 9/4 \rfloor+\lfloor 9/8 \rfloor=4+2+1$ $0$'s on the right. The other $12$ leading digits might be expected to split roughly equally and in fact split exactly equally.


text:
Q: How to plot boxplots at once when your x variable has more than 10 values I used the following code for plotting the variable TYPE (which has around 100 factors) vs the variable MEASURE. I don't mind having separate boxplots, but I will like to know if there is a way to plot or code all factors at once instead of one by one.
figa <- ggplot(dftest, aes(x = TYPE, y =  MEASURE))+
  geom_boxplot()
figa

A: It seems you are plotting all the TYPE factors, and they are not readable.
I add +coord_flip() to boxplots to make the result more readable:
library(tidyverse)
g<-ggplot(iris, aes(x = Species, y =  Sepal.Length))+
  geom_boxplot()+
  coord_flip()
ggsave("test.png", g, height = 15 , width = 7) # tall 15x7 for example


text:
Q: Connect edges with graph dot I need to add a link between two edges using dot.
What I need to add to the graph is the red link labeled "b" between the two edges showed in picture.
The source code is the following:
digraph {
    a -> b;
    a -> c;
}

A: Today I had the same problem and solved it with a small hack:

*

*create small point-shaped nodes for each edge you want to connect

*connect the main-nodes via the fake-nodes

*connect the fake-nodes

digraph {
    fakeAB [label="", shape=point, width=0.01, height=0.01];
    fakeAC [label="", shape=point, width=0.01, height=0.01];

    {
        rank=same;
            "b"; "c";
    }

    {
        rank=same;
            fakeAB; fakeAC;
    }

    "a" -> fakeAB [arrowhead=none];
    "a" -> fakeAC [arrowhead=none];
    fakeAB -> "b";
    fakeAC -> "c";

    fakeAB -> fakeAC [label="b", color="red", arrowhead=none];
}

The result:


text:
Q: compile and execute c program with argument I am new in C program and linux, how can we compile and run this program?
I have tried gcc example.c then ./a.out but it gives an error like input file cannot be opened ( I have written this error in the read method)
// example.c
int main(int argc, char *argv[])
{
    char* input = argv[1];
    read(input);

    char* output = argv[2];
    write(output);

    return 0;
}

Thanks.

A: Your program isn't going to work very well - you're not providing enough arguments to read and write, for example (assuming you mean to be calling POSIX read(2) and write(2), that is).
To answer your actual question, the problem appears to be that you're not providing any arguments.  You need to run it something like:
./a.out FILE1 FILE2

replacing FILE1 with the name of your input file and FILE2 with the name of your output file.

A: Firstly read() and write() both take 3 arguments(only one given).
Secondly it should be used like this:
int ifilehandle = open(argc[1],O_RDONLY,S_IREAD);
int ofilehandle = open(argc[2],O_WRONLY,S_IWRITE);
char buffer[32767];
read(ifilehandle,&buffer,32766);
write(ofilehandle,&buffer,32766);
close(ifilehandle);
close(ofilehandle);

Thirdly, a.out should be invoked like this:
./a.out filename1.extension filename2.extension


text:
Q: Select TOP 3 values with their respective groups and values So i have a table like this

user
GROUP
VALUE

A
G1
0.9

A
G2
0.8

A
G3
0.3

A
G4
0.7

B
G1
0.9

B
G2
0.8

B
G3
0.7

C
G1
0.9

C
G2
0.8

and need to get to something like this

user
first_G
Fir_G_val
second_G
sec_G_val
third_G
thi_G_val

A
G1
0.9
G2
0.8
G4
0.7

B
G1
0.9
G2
0.8
G3
0.7

C
G1
0.9
G2
0.8
NULL
NULL

I tried in different ways, none worked out for me (Guided by this post)

A: This operation is called pivot and can be carried out by:

*

*selecting the ranking for each group, using the ROW_NUMBER window function

*extracting group and value alternatively, for each of the new field

*aggregating values on each user

WITH cte AS (
    SELECT *, ROW_NUMBER() OVER(PARTITION BY user_ ORDER BY VALUE DESC) AS rn
    FROM tab
)
SELECT user_,
       MAX(CASE WHEN rn = 1 THEN GROUP_ END) AS first_G,
       MAX(CASE WHEN rn = 1 THEN VALUE_ END) AS first_G_val,
       MAX(CASE WHEN rn = 2 THEN GROUP_ END) AS second_G,
       MAX(CASE WHEN rn = 2 THEN VALUE_ END) AS second_G_val,
       MAX(CASE WHEN rn = 3 THEN GROUP_ END) AS third_G,
       MAX(CASE WHEN rn = 3 THEN VALUE_ END) AS third_G_val
FROM cte
GROUP BY user_


text:
Q: write dataframe to csv file took too much time to write spark I want to aggregate data based on intervals on timestamp columns.
I saw that it takes 53 seconds for computation, but 5 minutes to write result in the CSV file. It seems like df.csv() takes too much to write.
How can I optimize the code please ?
Here is my code snippet :
val df = spark.read.option("header",true).option("inferSchema", "true").csv("C:\\dataSet.csv\\inputDataSet.csv")

//convert all column to numeric value in order to apply aggregation function
df.columns.map { c  =>df.withColumn(c, col(c).cast("int")) }

//add a new column inluding the new timestamp column
val result2=df.withColumn("new_time",((unix_timestamp(col("_c0"))/300).cast("long") * 300).cast("timestamp")).drop("_c0")

val finalresult=result2.groupBy("new_time").agg(result2.drop("new_time").columns.map(mean(_)).head,result2.drop("new_time").columns.map(mean(_)).tail: _*).sort("new_time")

finalresult.coalesce(1).write.option("header", "true").csv("C:/result_with_time.csv")//<= it took to much to write

A: Here are some thoughts on optimization based on your code.

*

*inferSchema: it will be faster to have a predefined schema rather than using inferSchema.

*Instead of writing into your local, you can try writing it in hdfs and then scp the file into local.

*df.coalesce(1).write will take more time than just df.write. But you will get multiple files which can be combined using different techniques. or else you can just let it be in one directory with with multiple parts of the file.


text:
Q: Is there a way to use an "arbitrary" variant as a parameter? Imagine I have some function which is overloaded for many different types.
void func(int value){ ... }
void func(double value){ ... }
void func(bool value){ ... }

Is there a way I can define it for a std::variant of an arbitrary combination of the overloaded types? e.g.
template<class... Ts> struct overload : Ts... { using Ts::operator()...; };
template<class... Ts> overload(Ts...) -> overload<Ts...>;

void func(std::variant<> variant)
{
  std::visit(overload{[](auto& value) { func(value); }}, variant);
}

Such that I wouldn't have to write a separate overload for each possible template, i.e. in the following example
std::variant<int, double> v1;
std::variant<double, bool> v2;
std::variant<int, double, bool> v3;

func(v1);
func(v2);
func(v3);

All three calls would use the single "arbitrary variant" overload of func().
Note that there could be many more types involved than just the three primitive types I listed.
Edit: Added additional clarity.

A: With variadic template, you might do:
template <typename... Ts>
void func(const std::variant<Ts...>& variant)
{
    std::visit([](auto& value) { func(value); }, variant);
}

Demo


text:
Q: Hex encode ECDSA keys in node.js I'm building a nodejs app that talks to an API server. The API server requires that each request I make to it includes a X-Signature header using the prime256v1 ECDSA curve and sha256 hash on a particular set of data.
I looked through the crypto and tls documentation but didn't find anything suitable. I have successfully generated a private key with openssl ecparam -name prime256v1 -genkey but it is in PEM format. I have also generated a DER format key. Both of these include some extra metadata like the curve used and in the case of PEM, comments.
I can use these keys for signing operations on my side, but the server requires that I upload a public key using hex encoding (so the server can verify the signatures I make on my requests.)
Specifically the server wants something like the output of the following Python code:
from ecdsa import SigningKey
from binascii import hexlify
hexlify(SigningKey.from_pem(content).to_string())

Sample output for a pubkey (no newlines): c5bd76cd0cd948de17a31261567d219576e992d9066fe1a6bca97496dec634e2c8e06f8949773b300b9f73fabbbc7710d5d6691e96bcf3c9145e15daf6fe07b9
I would prefer not adding python as a dependency to my node app... anyone know of a way I can extract the binary data representing my private key from the PEM or DER files, so I can put it in a buffer and call buffer.toString('hex')? Or a way I can use the native crypto library to generate the ECDSA keypair? Or a library that would do the same?

A: openssl itself can print out the guts of things, in hex.
Doe the key change? sounds like you can just decode into hex one time, and use that?  No need for dependencies - just paste the hex into your node source?


text:
Q: Low level capabilities of high level languages I would like to know some low-level capabilities of high-level languages.
Off the top of my head I could point out:
-bitwise operations
-bit fields
-pointer arithmetic
-inline assembly
-interrupt functions
I would apreciate if you pointed out some, that aren't in my list. It would be nice if C or Pascal had them, but basically any high-level language will do.
Thank you.

A: C does not support inline assembler nor interrupts, all C code implementing them is using non-standard compiler extensions. C++ however, has support for inline assembler through the standard.
Here are some other important, hardware-related features of C:

*

*Function pointers are rather unique for C/C++ and makes it possible to execute code located at a specific memory address, and makes it possible to perform other hardware-related tasks. See this for more details of function pointer uses: Function pointers in embedded systems.

*The integer types. Both C and Pascal support int types of different sizes (byte, word, double word etc), although their sizes are not specified by the standards. For the same reason, the sizeof operator may be important as well.

*C also has some support for memory alignment, for example explicitly stating rules for how padding bytes should behave.

*The volatile keyword is also an important feature for hardware-related programming, as it allows variables to be updated in realtime, and without worries about compiler optimizations.

*The const keyword is used in hardware-related programming to determine where the data will end up: NVM or RAM.
Other important features that C lacks are multi-threading support as part of the language, and memory barrier support. Some C compilers implement memory barriers through the volatile keyword, but there are no guarantees for it to work by any standard.

A: Quoting Wikipedia:

A high-level programming language is a programming language with strong abstraction from the details of the computer.

C is no such language, as it stays extremely close the the details of the computer.

And looking at your list:

*

*bitwise operations

*bit fields

*pointer arithmetic

*inline assembly

*interrupt functions

All of those are closely related to the computer/OS architecture itself and are considered not high-level.

A: One high-level language with very good support for low-level programming is Ada.
In addition to previously mentioned C, Ada has also intrinsic support for concurrent systems. Tasks are a language construct, and do not need separate libraries. For concurrent systems, Ada also provides so called protected types, which allows usage of shared variables or data between tasks without additional consideration of mutual exclusion or signalling. The basic language libraries also provide support for interrupt handling.
For data access, the exact representation of data can be defined by the use of representation clauses. As a result of strong typing, it is also trivial to define view conversions between different representations of data, allowing for example tradeoffs between space and speed.
It is also possible to directly generate assembly as needed, by machine code insertions.


text:
Q: aws S3 sync command is not working for replicated objects in S3 I have replicated the objects in S3 from one account to another. After replicating the objects into another account, I have tried  using aws S3 sync command from the replicated account to copy the objects into ubuntu server. However, it is showing as Access Denied. Tried using aws S3 sync command with source bucket, it was able to download the images from source S3 bucket.
Bucket policy:

 {
>     "Version": "2012-10-17",
>     "Statement": [
>         {
>             "Sid": "DelegateS3Access",
>             "Effect": "Allow",
>             "Principal": {
>                 "AWS": "arn:aws:iam::acnt"
>             },
>             "Action": [
>                 "s3:ListBucket",
>                 "s3:GetObject",
>                 "s3:ObjectOwnerOverrideToBucketOwner"
>             ],
>             "Resource": [
>                 "arn:aws:s3:::name/*",
>                 "arn:aws:s3:::name"
>             ]
>         }
>     ]
}

A: When replicating Amazon S3 objects to a bucket owned by a different AWS Account, it is important to change the 'owner' of the objects to the new Account.
From Changing the replica owner - Amazon Simple Storage Service:

In replication, the owner of the source object also owns the replica by default. When source and destination buckets are owned by different AWS accounts, you can add optional configuration settings to change replica ownership to the AWS account that owns the destination bucket. You might do this, for example, to restrict access to object replicas. This is referred to as the owner override option of the replication configuration.
To configure the owner override, you do the following:

*

*Add the owner override option to the replication configuration to tell Amazon S3 to change replica ownership.

*Grant Amazon S3 permissions to change replica ownership.

*Add permission in the destination bucket policy to allow changing replica ownership. This allows the owner of the destination bucket to accept the ownership of object replicas.


text:
Q: Can I clip DirectX viewport into a single win32 control and use it together with other controls? I was drawing triangles in D3D.
Doing that, I noticed that I always used the whole window for rendering and what if I want to create editor for something or 2D game engine or similar that requires GUI controls? Should I put separated dialog boxes that contain that controls (as shown on this image) or I should just clip this viewport into certain place on window or control such as on this example:

I tried to use static control handle for DXGI_SWAP_CHAIN_DESC::OutputWindow instead of main window handle and program crashed. And this made me very confused.
I didn't provide code because there are identical examples of initializing DirectX.


text:
Q: What does this '|' mean in node()|@* I wish to know what is the purpose of "|" in node()|@*..
I know that node() means all child of current node and @* means all attributes for the context nodes,but I don'nt understand why that 'or' symbol (as in any programming language) is there??
What purpose does it serves??


text:
Q: Using InputView property on iOS I have developed a custom keyboard with a view and a view controller.  In my application's main view controller, I hold a property for the custom keyboard view controller.
I have a textView which should get input from the custom keyboard. The customKeyboard property is the view controller for the custom keyboard.
I put the following in viewDidLoad of the main application's viewController.
self.textView.inputView = self.customKeyboard.view;

The standard system keyboard appears when I make the textView first responder.  IB appears to be linking my textView property to the UI component.  What do I need to do to get the custom keyboard to appear?

A: Try some calls to [self.textView reloadInputViews]. If that doesn't work, try to subclass UITextView and override its inputView method such that it always returns the view you want to use as the custom keyboard.


text:
Q: Transforming a list of Long into a Map with long item as the key and list of String as the value I have a person
class Person{
  private Long id;
  private String firstName;
  private String lastName;
  //with getters and setters
}

I have a following method that receives a person's id and returns a list of tags that are associated with the person
public List<String> getTags(Long personId){
 /*ExampleImplementation*/
   someCollection.stream()
     .filter(Objects::nonNull)
     .map(SomeType::someMethod)
     .filter(Objects:nonNull)
     .collect(Collectors.toList());
}

I am building a method in order to get a map of all the personIds and the list of tags associated with the personId.
public Map<Long, List<String>>getPersonTags(List<Long> personIds){
  return personIds.stream()
            .collect(Collectors.groupingBy(
            (personId) -> personId,
            Collectors.mapping(this::getTags, Collectors.toList())));
}

But getPersonTags() is returning a Map<Long, List<List<String>>> but I expect a Map<Long, List<String>> What should I change to get my expected return type.

A: If personIds contains distinct values, you don't need to use groupingBy(). Use toMap() instead:
return personIds.stream()
        .collect(Collectors.toMap(Function.identity(), this::getTags));


text:
Q: Authenticating to the Google Admin Directory API I'm trying to figure out how to authenticate to the Admin Directory API. My goal is to be able to create new GSuite users.
I have followed this guide https://github.com/jay0lee/GAM/wiki/CreatingClientSecretsFile to setup a client/id secret and service account with Domain-Wide Delegation.
I can successfully get a bearer token, however when I try to make a request to an endpoint I get a 403. I would expect I should be authenticated to this endpoint as I can successfully get all data using GAM, which is using the same credentials.
require 'googleauth'
require 'google/apis/admin_directory_v1'

scope = ["https://www.googleapis.com/auth/admin.directory.user.readonly", "https://www.googleapis.com/auth/admin.directory.user"]

authorizer = Google::Auth::ServiceAccountCredentials.make_creds(
  json_key_io: File.open('service_account.json'),
  scope: scope)

pload = authorizer.fetch_access_token!
token = pload["access_token"]

url = "https://www.googleapis.com/admin/directory/v1/users/my@email.com"
uri = URI.parse(url)
request = Net::HTTP::Get.new(uri)
request.content_type = "application/json"
request["Authorization"] = "Bearer #{token}"

req_options = {
  use_ssl: uri.scheme == "https",
}

response = Net::HTTP.start(uri.hostname, uri.port, req_options) do |http|
  http.request(request)
end

p response #=> <Net::HTTPForbidden 403 Forbidden readbody=true>

A: Fixed the scopes on the Service Account and everything works fine.


text:
Q: Sequelize and Jest not playing well together To be a bit more specific, I'm using Jest's globalSetup and globalTeardown functions/files to setup my database once at the start, and then also close and drop the tables at the end.
This isn't really the best solution, but sadly it's the only one that even remotely works without errors. Ideally, I would like to be able to establish the database connection once, and then drop/clear tables and re-create them after every test suite. Usually, with other databases (specifically Mongoose/NoSQL), this could be accomplished with Jest's beforeAll/Each and afterAll/Each no problem, but sadly this results in a lot of errors with Sequelize, specifically that it tries to re-establish the database connection every time which results in a lot of port/listen errors.
The reason I say my current setup of using the global files "sort of" works, is because the setup part works perfectly, but the teardown part, AKA await db.dropAllSchemas({}); doesn't work at all. The tables are kept throughout all tests, unless I manually wipe them.
If someone has any experience with this, I would ideally like to achieve the solution I posted in the first part, but worst case I'd like to fix what I currently have so it drops tables at the end of all tests.
This is the code I'm using to try and achieve the FIRST solution (without global files), and which causes all the errors;
setupTestFramework.js
import { db } from '../../src/startup/database';

beforeAll(async () => {
  await db.sync();
});

afterAll(async () => {
  await db.dropAllSchemas({});
});

This code results in the errors;
SequelizeDatabaseError: Table 'db_tests.products' doesn't exist

It also results in a sort of scatter in the tests. Some of the initial tests pass (mainly 1–2 and probably because they are on the same DB connection), but after those all test fail.
Hopefully someone can help out as I've not really been able to find a decent solution to this.
EDIT:
database.js
import config from 'config';
import Sequelize from 'sequelize';
import { info } from 'winston';

export const db = new Sequelize(
  config.get('db.database'),
  config.get('db.username'),
  config.get('db.password'),
  {
    host: config.get('db.host'),
    port: config.get('db.port'),
    dialect: 'mysql',
    operatorsAliases: false,
    logging:
      process.env.NODE_ENV === 'production' || process.env.NODE_ENV === 'test' ? null : console.log,
  }
);

export default async () => {
  try {
    await db.authenticate();
    info('Connected to database successfully...');

    await db.sync();
  } catch (error) {
    throw new Error('Unable to connect to database...');
  }
};

A: I had an issue similar to yours, i fixed it by closing the db connection at the end of all tests.
Export your db in your database config file and import it in your test class, then you can close the connection at the end of all tests.
afterAll(() => {
    db.close()
})

Note: when you drop all schemas, it removes all tables (for postgres db), instead close the connection after each test suites.


text:
Q: How do I get esri map view to change with a service in angular 8? I am trying to get the map to change when you reach a different slide in the scroll-spy. I'm having trouble getting a number from the service to use as an index for an array. I put the project up here on stackblitz.
This is the app.component.ts
export class AppComponent  {
  slides=slides
  mapCenter = [-121.448637, 37.724050];
  basemapType = 'satellite';
  mapZoomLevel = 13;
  currentSection:any = 1;
  toggleSidebar() {
    if (document.getElementById("mySidebar").style.display === "none") {
    document.getElementById("mySidebar").style.display = "block";
  } else {
    document.getElementById("mySidebar").style.display = "none";
  }
  }
   constructor(private data: SlideService) { }
    ngOnInit() {
    this.currentSection = this.data.currentMessage.subscribe(msg => this.currentSection = msg.slice(-1));

    let zoomlist:any[]=[];
    for (let slide of slides){
      if(slide.MapAttributes.viewType==="detailed"){
        continue;
      }
      let zoom = slide.MapAttributes.Zoom
      zoomlist.push(zoom)
    }
    this.mapZoomLevel = zoomlist[(+(this.currentSection)-1)]

    let centerlist:any[]=[];
    for (let slide of slides){
      if(slide.MapAttributes.viewType==="detailed"){
        continue;
      }
      let center = slide.MapAttributes.MapCenter
      centerlist.push(center)
    }
    this.mapCenter = centerlist[(+(this.currentSection)-1)]
  }

This is the html

      <app-sidebar id="mySidebar"class="col-sm-4"></app-sidebar>

        <app-esri-map [center]="mapCenter" [basemap]="basemapType" [zoom]="mapZoomLevel" (mapLoaded)="mapLoadedEvent($event)"></app-esri-map>

    <button (click)="toggleSidebar()" id= "infoToggle">current:{{currentSection}}</button>

and this is the service
import { Injectable } from '@angular/core';
import { BehaviorSubject } from 'rxjs';

@Injectable({
  providedIn: 'root'
})
export class SlideService {

  private messageSource = new BehaviorSubject<string>("slide1");
  currentMessage = this.messageSource.asObservable();

  constructor() { }

  changeMessage(msg: string) {
    this.messageSource.next(msg);
  }

}

A: Maybe you already found an answer to your question, but here are my suggestions on how to achieve that. I will assume you only want to modify the center position and the zoom level of your map whenever your slide changes.
You are already giving the center and zoomLevel parameters as input to your esri-map-component, but those values need to be updated whenever the slide changes. This can be achieved by modifying the app-component like that :

constructor(private data: SlideService) { }
    ngOnInit() {
    this.currentSection = this.data.currentMessage.subscribe(msg =>  {
      this.currentSection = msg.slice(-1);
      this.updateMapCenter();
      });
  this.updateMapCenter();

  }

  updateMapCenter() {
    let zoomlist:any[]=[];
    for (let slide of slides){
      if(slide.MapAttributes.viewType==="detailed"){
        continue;
      }
      let zoom = slide.MapAttributes.Zoom
      zoomlist.push(zoom)
    }
    this.mapZoomLevel = zoomlist[(+(this.currentSection)-1)]

    let centerlist:any[]=[];
    for (let slide of slides){
      if(slide.MapAttributes.viewType==="detailed"){
        continue;
      }
      let center = slide.MapAttributes.MapCenter
      centerlist.push(center)
    }
    this.mapCenter = centerlist[(+(this.currentSection)-1)]
  }

This way, the bindings on your esri-map-component are reevaluated each time the slide changes. All you have to do now is to listen to those changes on your esri-map-component :

ngOnChanges(changes) {
    if(this.mapView && changes && changes['center']) {
      this.mapView.goTo(this._center);
      this.mapView.zoom = this._zoom;
    }
  }

The mapView needs to be a property of the esri-map-component itself.
Hope this helps!


text:
Q: validating with combination I am trying to validation on a password in javascript . Can someone shed some light on creating the perfect regular expression or another way of validating it. I tried various ways but didn't worked
But this doesn't work.

A: You need to use \[, \], \- to make it a part of the character class
([\d.\[!@#$%^&()\-_=+{};:,<.>\]]){2}

const strArr = ["1@", "11", "#$", "aa", "aa1#"];

const regex = /([\d.\[!@#$%^&()\-_=+{};:,<.>\]]){2}/g;

const result = strArr.flatMap((s) => {
  const matches = s.match(regex);
  if (matches && matches.length) console.log("NOT SELECTED");
  else console.log("SELECTED");
  return matches;
});
console.log(result);

A: You can abuse a lookahead on every character to determine that no index is followed by two of the specified characters.

const regex = /^(?:(?![\d!@#$%^&()-_=+{};:,<.>]{2}).)+$/;

["1@", "11", "#$", "aa", "aa1#"].forEach(str => {
  console.log(str, regex.test(str));
});

It is a bit wasteful, but in this version it should not be a problem.
Depends on how you use that construct; what you put around/inside it.
Read about ReDoS attacks.


text:
Q: How to synchronize Direct3D 11 overlay with WPF Viewport3D? I'm developing a WPF application showing a 3D scene. While I use the Viewport3D control to display 2D WPF controls within that scene, I use native Direct3D 11 in a transparent overlay window for complex animated 3D geometries. This works fine.
The one and only problem is, that currently there may be a significant delay because the Direct3D overlay window is not synchronized with the WPF Viewport3D. It becomes only visible when the camera is moved around because then the Viewport3D rendering has to be updated just like the Direct3D rendering. Ideally, the Direct3D buffer should be swapped immediately after the WPF buffer.
My question: Is there any way to execute code just after the Viewport3D presents its contents? Or at least close to that moment?
Does not have to be a clean solution – I could also live with a dirty native hack …
I managed to create a method which gets called from RenderContent of the (internal) Viewport3DVisual class, but this is executed more often than the actual present to screen and probably not on the render thread.

A: Ok, I found the solution by myself. It is possible to add an event handler to the internal RenderComplete event of the internal MediaContext class using reflection:
Assembly oAssemblyPresentationCore = typeof( Visual ).Assembly;
Type oTypeMediaContext = oAssemblyPresentationCore.GetType( "System.Windows.Media.MediaContext" );
MethodInfo oMethodInfoGetMediaContextFromDispatcher = oTypeMediaContext.GetMethod( "From", BindingFlags.Static | BindingFlags.NonPublic );
object oMediaContext = oMethodInfoGetMediaContextFromDispatcher.Invoke( null, new object[] { oViewport3D.Dispatcher } );
EventInfo oEventInfoRenderComplete = oMediaContext.GetType().GetEvent( "RenderComplete", BindingFlags.NonPublic | BindingFlags.Instance );
oEventInfoRenderComplete.GetAddMethod( true ).Invoke( oMediaContext, new object[] { new EventHandler( EventHandlerRendered ) } );


text:
Q: I want to display the output as follows by writing sql query in Oracle 10g? In my schema i have the dept table data as follows
dept_id       dept_name
  10             IT
  20             EE
  30             EC
  40             OP

I want to get the output as follows and i dont want to display column headdings dept_id and dept_name
 IT         EE           EC          OP
 10         20           30          40

So, Please help me to get the result. This question asked by an Interviewer.

A: Oracle 10g doesn't have the PIVOT feature, so you'll need to use something like this:
SELECT
  MAX(CASE WHEN dept_name = 'IT' THEN dept_id END) AS IT,
  MAX(CASE WHEN dept_name = 'EE' THEN dept_id END) AS EE,
  MAX(CASE WHEN dept_name = 'EC' THEN dept_id END) AS EC,
  MAX(CASE WHEN dept_name = 'OP' THEN dept_id END) AS OP
FROM dept


text:
Q: Infinite rerendering with useEffect I'm trying to rerender a component once the state is changed, this how I do it:
const [items, setItems] = useState([]);

useEffect(() => {
    console.log("I am rerendering")
    const displayNotebook = async () => {
    const reponse = await axios({// URL etc...},
      });
      setItems(reponse.data); // add data to the list
    };

   displayNotebook()

  },[items]);

I pass the date in a map as so
const workspaceCard = items.map((msg) => (
<WorkspaceContent
  message={msg.content}
/>));

The problem is that the component is in a infinite rerendering, I could use an empty array but this not what I want, I am trying to rerender the component each time the state is updated.
I searched and found this answer Infinite loop in useEffect but does not help me

A: As Gaëtan already indicated, your logic has a loop: inside your effect you are setting items, but you are also indicating that the effect should re-run whenever items change. Hence the cycle. The fix is simple then, just remove the dependency on items, if you don't need/want to rerun the effect whenever they change:
useEffect(() => {
    // ...
  },[]);  // items removed


text:
Q: Copy-construct from reference Consider this code
class Foo {
private:
    Bar bar; //note: no reference

public:
   Foo(Bar& b) : bar(b) { }
};

Will Bar get copy-constructed?

A: That depends on the signatures of Bar's public constructors, either explicitly or implicitly defined.
To start with, the C++ standard allows for implicit conversion of references as long as the only difference in the underlying type is that the destination type is at least as cv-qualified than the source type, using the partial ordering defined in this table (C++11, §3.9.3/4):

no cv-qualifier < const
no cv-qualifier < volatile
no cv-qualifier < const volatile
const          < const volatile
volatile    < const volatile

So, taking that into account as well as §12.8/2:

A non-template constructor for class X is a copy constructor if its first parameter is of type X&, const X&, volatile X& or const volatile X&, and either there are no other parameters or else all other parameters have default arguments.

if Bar has a constructor with any of the following signatures:
Bar(Bar&);
Bar(Bar const&);
Bar(Bar volatile&);
Bar(Bar const volatile&);

then yes, b will be copy-constructed into Foo::bar.

EDIT: This was incorrect, I was thinking of operator= and the details of qualifying as a move-assignment operator.
Note that it's possible to have an eligible constructor that is not a copy constructor:
Bar(Bar);

This will work (read: compile), but it is not technically a copy constructor.

A: Yes your member variable bar will be copy constructed, that's one of the benefits of using an initializer list as opposed to assigning the value in the body of the constructor.
If the Bar class does not have an accessible copy constructor and the compiler can't generate a default one, the code will fail to compile.
When you pass a reference to a copy constructor, you should generally make it a const reference.


text:
Q: how to merge keys in dictionary outside of list? I'm trying to get dictionary with same keys and merge its values and if there is a duplicate leave only one value of duplicate.
data = {"test1":["data1", "data2"],
   "test1":["data3", "data4", "data2"],
   "test2":["1data", "2data"],
   "test2":["3data", "4data", "2data"]
   }

desired_result = {"test1":["data1", "data2", "data3", "data4"],
                 "test2":["1data", "2data", "3data", "4data"]
                 }

any ideas how to get result?

A: First you need create list of dict (because you can't have dictionary with same keys) then iterate over them and extend them to list with key of dict then use set for delete duplicated like below:
data = [{"test1":["data1", "data2"]},{"test1":["data3", "data4", "data2"]},{"test2":["1data", "2data"]},{"test2":["3data", "4data", "2data"]}]

from collections import defaultdict

rslt_out = defaultdict(list)
for dct in data:
    for k,v in dct.items():
        rslt_out[k].extend(v)

for k,v in rslt_out.items():
    rslt_out[k] = list(set((v)))

print(rslt_out)

output:
defaultdict(list,
            {'test1': ['data3', 'data4', 'data2', 'data1'],
             'test2': ['2data', '3data', '1data', '4data']})


text:
Q: eigenvalues and eigenvectors for a generalized Pauli matrix in spherical coordinates If we have $nz=\cosθ$, $nx=\sinθ\cosφ$ and $ny = \sinθ\sinφ$,
how we can compute the eigenvectors of the Linear Operator of the spin ?

A: I assume this is a homework problem, and you are asked to diagonalize your 2x2 matrix
$$
\hat{n}\cdot\vec{\sigma}=  \begin{pmatrix}
      \cos \theta&  e^{-i\phi}\sin \theta \\
    e^{i\phi}  \sin \theta &-\cos \theta
    \end{pmatrix}
$$
directly, for practice.
The eigenvalues are obviously 1 and -1, corresponding to eigenvectors, respectively, $(\cos (\theta/2),~ e^{i\phi} \sin (\theta /2))$ and     $( - e^{-i\phi }\sin (\theta /2),~ \cos (\theta /2))$ .
I should not spoil the fun of interpreting the answer by rotating from z to n, so getting the above matrix as $R^{-1} \sigma_z R$, and getting this answer indirectly, utilizing Wigner's d matrices, which I imagine you were invited to do...


text:
Q: Firebase project not showing in Google Analytics I have a firebase project that has Google Analytics enabled.

and when I click Manage, there is a link to Google Analytics.

But in Google Analytics it is not showing at all.


text:
Q: How to use css @keyframes and animation properly for dropdown I am having a problem implementing the @keyframes and animation for dropdown. I have implemented blink animation for my dropdown. But, when i open the dropdownlist and try to scroll by mousepress, the scrollbar is not properly working, it's not staying with my mousepress. Please, check the code snippet and run the code snippet to understand the problem. Thanks

@keyframes blink {
  50% {
    border-color: #fff;
  }
}

.blink {
  border: 3px solid #0061a0;
  font-weight: bolder;
  animation: blink 1s infinite;
  animation-iteration-count: infinite;
}
<select name="birthYear" class="blink">
  <option>YYYY</option>
  <option value="2022">2022</option>
  <option value="2021">2021</option>
  <option value="2020">2020</option>
  <option value="2019">2019</option>
  <option value="2018">2018</option>
  <option value="2017">2017</option>
  <option value="2016">2016</option>
  <option value="2015">2015</option>
  <option value="2014">2014</option>
  <option value="2013">2013</option>
  <option value="2012">2012</option>
  <option value="2011">2011</option>
  <option value="2010">2010</option>
  <option value="2009">2009</option>
  <option value="2008">2008</option>
  <option value="2007">2007</option>
  <option value="2006">2006</option>
  <option value="2005">2005</option>
  <option value="2004">2004</option>
  <option value="2003">2003</option>
  <option value="2002">2002</option>
  <option value="2001">2001</option>
  <option value="2000">2000</option>
  <option value="1999">1999</option>
  <option value="1998">1998</option>
  <option value="1997">1997</option>
  <option value="1996">1996</option>
  <option value="1995">1995</option>
  <option value="1994">1994</option>
  <option value="1993">1993</option>
  <option value="1992">1992</option>
</select>

A: You can animate a wrapper <div> element instead.

@keyframes blink {
  50% {
    border-color: #fff;
  }
}

.blink {
  border: 3px solid #0061a0;
  font-weight: bolder;
  animation: blink 1s infinite;
  animation-iteration-count: infinite;
}
<div class="blink" style="display: inline-block;">
<select name="birthYear"><option>YYYY</option><option value="2022">2022</option><option value="2021">2021</option><option value="2020">2020</option><option value="2019">2019</option><option value="2018">2018</option><option value="2017">2017</option><option value="2016">2016</option><option value="2015">2015</option><option value="2014">2014</option><option value="2013">2013</option><option value="2012">2012</option><option value="2011">2011</option><option value="2010">2010</option><option value="2009">2009</option><option value="2008">2008</option><option value="2007">2007</option><option value="2006">2006</option><option value="2005">2005</option><option value="2004">2004</option><option value="2003">2003</option><option value="2002">2002</option><option value="2001">2001</option><option value="2000">2000</option><option value="1999">1999</option><option value="1998">1998</option><option value="1997">1997</option><option value="1996">1996</option><option value="1995">1995</option><option value="1994">1994</option><option value="1993">1993</option><option value="1992">1992</option></select>
</div>

A: 0% is the beginning of the animation, and 100% is when the animation is complete.
For best browser support, you should always define both the 0% and the 100% selectors.
@keyframes blink {
  0%{
    border-color: #0061a0;
  }
  100% {
    border-color: #fff;
  }
}

.blink {
  border: 3px solid #0061a0;
  font-weight: bolder;
  animation: blink 1s infinite;
  animation-iteration-count: infinite;
}


text:
Q: Auto-forwarding Outlook invites as emails Long story short, my employer requires me to install some MDM software on my phone in order to access email, which I have no interest in doing.  However, I do rely heavily on my phone for meeting reminders, which I'm missing terribly.
I'm attempting to devise a workaround by which Outlook automatically forwards Meeting Invites (and Meeting updates!) to my personal mail from which I can add to my gmail calendar.  The functionality of accepting it or declining it isn't terribly important to me.
Now to my question: is there a way to detect an email as a meeting invite?  I think I've got the forwarding bit figured out.
Update: Tried with Julian's suggestion, result it failure.  Outlook obnoxiously sends a notification to the Meeting creator saying that I forward the mail on their behalf.  Doesn't look too good when it's to a personal address.

A: There is a condition in the Rules settings for "which is a meeting invite or update". You can use this to create a rule on incoming email and get it forwarded to your GMail account.

A: It appears you can choose to forward the invite as an attachment -- I'm hoping this avoids the obnoxious notification.  I just tried this in Outlook 2010, will test it out shortly.
When you create the rule, choose "forward it to people or public group as an attachment."
Potentially helpful link: http://www.send4help.net/automatically-forward-a-copy-of-meeting-invitations-outlook-2007-408


text:
Q: firebase info/connected onDataChange 1 minute false no response I have the following code called in onCreate to keep track of whether the user is connected to firebase/can connect to firebase:
    DatabaseReference connectedRef = FirebaseDatabase.getInstance().getReference(".info/connected");
    connectedRef.addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot snapshot) {
            connected = snapshot.getValue(Boolean.class);
        }
        @Override
        public void onCancelled(DatabaseError error) {
            connected = false; // not called in the observations below
        }
    });

Observed behavior:
A. When initialized:

*

*onDataChange is called with connected set to false

*onDataChange is called with connected set to true quickly thereafter (assuming had internet connection)

B. Before the 1 minute:

*

*Turning off wifi or data will cause connected set to false

*Turning on wifi or data will cause connected set to true

C. At 1 minute

*

*connected set to false via onDataChange

D. After 1 minute

*

*onDataChange is not called regardless of going on wifi/data

Expected behavior:
A'. Same as A
B'. Same as B
C'. Nothing
D'. Same as B.
I've seen other questions regarding losing authentication, but I haven't seen auth issues in my logs. Additionally the precise time of one minute seems very specific and was not seen in other similar question/answers.
Note that I'm using firebase 9.0.2.

A: Based on what I have observed on 9.0.2, the connection is closed after one minute when it is not needed.  To leave the connection open would needlessly drain the battery.
A connection is needed when:

*

*DatbaseReference.setValue() is executed.

*Query.addListenerForSingleValueEvent() is executed

*A ValueEventListener or ChildEventListener has been added and not removed

After a connection has been closed, one of the listed events will cause it to reopen.  For events 1 and 2, the connection will close again after one minute.  When a listener has been added (not for single value), the connection remains open until the listener is removed.


text:
Q: Recalculate the new weighted mean when merging two factors by group, and keep original data I'm working on a data frame that contains:

*

*counts per cluster (flow cytometry data)

*of several files

*and mean, max, min, total for lots of variables recorded by the machine.

In the case that I want to reduce the number of groups (pool similar clusters together) I would want to merge all the information in a file for group 'a' and 'b' by file
So far, following this SO Question I have already worked out the min, max, and total, but am stuck on how to get the following calculation working in this structure (mutate_at) using a custom function which would do:

(counts of 'a'  * mean of 'a'  + counts of 'b'  * mean of 'b') /
  sum(counts for 'a', counts of 'b' )

in order to recalculate the new mean for each of the mean_i columns, where "mean"  in the equation refers to 1 of the columns containing mean values I'm calling with vars(mean_cols)
The code so far:
library(dplyr)

set.seed(123)
df <- data.frame(ID = 1:20,
                 total_X = runif(20),
                 min_X = runif(20),
                 max_X = runif(20),
                 mean_X = runif(20),
                 total_Y = runif(20),
                 min_Y = runif(20),
                 max_Y = runif(20),
                 mean_Y = runif(20),
                 Counts = runif(20)*1000,
                 category = rep(letters[1:5], 4),
                 file = as.factor(sort(rep(1:4, 5))))

total_cols = names(df)[which(grepl('total', names(df)))]
min_cols = names(df)[which(grepl('min', names(df)))]
max_cols = names(df)[which(grepl('max', names(df)))]
mean_cols = names(df)[which(grepl('total', names(df)))]

recalmean <- function() { sum(Counts * vars)/sum(Counts)}
  #counts of 'a'  * mean of 'a'  + counts of 'b'  * mean of 'b'  / sum(counts for 'a', counts of 'b' )

x <- df %>% bind_rows(
  df %>%
    filter(category %in% c('a' , 'b')) %>%
    group_by(file) %>%
    mutate_at(vars(total_cols), sum) %>%
    mutate_at(vars(min_cols), min) %>%
    mutate_at(vars(max_cols), max) %>%
    # mutate_at(vars(mean_cols), recalmean) %>%  ## this line needs to do the custom weighed mean calculation
    mutate(category = paste0(category,collapse='')) %>%
    filter(row_number() == 1 & n() > 1)
) %>% mutate(ID = row_number())

A: got to admit it was challenging...you should reconsider the data structure
library(tidyverse)

set.seed(123)
df <- data.frame(ID = 1:20,
                 total_X = runif(20),
                 min_X = runif(20),
                 max_X = runif(20),
                 mean_X = runif(20),
                 total_Y = runif(20),
                 min_Y = runif(20),
                 max_Y = runif(20),
                 mean_Y = runif(20),
                 Counts = runif(20)*1000,
                 category = rep(letters[1:5], 4),
                 file = as.factor(sort(rep(1:4, 5))))

x <- df %>% bind_rows(
  gather(df,metric,value,-ID,-file,-category,-Counts) %>%
    mutate(group=str_extract(metric,"[A-Z]$"),metric = str_replace(metric,"_.$","")) %>%
    filter(category %in% c('a' , 'b')) %>%
    spread(metric,value) %>%
    group_by(file,group) %>%
    summarise(Counts = mean(Counts),
              category = paste0(category,collapse = ''),
              max = max(max),
              min = min(min),
              total = sum(total),
              mean = sum(Counts * mean)/sum(Counts)) %>%
    ungroup() %>%
    gather(metric,value,-file,-group,-category,-Counts) %>%
    mutate(metric = paste(metric,group,sep='_'),group=NULL) %>%
    spread(metric,value) %>%
    mutate(ID=0)
) %>% mutate(ID = row_number())


text:
Q: What is the correct usage/syntax for the c++17 alignas() specifier for dynamically allocated arrays of fundamental types? This must be a repeat question, but I have not found it after searching for 2 days ...
I'm using MSVC with /std:c17 /std:c++17 and trying to get alignas(64) to work with arrays of doubles. The syntax in the code below is the only one I have found that compiles, but it's not aligning ... typically, the array is unaligned about 75% of the time. I know there are many ways to do this with more complicated syntax, but isn't there a way that "just works" with alignas(), as it would for a structure or class?
double* AR;
int count=0, asize=10;
for (int i = 0; i < 1000; i++)
{
    AR = new double alignas(64)[asize];
    if (((uintptr_t)AR & 63) != 0) count++;
    //if (((uintptr_t)AR % 64) != 0) count++;
    delete[] AR;
}

A: While C++17 does have the means for operator new to be given an alignment for the memory it allocates, there is no mechanism in C++ to specify the alignment for memory allocated by a new expression outside of the alignment of the type being allocated. That is, if you perform a new T or new T[], the alignment of the allocated pointer will be alignof(T). C++17 added alignment-based operator new allocators, which allows them to support over-aligned types.
This is fine if you have control over T and can specify its alignment at definition time via alignas. But if you're using someone else's type or a fundamental type like double, you can't change the alignment of those types. So there's no way to directly use a new expression to allocate such memory.
You will have to use ::operator new directly to allocate sufficient memory at the desired alignment, and then use placement-new to actually create the objects there. Of course, placement-new on arrays has a number of issues.
I suspect this compiles only because alignas is considered an attribute and it is grammatically legal to shove an attribute before the [] in a new expression. It isn't intended to actually work, as there is no statement in the section on new expressions that allows it to get the alignment of the allocation from anything other than alignof(T).


text:
Q: Drools integration vs. traditional way I'm new to Drools. I read a lot of examples for using Drools in Java enterprise applications or Spring applications.I found that Drools supports integration with Spring and CDI by using annotations or application context in spring to create Kie objects like KBase, KSession, and KContainer. I can't get the advantage of using this integration methods. Other examples develop Spring applications but create these objects using the traditional way. like this example
What is the benefit of using Drools integration rather than the traditional way? Which way should I use? Does the injection of KSession implement any session management or pooling ?

A: There will be no striking Performance Improvement in Spring Drools Integration vs Traditional way.
But as with any Spring Framework Module Spring Drools Integration will provide a Layer of Abstraction and Flexibility for your configurations of Drools.
Furthermore it enable to keep everything Simple by creating the necessary Drools objects easily with minimum configuration and lets you focus on the Core Rule Implementation.


text:
Q: How can I count on listview item on click? In my code im creating persons and go with them into a list per button click.
From this list, It shows all created persons(items) in listview.
So I want to count for every click. Example:
Im Creating Person Max:
You can see max in listview now
When Im creating a second person
**Im want to count like this:
max count : 0
second person count : 0
Click on Max count++
max count : 1
second person count : 0
Below is the code:
listView.setOnItemClickListener{ adapterView, view, i, l ->
 Toast.makeText(this, "Item Selected " +personNamelist[i], Toast.LENGTH_LONG).show()
clickList.add(Person(personNamelist[i], 0))
                    clicks++


text:
Q: Unexpected token '?' in Rest I'm trying to add slash commands to my discord bot using Discord.js and Rest but I keep getting an unexpected token somewhere in rest. Could anybody help me?
When I run:
const { SlashCommandBuilder, Routes } = require('discord.js');
const { REST } = require('@discordjs/rest');
var clientId = //myClientId
var guildId = //myGuildId

const commands = [
    new SlashCommandBuilder().setName('ping').setDescription('Replies with pong!')
]
    commands.map(command => command.toJSON());

const rest = new REST({ version: '10' }).setToken(process.env.TOKEN);

(async () => {
    try {
        console.log('Started refreshing application (/) commands.');

        await rest.put(
        Routes.applicationCommands(clientId),
        { body: commands },
    );

        console.log('Successfully reloaded application (/) commands.');
    } catch (error) {
        console.error(error);
    }
})();

I Get:
/home/runner/TinkerTank/node_modules/@discordjs/rest/dist/lib/CDN.cjs:53
      extension: extension ?? "png"
                            ^

SyntaxError: Unexpected token '?'
    at wrapSafe (internal/modules/cjs/loader.js:915:16)
    at Module._compile (internal/modules/cjs/loader.js:963:27)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:1027:10)
    at Module.load (internal/modules/cjs/loader.js:863:32)
    at Function.Module._load (internal/modules/cjs/loader.js:708:14)
    at Module.require (internal/modules/cjs/loader.js:887:19)
    at require (internal/modules/cjs/helpers.js:74:18)
    at Object.<anonymous> (/home/runner/TinkerTank/node_modules/@discordjs/rest/dist/index.cjs:5:13)
    at Module._compile (internal/modules/cjs/loader.js:999:30)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:1027:10)

If somebody could help me out that would be great.

A: maby this will help you. npm install node@16.13.1 --save-dev --save-exact
For me, this solved the problem.
I found this here


text: Q: custom resources in chef I'm new to chef and ruby programming. I'm sure custom resources is a kind function to prevent repetition of work in the code.  How should I use custom resources in a recipe that has key value pair property for various resources?


text:
Q: Datatype  is not supported for sorting operation Доброго времени суток.
Был запрос:
SELECT
  t1.PV_FISH_ID,
  t1.PV_FISH_NAME,
  t1.PV_ACOUNT,
  min(t1.PV_MIN_WEIGHT),
  t1.PV_ATROF,
  (SELECT SUM(PV_FISH_COUNT) FROM PlanView WHERE PV_FISH_ID = t1.PV_FISH_ID AND PV_ATROF>=PV_MIN_WEIGHT),
  max(t1.PV_MAX_WEIGHT),
  max(t1.PV_CREDIT_WEIGHT) AS CREDIT
FROM PlanView t1
LEFT JOIN PlanView t2 ON t1.PV_FISH_ID=t2.PV_FISH_ID
WHERE t2.PV_MIN_WEIGHT < t2.PV_ATROF AND t2.PV_MAX_WEIGHT > t2.PV_ATROF AND t2.PV_ATROF>=t2.PV_MIN_WEIGHT
AND
t2.PV_UD=1
AND
t2.PV_N=1
AND t2.PV_THROUGH=-1
GROUP BY t1.PV_FISH_ID, t1.PV_FISH_NAME, t1.PV_ACOUNT, t1.PV_ATROF;

И пока PlanView был таблицей всё работало, но переделал я его на View и получил эту ошибку, как от неё избавиться?
И, если не сложно, помогите оптимизировать этот запрос, сдаётся мне он очень не оптимальный.
Код ViewPlan:
CREATE OR ALTER VIEW PLANVIEW(
    PV_ID,
    PV_FISH_ID,
    PV_FISH_NAME,
    PV_MIN_WEIGHT,
    PV_MAX_WEIGHT,
    PV_ATROF,
    PV_ACOUNT,
    PV_PRICE,
    PV_FISH_COUNT,
    PV_CREDIT_WEIGHT,
    PV_CREDIT,
    PV_OPYT,
    PV_THROUGH,
    PV_N,
    PV_U,
    PV_D,
    PV_V,
    PV_UD,
    PV_DO,
    PV_SP)
AS
SELECT
  NF_ID, FL_FISH_ID,
  NF_NAME, PF_MIN_WEIGHT, PF_MAX_WEIGHT,
  AF_WTROF,
  AF_COUNT, PF_PRICE,
  FL_FISH_COUNT, PF_CREDIT_WEIGHT, PF_CREDIT,
  AF_OPYT, PF_THROUGH,
  (CASE WHEN EXISTS(SELECT 1 FROM FishDaysTime WHERE FD_FISH_ID=FL_FISH_ID AND FD_DTIME_ID=0) THEN 1 ELSE 0 END),
  (CASE WHEN EXISTS(SELECT 1 FROM FishDaysTime WHERE FD_FISH_ID=FL_FISH_ID AND FD_DTIME_ID=1) THEN 1 ELSE 0 END),
  (CASE WHEN EXISTS(SELECT 1 FROM FishDaysTime WHERE FD_FISH_ID=FL_FISH_ID AND FD_DTIME_ID=2) THEN 1 ELSE 0 END),
  (CASE WHEN EXISTS(SELECT 1 FROM FishDaysTime WHERE FD_FISH_ID=FL_FISH_ID AND FD_DTIME_ID=3) THEN 1 ELSE 0 END),
  (CASE WHEN EXISTS(SELECT 1 FROM RodTable WHERE RT_ID=FL_FISH_ID) THEN 1 ELSE 0 END),
  (CASE WHEN EXISTS(SELECT 1 FROM DonkeyTable WHERE DOT_FISH_ID=FL_FISH_ID) THEN 1 ELSE 0 END),
  (CASE WHEN EXISTS(SELECT 1 FROM SpinTable WHERE ST_ID=FL_FISH_ID) THEN 1 ELSE 0 END)
FROM FishOnLocation, ParamsFish, NamesFish, AkkFishTable
WHERE FL_LOC_ID=76
AND PF_FISH_INDEX=NF_ID
AND FL_FISH_ID=PF_ID
AND AF_ID=NF_ID

A: По воводу оптимизации. Правда не запроса, а view
Предалагаю заменить штуки вида (CASE WHEN EXISTS(SELECT 1 FROM FishDaysTime WHERE FD_FISH_ID=FL_FISH_ID AND FD_DTIME_ID=0) THEN 1 ELSE 0 END),
на LEFT JOIN (SELECT 1 AS THE_ONE, FD_FISH_ID, FD_DTIME_ID FROM FishDaysTime) FDT0 ON (FD_FISH_ID=FL_FISH_ID AND FD_DTIME_ID=0) + COALESCE(FDT0.THE_ONE, 0)
по нижеследующей схеме и посмотреть что будет. По крайней мере выгладит красивее, на мой взгляд.
И да, такаой способ работает, если подзапрос вернёт не более одной записи. Если больше, то надо поставить DISTINCT либо в подзапросы, либо в запрос.
CREATE OR ALTER VIEW PLANVIEW(
    PV_ID,
    PV_FISH_ID,
    PV_FISH_NAME,
    PV_MIN_WEIGHT,
    PV_MAX_WEIGHT,
    PV_ATROF,
    PV_ACOUNT,
    PV_PRICE,
    PV_FISH_COUNT,
    PV_CREDIT_WEIGHT,
    PV_CREDIT,
    PV_OPYT,
    PV_THROUGH,
    PV_N,
    PV_U,
    PV_D,
    PV_V,
    PV_UD,
    PV_DO,
    PV_SP)
AS
SELECT
  NF_ID, FL_FISH_ID,
  NF_NAME, PF_MIN_WEIGHT, PF_MAX_WEIGHT,
  AF_WTROF,
  AF_COUNT, PF_PRICE,
  FL_FISH_COUNT, PF_CREDIT_WEIGHT, PF_CREDIT,
  AF_OPYT, PF_THROUGH,
  COALESCE(FDT0.THE_ONE, 0),
  COALESCE(FDT1.THE_ONE, 0),
  ...
FROM FishOnLocation, ParamsFish, NamesFish, AkkFishTable
LEFT JOIN (SELECT 1 AS THE_ONE, FD_FISH_ID, FD_DTIME_ID FROM FishDaysTime) FDT0 ON (FD_FISH_ID=FL_FISH_ID AND FD_DTIME_ID=0)
LEFT JOIN (SELECT 1 AS THE_ONE, FD_FISH_ID, FD_DTIME_ID FROM FishDaysTime) FDT1 ON (FD_FISH_ID=FL_FISH_ID AND FD_DTIME_ID=1)
...
WHERE FL_LOC_ID=76
AND PF_FISH_INDEX=NF_ID
AND FL_FISH_ID=PF_ID
AND AF_ID=NF_ID

Если подзапрос вернёт строку, то THE_ONE будет == 1
Если не вернёт ни шиша, то THE_ONE == NULL
COALECSE(...) Возвращает первый параметр, который != NULL.
В итоге получается 1, если есть строка в подзапрсе и 0, если её нет.
А на счёт dtype_unknown, может повыполнять все запросы, подзапросы, чтобы увидеть в каком из них получится колонка с непонятным типом? Консоль или ibexpert показывают тип колонки?

A: Дайте имя столбцам min(t1.PV_MIN_WEIGHT) и max(t1.PV_MAX_WEIGHT).


text:
Q: Base aritmetic in bash I have a question. I wanted to count a number of parameters in a expression for a range.
Existing for now code part:
if [ -n "$@" ]; then
    name=$1

    # count=$(( $#-1 ))

    for a in [2..${count}]; do
        # some code
    done
fi

My questtion is, if there would be any difference  in between this two ones:
$#-1

and
1-$#

?
Thanks

A: It seems like you want to iterate over the arguments starting from $2; in bash you can do it like this
#!/bin/bash

for a in "${@:2}"
do
    echo "$a"
done


text:
Q: Mapping Json in JDBI RowMapper I'm using JDBI v 3.11.1 with Amazon Aurora (and Jackson). In our tables, we use JSonB a lot and I feel like the mapping I'm doing is a bit too complicated/slow.
Currently I'm having a DAO doing something like this:
@RegisterRowMapper(ContactMapper.class)
  public interface ContactsDao {

    @SqlQuery("SELECT * FROM contacts")
    List<Contact> listContacts();
}

while the mapper does something like this: (stripped down to what is needed for this question)
public class ContactMapper implements RowMapper<Contact> {

  private final ObjectMapper objectMapper = new ObjectMapper();

  @Override
  public Contact map(ResultSet r, StatementContext ctx) throws SQLException {

    Address address = r.getString("address") == null ? null : (Address) mapJson(r.getString("address"), Address.class);

    return new Contact(
        r.getString("id"),
        address
    );
  }

  private Object mapJson(String json, Class clazz) {
    if (Strings.isNullOrEmpty(json)) {
      return null;
    }
    try {
      return objectMapper.readValue(json, clazz);
    } catch (IOException e) {
      LOGGER.error("Could not map Address.", e);
      return null;
    }
  }
}

Address is stored within Aurora as a JsonB field. I've read something about a JsonMapper Annotation but since the jdbi documentation is quite unclear, I'm not sure if this is the right thing.
Is the way how I map my results the "standard" way of doing this or is there a better/more efficient way?
Thanks

A: there is a json plugin, backed by jackson or guava. see http://jdbi.org/#jdbi3-json
if installed, on nested properties like in your case, everything should be mapped correctly as long as the database declares the datatype as "json"/"jsonb" (not string or anything).
furthermore the annotation @Json on your sql objects query method should suffice, if not nested (e.g. Contact is a json as a whole)

A: I'll add to what @winson has recommended. jdbi3-json is a great plugin for this but it doesn't provide anything for RowMappers as far as I could see.
I found this workaround which isn't really that cleaner but it would mean the same ObjectMapper would be in use if you use the other features of jdbi3-json.
public Contact map(ResultSet r, StatementContext ctx) throws SQLException {
    var addressMapper = (ColumnMapper<Address>) new JsonColumnMapperFactory()
        .build(Address.class, ctx.getConfig()).orElseThrow();
    return new Contact(
        r.getString("id"),
        addressMapper.map("address")
    );
}


text:
Q: Order of Children of a Node I'm currently testing the viability of using Gentics Mesh CMS just in a minor role for to populate a news feed.  The general idea being that I have a news folder item, with various news items under it currently.
What is determining the order of children?  When I grab the data of said news node, the order of the children just seems haphazard at best.  I have 3 items in there for testing.
Yesterday I was getting them back in the order 3-1-2.  Now they are 1-3-2.
Neither of these is a useful order, as I would like 3-2-1.  So how can I force an order?  Either in how it's storing things, or in retrieval?

A: You can force an order if you are using Elasticsearch (enabled by default).
POST this example to https://demo.getmesh.io/api/v1/search/nodes
{
    "query": {
        "term": {
            "parentNode.uuid": "21203632520b4d19a03632520b2d19c1"
        }
    },
    "sort": {
        "created": "asc"
    }
}

This will get the first 25 nodes which are in the folder with UUID 21203632520b4d19a03632520b2d19c1, sorted by their creation date.

A: The elements are currently returned in natural order in which they are returned by the graph database. It is possible that new elements are inserted in "free" slots and thus the order changes. I believe the behavior you observed is caused by not applying any sorting. I created an issue for this bug.
https://github.com/gentics/mesh/issues/327


text:
Q: spring-cloud-starter-netflix-eureka-server:jar:unknown was not found These are the two pom files of parent and discovery service sitting inside parent .
   <properties>
        <maven.compiler.source>17</maven.compiler.source>
        <maven.compiler.target>17</maven.compiler.target>
        <spring-cloud-version>2021.0.2</spring-cloud-version>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    </properties>

        <modules>
        <module>product-service</module>
        <module>order-service</module>
        <module>inventory-service</module>
        <module>discovery-service</module>
    </modules>

    <dependencyManagement>
        <dependencies>
            <dependency>
                <groupId>org.testcontainers</groupId>
                <artifactId>testcontainers-bom</artifactId>
                <version>1.17.6</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
            <dependency>
                <groupId>org.springframework.cloud</groupId>
                <artifactId>spring-cloud-dependencies</artifactId>
                <version>${spring-cloud.version}</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
        </dependencies>
    </dependencyManagement>

and discovery service pom
    <dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-autoconfigure</artifactId>
    </dependency>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-netflix-eureka-server</artifactId>
        </dependency>

</dependencies>

I am getting these errors .
**Non-resolvable import POM: org.springframework.cloud:spring-cloud-dependencies:pom:${spring-cloud.version} was not found in https://repo.maven.apache.org/maven2 during a previous attempt.
Another error is
org.springframework.cloud:spring-cloud-starter-netflix-eureka-server:jar:unknown was not found in **https://repo.maven.apache.org/maven2 during a previous attempt.
I tried different approaches such as changing this line to
<version>${spring-cloud.version}</version>

to 2021.0.2
but all this didn't help .