text:
Q: Constant power outages, wasting time to determine the last executed command in my .sh script. What command to use to record progress? (I found a perfect solution by using Google Forms and a simple curl command, I wrote it as an answer if anyone ever needs it)
I execute a long .sh script with thousands of commands and once a power outage occurs, I need a lot of time to determine which was the last executed command so I can resume working.
I need a creative solution first regarding where the log would be the best to be stored (locally, or on the net, google spreadsheet maybe), and second - a command that I will place on strategic lines in the script and whose sole purpose is to create a descriptive output in the log i.e. if I see 1-SVK in the log, I will be able to resume working within a minute.
So what is the best place to store such a log (non-sensitive data) for a start ? And what command should I use ?
Only the output of the most recent execution of that command should be logged, I will modify the command properly and place it on each strategic line in the script so it will provide a correct output in the log (ex: 1-SVK, 2-SVK).
The code in the bash script should look like this:
[command that will print 1-SVK somewhere]
curl command 1
curl command 2
curl command 3
[command that will print 2-SVK somewhere]
curl command 4
curl command 5
curl command 6
...

Thank you in advance for your valuable advice

A: There are many ways to solve this problem, and the best solution depends on the specific details of the situation. However, some general advice would be to use a command like 'tee' to send the output of the script to both stdout and a log file. This way, you will have a record of the script's output even if the power goes out. Another option would be to use a tool like 'screen' or 'tmux' to keep the script running in the background even if the terminal is closed. This way, you can reconnect to the script and see the last few lines of output even if the power goes out.

A: Here is one perfect solution I just found, I am more than satisfied with this, I tested it and works great.
https://johnmu.com/using-curl-to-add-rows-to-google/
Leaving my question alive in case it would help someone in the future.
curl 'https://docs.google.com/forms/u/0/d/e/[ID_OF_YOUR_FORM]/formResponse' --data 'entry.[NUMERICAL_ID_OF_THE_ENTRY]=[THE_TEXT_YOU_WANT_TO_SEE_AS_AN_ANSWER_IN_THE_FORM]' --silent >/dev/null


text:
Q: Jquery refresh div block one time to show php session How could I refresh div with id which is contain PHP session?
my JQ ajax call:
$('#btn_1').click(function(){
    var parameters = $('#booking_form').serialize();

    $.ajax({
        url: baseurl + 'site/process',
        type: 'POST',
        data: parameters,
        dataType: 'json',
        success: function(output_str){
            if(output_str == "false"){
                $('#result_msg').html("please select one");

            }else{
                $('#result').html(output_str);
                $('#loaddiv').load();

            }
        }
    });
});

here is where I wanna to reload after ajax callback:

<?php echo $selected; ?>

<?php echo $sum_charges; ?>

$selected and $sum_charges is a php session that is stored during the process, the session would only show up in page when I refresh it manually, how could I make the session show immediately when the result callback to page?
Thanks!!
Edit:
I using codeigniter (still new in CI) in my process, here is part of my controller for this process:
public function process(){
    $confTypes = $this->input->post('cType');
    $user_email = $this->input->post('user_email');
    $output_str = NULL;
    $conf_charge_total = 0;

    if(!empty($confTypes)){

        foreach($confTypes as $confType){
            $explode_value = explode(",", $confType);

            $conf_type = $explode_value[0];
            $conf_charge = $explode_value[1];

            $conf_charge_total += $conf_charge; //sum up checked values

            $output_str .= $conf_type.":".$conf_charge.",";
            /*$output_str = array(
                    'selected' => $conf_type.','.$conf_charge,
                    'email' => $user_email,
                    'sum' => $conf_charge_total,
                    'flag' => 'true'
                );*/
            $this->session->set_userdata('selected', $output_str);

        }

        $output_str .= $conf_charge_total;

        $this->session->set_userdata('sum_charges', $conf_charge_total);

    }else{
        $output_str = "false";
    }

    echo json_encode($output_str);
}

A: if your js script is in the same page you can do..
success: function(output_str){
        if(output_str == "false"){
            $('#result_msg').html("please select one");

        }else{
            $('#result').html(output_str);
            var divContent="
<?php echo $selected; ?>

<?php echo $sum_charges; ?>
"; //this will echo the latest session variable...
              $('#loaddiv').html(divContent);

        }
    }

updated
send your session variable as json
PHP
 echo json_encode(array('selected'=>$selected,'sum_charges'=>$sum_charges,'output_str'=>'yourStr'));

JQUERY
success: function(output_str){
        if(output_str == "false"){
            $('#result_msg').html("please select one");

        }else{
            $('#result').html(output_str.output_str);
            var dinContent="
"+output_str.selected+"

"+output_str.sum_charges+"
"; //this will echo the latest session variable...
              $('#loaddiv').html(dinContent);

        }
    }

A: The ajax calling page returns json as you used dataType: 'json', then the called page should return a json formatted string like
echo json_encode(array("selected"=>"abc","sum_charges"=>123));
In your ajax function change the success function like:
success: function(output_str){
    if(output_str == "false"){
        $('#result_msg').html("please select one");

    }else{
        $('#result').html(output_str);
        var str="
"+output_str.selected+"

"+output_str.sum_charges+"
";
        $('#loaddiv').html(str);
    }
}

redpajama_set_name: RedPajamaStackExchange


text:
Q: Implementing timer using select I am planning to write a small timer library in C using timerfd_create.
The basic user of this library will have two threads

*

*application thread

*Timer thread

There will be a queue between these two threads so that whenever the application wants to start a timer, it will push a message into the queue which the timer thread will then read and create an FD for it and put it in select.
The problem with the above approach is that the timer thread being a single thread would be blocked in the select system call and would not know if a message has been posted in his receive queue to start a timer.
One way around this is to let the select timeout every "tick" and then check for messages in the queue. Is their a better way to do this?
I was also thinking of raising an Interrupt every time the application puts a message in the select queue to interrupt the select. Does that work well with Multi-threaded applications?
Platform : Unix

A: If you insist on having multiple threads post timers to a dedicated timer thread sitting in select(2), then why not use eventfd(2) or just an old-good self-pipe trick to signal that new timers are available. Include the event file descriptor to the pollable set, wait on all of them.

A: Which platform(s) are you wanting to target?  Under Windows, for instance, there are much better ways to handle this without using select(), such as PostThreadMessage() and WaitMessage().

A: If you are using timerfd's then there is no need for a dedicated timer thread, just write the application around an event loop using select, poll, or epoll, etc.


text:
Q: jQuery - Checking an input box against another input box in a PHP while loop I have come about quite a problem while programming an order submitting page, the aim of the page is to submit a dispute for an order - providing two fields are filled in, but only if one field is less than another one.
Basically, one is a drop down and the other is a disputes box, the queries are as follows:
If DisputesTextBox = "" and a drop down box = "Please Select..."
Everything is fine - submit button enabled
If DisputesTextBox != "" and dropdown box = "Please select..."
Error ( and vice versa, so if disputes is populated but dropwn = please select...) - submit button disabled
If DisputesTextox != "" and dropdown box = "Other"
Everything is fine - submit button enabled
If DisputesTextBox > shippedbox
Error - submit button disabled

Item ID	Description	Dispute Quantity	Shipped Quantity	Ordered Quantity	Reason

                    <?php
                        $data = mysql_query("SELECT * FROM `artran09` WHERE `invno` = '$invoiceno'") or die(mysql_error());
                        echo "";
                        $i = -1;
                        echo "<form action=\"submitdispute.php?invno=".$invoiceno."&ordate=".$placed."\" method=\"POST\" onsubmit=\"return confirm('Are you sure you are ready to dispute your order?');\">";

                            while ($info = mysql_fetch_array($data)) {
                                $i += 1;
                                echo "
";
                                echo "".$info['item']."	";
                                echo "".$info['descrip']."	";

                                echo "<input type=\"text\" input name=".$i." onKeyPress=\"return numbersonly(this, event)\"  maxLength=\"3\">	";

                                echo "<input type=\"text\" value=".$info['qtyshp']." onKeyPress=\"return numbersonly(this, event)\" maxLength=\"3\" disabled=\"disabled\">	";

                                echo "<input type=\"text\" value=".$info['qtyord']." onKeyPress=\"return numbersonly(this, event)\" maxLength=\"3\" disabled=\"disabled\">	";

                                echo "<select name = \"reason$i\">";
                                echo "<option>Please Select...</option>";
                                echo "<option>Short/Not received</option>";
                                echo "<option>Damaged Goods</option>";
                                echo "<option>Product Not Ordered</option>";
                                echo "</select>	";

                                echo "
";
                            }

                    ?>

<input type = "submit" value = "Dispute" name ="Submit">
    </form>

Thanks, hope anyone can help!
Edited for Wolf/anyone who can help - what's up with this code here:
-- code i edited --
function validateSubmit(){

   // this will loop through each row in table
   // Make sure to include jquery.js
   $('tr').each( function() {
      // Find first input
      var input1 = $(this).find('input').eq(0);
      var qty1 = input1.val();
      // Find Second input
      var input2 = $(this).find('input').eq(1);
      var qty2 = input2.val();
      // Find third input
      var input3 = $(this).find('input').eq(2);
      var qty3 = input3.val();
      // Find select box
      var selectBx = $(this).find('select');
      var selectVal = selectBx.val();
      // Add your validation code here for the inputs and select
      // Return true if all validations are correct
      // Else return false
        if(qty1 = "" && selectVal = "Please Select...") {
            return true;
            alert("You have an error somewhere, please check over your quantites.");
            break;
        }
        if (qty1 > qty2) {
            return false;
            alert("You have an error somewhere, please check over your quantites.");
            break;
        }
   });

}

A:         return true;
        alert("You have an error somewhere, please check over your quantites.");
        break;

If you call return, execution of the current function is halted immediately and the value is returned. This means that nothing after a return statement is executed. The alert() will not run, because the functions ends with the return true.


text:
Q: How to open Notepad text file and keep on top of all other windows until i close it in VBScript? I would like to create a vbscript to open a notepad text file I saved and keep this notepad text file on top of all other windows either until i minimise it or close it.
I want to create a reminder in tasks then so it pops up every 30 minutes or so and reminds me but so when i browse it does not go in the background.
Greatly appreciate any help.
Dim oShell
Set oShell = WScript.CreateObject ("WScript.Shell")
oShell.run "notepad.exe C:\Users\***USER***\AppData\Roaming\Microsoft\Windows\Start Menu\Programs\Startup\TODO.txt", 1
Set oShell = Nothing

A: I made for you an example to create a schedule task to be executed each 30 minutes to open Notepad Maximized :

Option Explicit
Dim Title,fso,Ws,FilePath,TaskName,Repeat_Task,Command
Title = "Create Schedule Task"
Set fso = CreateObject("Scripting.FileSystemObject")
FilePath = "C:\Users\***USER***\AppData\Roaming\Microsoft\Windows\Start Menu\Programs\Startup\TODO.txt"
If Not fso.FileExists(FilePath) Then
    MsgBox "File : "& chr(34) & FilePath & chr(34) & vbcrlf & vbcrlf &_
    "Does not exists ! Please check it ," & vbcrlf &_
    "before proceeding with this vbscript !",vbExclamation,Title
    Wscript.Quit(1)
End If
TaskName = "Open_Notepad"
Repeat_Task = 30
Call Create_Schedule_Task(Repeat_Task,TaskName,WScript.ScriptFullName)
Command = "CMD /C Start /MAX Notepad "& FilePath &""
Set Ws = CreateObject("Wscript.Shell")
Ws.run Command,0,True
'--------------------------------------------------------------
Sub Create_Schedule_Task(Repeat_Task,TaskName,ScriptFilePath)
Dim Task,Result
Task = "CMD /C Schtasks /Create /SC DAILY /ST 08:00 /F /RI "&_
Repeat_Task &" /DU 24:00 /TN "& TaskName &" /TR "& ScriptFilePath &""
Set Ws = CreateObject("Wscript.Shell")
Result = Ws.run(Task,0,True)
End Sub
'---------------------------------------------------------------

Bonus : EDIT on 17/08/2020 @08:50 : This is a Hybrid code Batch and Powershell that help us to show All No Microsoft Scheduled Tasks.
Show_No-Microsoft_Tasks.bat

<# : Batch portion
@rem # The previous line does nothing in Batch, but begins a multiline comment block
@rem # in PowerShell.  This allows a single script to be executed by both interpreters.
@echo off
Title Get Schedule Tasks with a Hybrid code Batch and Powershell Script by Hackoo 2020
echo(
rem # This a Powershell command executes the hybrid portion at the bottom of this script
rem @for /f "delims=" %%I in ('powershell -noprofile "iex (${%~f0}|out-string)"') do echo %%I
>"%~dpn0.txt"  (
    @for /f "delims=" %%I in ('powershell -noprofile "iex (${%~f0}|out-string)"') do echo %%I
)
REM TimeOut /T 3 /NoBreak>nul
If Exist "%~dpn0.txt" Start "" "%~dpn0.txt" & exit /b
rem # End multi-line PowerShell comment block.  Begin PowerShell scripting.
: end Batch / begin PowerShell hybrid code #>
Function getTasks($path) {
    $out = @()
    # Get root tasks
    $schedule.GetFolder($path).GetTasks(0) | % {
        $xml = [xml]$_.xml
        $out += New-Object psobject -Property @{
            "Name" = $_.Name
            "Path" = $_.Path
            "LastRunTime" = $_.LastRunTime
            "NextRunTime" = $_.NextRunTime
            "Actions" = ($xml.Task.Actions.Exec | % { "$($_.Command) $($_.Arguments)" }) -join "`n"
        }
    }
    # Get tasks from subfolders
    $schedule.GetFolder($path).GetFolders(0) | % {
        $out += getTasks($_.Path)
    }
    #Output
    $out
}
$tasks = @()
$schedule = New-Object -ComObject "Schedule.Service"
$schedule.Connect()
# Start inventory
$tasks += getTasks("\")
# Close com
[System.Runtime.Interopservices.Marshal]::ReleaseComObject($schedule) | Out-Null
Remove-Variable schedule

# To show All No Microsoft Scheduled Tasks
$tasks | ? { $_.Path -notmatch "Micro*" }
Read-Host 'Type any key to continue'
$tasks | ? { $_.Path -notmatch "Micro*" } | Out-GridView
Read-Host 'Type any key to continue'

<#
# Output all tasks
#$tasks | Out-GridView
#Read-Host 'Type any key to continue'
# To show only tasks with those extensions in their TaskPath
#$tasks | ? { $_.Actions -match "(\.vbs|\.vbe|\.cmd|\.bat|\.hta)" } | Out-GridView
#Read-Host 'Type any key to continue'
#>


text:
Q: bring Jinternal frame infront of everything in this code when the new button is clicked, the Jinternalframe goes behind the button, even if i add anything else like, jlabel, jtextfield, etc, the internalframe opens behind everything. i tried the tofront() and movetofront() functions, but it doesnt seem to work. plz help, thanks.
code:
    import java.awt.BorderLayout;
import java.awt.CardLayout;
import javax.swing.JFrame;
import javax.swing.JButton;
import java.awt.Color;
import java.awt.FlowLayout;
import java.awt.GridBagLayout;
import java.awt.GridLayout;
import javax.swing.*;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;

public class Messages2 extends JFrame {

    JFrame frame;
    JButton button1;

    public static void main(String[] args) {
        Messages2 window = new Messages2();
        window.frame.setVisible(true);
    }

    public Messages2() {

        frame = new JFrame();
        frame.getContentPane().setBackground(Color.WHITE);
        frame.setBounds(100, 100, 220, 220);
        frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
        //frame.getContentPane().setLayout(new FlowLayout());

        JButton btnNew = new JButton("New Message");
        btnNew.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent arg0) {
                JDesktopPane desktopPane = new JDesktopPane();
                JInternalFrame intFrame = new JInternalFrame(
                        "JInternalFrame demo");

                intFrame.setMaximizable(true);
                intFrame.setIconifiable(true);
                intFrame.setResizable(true);
                intFrame.setClosable(true);
                intFrame.setDefaultCloseOperation(JInternalFrame.DISPOSE_ON_CLOSE);

                intFrame.setSize(320, 240);
                // intFrame.pack();
                intFrame.setVisible(true);

                desktopPane.add(intFrame);

                frame.add(desktopPane, BorderLayout.CENTER);
            }

        });
        btnNew.setBounds(1, 35, 145, 31);
        frame.getContentPane().add(btnNew);
    }
}

A:
when the new button is clicked, the Jinternalframe goes behind the button, even if i add anything else like, jlabel, jtextfield, etc,

Based on the code you posted in you last question (before you deleted it), you are attempting to add all your components directly to the frame. Swing paints components in the reverse order that a component is added. So since the internal frame is added last it is painted first and then all the other components are painted over top of it.
This is not the way you should be working with a JInternalFrame. You need to separate the JDesktopPane/JInternalFrames from your other components and work with each separately.
Read the section from the Swing tutorial on How to Use Internal Frames for basic information and examples.

*

*the internal frame is added to a JDesktopPane which is added to the frame.

*Don't use a null layout for your other components. Swing was designed to be used with layout managers. These components should be added to a panel and then the panel added to the frame.

The panel and the desktop pane must be added to different areas of the frame. For example:
frame.add(panel, BorderLayout.NORTH);
frame.add(desktopPane, BorderLayout.CENTER);

A: You're not using JInternalFrame correctly. It should only be placed within a JDesktopPane, something you're not doing and that I suggest that you start doing. Please check the appropriate tutorial on this.
Your button and your JInternalFrame now fill the field since you're using the JFrame's default BorderLayout. Suggestion:

*

*First and foremost, explain fully just what exact effect/user experience you're trying to achieve. Are you sure that a JInternalFrame is your best choice here?

*Learn about and use the layout managers to their best advantage.

*If you're going to use a JInternalFrame, then while it's OK to add the JInternalFrame in your ActionListener, you're usually going to want to add the JDesktopPane to the GUI on GUI creation, not in the ActionListener.


text:
Q: Getting an error Argument type 'Uint8List' can't be assigned to the parameter type 'File' I was trying to upload my image in firebase storage and got the error The argument type 'Uint8List' can't be assigned to the parameter type 'File'. I am a beginner. Here is my code, please help me resolving this issue.
Future<String> uploadImageToStorage(
      Uint8List image, String productUid) async {
    Reference storageRef = storage.ref().child('products').child(productUid);
    UploadTask uploadFile = storageRef.putFile(image);
    TaskSnapshot taskSnapshot = await uploadFile;
    Future<String> imageUrl = taskSnapshot.ref.getDownloadURL();

    return imageUrl;
  }

A: Change the putFile() to putData() and pass the image. Here is an updated code, let me know if this works for you.
Future<String> uploadImageToStorage(
      Uint8List image, String productUid) async {
    Reference storageRef = storage.ref().child('products').child(productUid);
    UploadTask uploadFile = storageRef.putData(image);
    TaskSnapshot taskSnapshot = await uploadFile;
    Future<String> imageUrl = taskSnapshot.ref.getDownloadURL();

    return imageUrl;
  }


text:
Q: Cannot convert value of type '(Any) -> ()' to expected argument type '(_) -> _' Installing PromiseKit (6.2.1). Swift4.0.
import UIKit
import PromiseKit

class ViewController: UIViewController {
    func onFulfilled() -> (String) -> Promise<String> {
        return { result in
            return Promise<String> { seal in
                print(result)
                DispatchQueue.main.asyncAfter(deadline: .now() + .seconds(1), execute: {
                    seal.fulfill("Hello")
                })
            }
        }
    }

    override func viewDidLoad() {
        super.viewDidLoad()

        Promise.value("first")
            .then(onFulfilled())
            .then(onFulfilled())
            .then(onFulfilled())
            .then { result in print(result) } // Cannot convert value of type '(Any) -> ()' to expected argument type '(_) -> _'
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
    }
}

Error

Cannot convert value of type '(Any) -> ()' to expected argument type '(_) -> _'

How to Fix
How to fix the .then { result in print(result) }?

A: replace then with done.
_ = Promise.value("first")
            .then(onFulfilled())
            .then(onFulfilled())
            .then(onFulfilled())
            .done { result in print(result) }

see: https://github.com/mxcl/PromiseKit/blob/master/Documentation/GettingStarted.md

done is the same as then but you cannot return a promise. It is typically the end of the "success" part of the chain.


text:
Q: How to specify discriminator value for the parent table using single table inheritance? I have several entities using single table inheritance:
@Entity()
@TableInheritance({ column: { type: 'varchar', name: 'documentType' } })
export class Document {
    ...
    @Column({ type: 'enum', enum: DocumentType })
    documentType: DocumentType;
    ....
}

@ChildEntity(DocumentType.TRAINING_DOCUMENT)
export class TrainingDocument extends Document { ... }

@ChildEntity(DocumentType.GENERATED_RECORD)
export class GeneratedRecord extends Document { ... }

I also have an enum for DocumentType
export enum DocumentType {
    DOCUMENT = 'DOCUMENT',
    TRAINING_DOCUMENT = 'TRAINING_DOCUMENT',
    GENERATED_RECORD = 'GENERATED_RECORD'
}

I can specify the discriminator value for the child entities (TrainingDocument, and GeneratedRecord), but I can't see a way to specify it for the parent (Document) class.
When I go to insert into my document repo I get the following error:
QueryFailedError: invalid input value for enum document_documenttype_enum: "Document"

I have looked at the docs and I can't see any way to specify the discriminator value in the decorators.
I have also tried manually setting the documentType field when I create the entity, but it seems that TypeORM overrides it.


text:
Q: Can I make Install-SPSolution verbose? I'm trying to deploy a farm solution using:
Install-SPSolution -Identity [bla bla bla] -GACDeployment
However, the job never seems to finish and doing Get-SPSolution shows "False" for the solution "Deployed" column. I've no idea why is not being able to deploy and would like to get a verbose log from Install-SPSolution. Is this possible? I already searched but couldn't find anything. If this is not possible what are the steps I should take to investigate this?

A: You are right, there is no option to get verbose. I would say the only way to do that is to do it manually --> meaning you log each step to a text file from start to finish and this will get you a little bit of information on where it stopped (maybe try that on a DEV environment and once you figure the issue and fix it, trim the logging part and deploy to PROD)

A: Couple of things you can do.

*

*Enable the Verbose logging for the farm and then deploy the solutions and check the ULS logs.

*Or use the -Verbose parameter in your  command, which will list all steps in it. like this
Install-SPSolution -Identity [bla bla bla] -GACDeployment -Verbose
It will show output like this
VERBOSE: Leaving BeginProcessing Method of Install-SPSolution.
VERBOSE: Performing the operation "Install-SPSolution" on target
"blah blah .wsp".
VERBOSE: Leaving ProcessRecord Method of Install-SPSolution.
VERBOSE: Leaving EndProcessing Method of Install-SPSolution.
Or in case of error:

VERBOSE: Leaving BeginProcessing Method of Install-SPSolution.
VERBOSE: Performing the operation "Install-SPSolution" on target
  "blahblah.wsp".
Install-SPSolution : A deployment or retraction is
  already under way for the solution "blahblah.wsp", and only one
  deployment or retraction at a time is supported. At line:1 char:1
  + Install-SPSolution -Identity blab lah
  -GACDeployment ...
  + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  ~~~
      + CategoryInfo          : InvalidData: (Microsoft.Share...InstallSolution:    SPCmdletInstallSolution)
  [Install-SPSolution], InvalidOperationException
      + FullyQualifiedErrorId : Microsoft.SharePoint.PowerShell.SPCmdletInstallS    olution
VERBOSE: Leaving ProcessRecord Method of Install-SPSolution. VERBOSE:
  Leaving EndProcessing Method of Install-SPSolution.


text:
Q: How to programmatically check whether the mobile phone is currently charging or is on battery? do the mobile phones have an API function, or something similar, that could be called by a phone application to determine whether the phone is currently charging or is on battery?
I'm guessing that if there is such a function, it would likely have a different name on each mobile OS, so if anybody could name those function names, and the OS for each, that would be great.
many thx

A: Nokia's implementation of Java ME has an API function to check the battery level.
More generally, Java ME has the "Sensor API" (which is highly implementation-specific) that exposes sensors such as the charger state, accelerometer(s), etc.

A: On the RIM BlackBerry line of devices, this can be done by using the net.rim.device.api.system.DeviceInfo class; specifically, the getBatteryStatus() static method of that class which returns a bitfield of flags related to the battery state on the device. The bitfield contains various flags that indicate whether the device is being charged or is running on battery power (among other things).


text:
Q: Adding border on border radius image background bleed through I'm adding a black border on images with a blue background and while doing so, it appears to add an ever so noticeable background colored outline on the INSIDE of the border when doing so. Is there a way to get rid of this? The code I'm using is simple:
border-radius: 100%;
border: 3px solid rgb(0, 0, 0);

And you can see the background color edging in by adding a radius to any image, as an example:

A: There are several ways to avoid that annoying border-radius background bleed:
Method 1: Wrapper with Background Color
Put the  in a wrapper element, and add padding to the wrapper, with a background color that matches the 's border. This way, any antialiasing that happens on the image will take into account the background color of the wrapper, rather than the background color of the page.
Method 2: Add Background Color to Image
Add a background color to your  that matches the border color. It'll use the 's background color instead of the page background color to do the antialiasing.
Method 3: Use Padding Instead
Don't bother with a border. Add padding to your  equal to the border size you want, and add a background color in the border color you want. This gets you the same effect with the least amount of code.

Here's a JSFiddle with each of these methods: https://jsfiddle.net/4zpL98au/14/

A: @stvnrynlds gave an interesting answer and I wanted to test this out myself with actual code.
I have created a snippet below with both versions for comparison.
.test1 - uses padding with a wrapper instead of a border
.test2 - uses border only

.test1{
  border-radius: 50%;
  width:50px;
  height: 50px;
  padding:5px;
  background:black;
}

.test1 img{
  border-radius:50%;
}

.test2 img{
  border-radius: 50%;
  border: 5px solid black;
}

Zooming in 500% into the browser you can see the end results:

A: There's a quite simple solution for this problemen, just by adding a background color:
background:#000;
border-radius: 100%;
border: 3px solid #000;


text:
Q: Get a Named Range by String in Excel Workbook when Name is duplicated To elaborate, let's say I have two named ranges in my workbook. Both named ranges have the same Name (let's say "myName"), but one is scoped to Sheet1 and the other is scoped to the Workbook.
Given a name (string) of the Named Range, I want to grab the Workbook level Named Range.
If I use the native call: wb.Names.Item("myName"), it returns the sheet scoped named range.
If instead I do: wb.Names.Item("Sheet1!myName"), that obviously returns the sheet scoped name range. I've found I can use this to specify the sheet specific ones, but not a workbook one.
Is there anyway I can specify I want the workbook scoped one?
My workaround is currently iterating over the list of all the Names, and comparing the .Name property to grab the workbook scope Named Range. This works because the .Name property appends a "Sheet1!" to the sheet scoped Named Range. This is however very costly to do, and I want to avoid it.

A: When we (JKP and myself) were writing Name Manager we specifically added a filter and warning message for Duplicate Global/Local Names because this Excel object model behaviour you mention leads to hard to detect bugs.  So my recommendation is never to use duplicate Global/Local Names.We use code to detect if a name is duplicate global/local with the parent of the local name active and then switch sheets if necessary. The optimised VBA code we use to find the local version of a global name is this: its reasonably fast unless you have several tens of thousands of names -
    Function FindNameLocal(oSheet As Worksheet, sName As String) As Name
        Dim oName As Name
        Dim strLocalName As String
        Dim strLocalNameNoQuote
        Dim strName As String
        Set FindNameLocal = Nothing
        If Len(sName) > 0 And Not oSheet Is Nothing And oSheet.Names.Count > 0 Then
            On Error Resume Next
            strLocalName = "'" & oSheet.Name & "'!" & sName
            strLocalNameNoQuote = oSheet.Name & "!" & sName
            Set FindNameLocal = oSheet.Names(strLocalName)
            If Err <> 0 Or (FindNameLocal.NameLocal <> strLocalName And FindNameLocal.NameLocal <> strLocalNameNoQuote) Then
                On Error GoTo 0
                Set FindNameLocal = Nothing
                For Each oName In oSheet.Names
                    strName = oName.Name
                    If Len(strLocalName) = Len(strName) Or Len(strLocalNameNoQuote) = Len(strName) Then
                        If strName = strLocalName Or strName = strLocalNameNoQuote Then
                            Set FindNameLocal = oName
                            GoTo GoExit
                        End If
                    End If
                Next
            End If
        End If
GoExit:
    End Function


text:
Q: Uncaught exception 'Dailymotion API Exception' with message 'This video format is not supported I am getting this error when video uploading in daily motion using API, but two days ago I did get any error, successfully updated
Error
Uncaught exception 'DailymotionApiException' with message 'This video format is not supported'

A: As stated in the error message, this means that the format of the video file you provide is not valid or not supported. Can you check the following:

*

*that the video source is valid

*that the video file respects the following specifications: https://faq.dailymotion.com/hc/en-us/articles/203790706-Upload-specifications-and-encoding-settings Maybe your video file is too long or too big?


text:
Q: SSH tunnel freezes and says "administratively prohibited" when a domain cannot be resolved So I am opening a SSH tunnel to a remote server to use it as proxy:
ssh -D 10000 -N remote

I use FireFox with FoxyProxy and it is working quite well. Except sometimes the tunnel freezes. A good example is the page of this Australian songwriter. The site makes requests to the domain johnbutler-trio.com which might not be configured correctly. The result is that the tunnel freezes for a minute and no further connection is possible until a time out is triggered. After that everything is back to normal until I visit this site again. With the debug switch enabled the output is the following:
debug1: channel 5: new [dynamic-tcpip]
debug1: Connection to port 10000 forwarding to socks port 0 requested.
...
debug1: Connection to port 10000 forwarding to socks port 0 requested.
debug1: channel 45: new [dynamic-tcpip]

channel 38: open failed: administratively prohibited: open failed
debug1: channel 38: free: direct-tcpip: listening port 10000 for johnbutler-trio.com port 80, connect from 127.0.0.1 port 45057 to 127.0.0.1 port 10000, nchannels 46
channel 39: open failed: administratively prohibited: open failed
channel 40: open failed: administratively prohibited: open failed
channel 41: open failed: administratively prohibited: open failed
channel 42: open failed: administratively prohibited: open failed
channel 43: open failed: administratively prohibited: open failed
debug1: channel 39: free: direct-tcpip: listening port 10000 for johnbutler-trio.com port 80, connect from 127.0.0.1 port 45058 to 127.0.0.1 port 10000, nchannels 45
debug1: channel 40: free: direct-tcpip: listening port 10000 for johnbutler-trio.com port 80, connect from 127.0.0.1 port 45059 to 127.0.0.1 port 10000, nchannels 44
debug1: channel 41: free: direct-tcpip: listening port 10000 for johnbutler-trio.com port 80, connect from 127.0.0.1 port 45060 to 127.0.0.1 port 10000, nchannels 43
debug1: channel 42: free: direct-tcpip: listening port 10000 for johnbutler-trio.com port 80, connect from 127.0.0.1 port 45061 to 127.0.0.1 port 10000, nchannels 42
debug1: channel 43: free: direct-tcpip: listening port 10000 for johnbutler-trio.com port 80, connect from 127.0.0.1 port 45062 to 127.0.0.1 port 10000, nchannels 41

What is going on? How can I prevent the tunnel from freezing when there is an error which somebody's domain? Btw opening random non registered domains won't result in a tunnel freeze.


text:
Q: JQuery Ajax call returns "Error: Not enough storage is available to complete this operation." So I am getting the above error when I am trying to pass the result.target of an OnLoad event in the FileReader.readAsArrayBuffer call using an jQuery Ajax POST call. The POST call is not actually being made (as monitored by Fiddler). This call works for files tested to about 120 mbs. I am trying to upload a 218 mb file though now. Also this seems to be IE specific, as it works in Chrome.
Call:
$.ajax({
 type: 'POST',
 url: url,
 contentType: 'application/json;odata=verbose',
 data: fileData,
 processData: false,
 headers: { ACCEPT: 'application/json;odata=verbose', "X-RequestDigest": formDigest, "If-Match": "*" }
}).done(function (results) {
    //Do Stuff
});

As context, fileData is the result.target created through a file upload via the HTML 5 File API. I am trying to pass a file to upload in SharePoint via the Web API.

A: Servers usually have limits on file sizes that can be uploaded. It sounds like you're running into the servers limit. If you own the server, you can raise the cap, otherwise you could try asking the server's admin.


text:
Q: How does AirDroid's web.airdroid.com get routed to my device? I am using AirDroid (PlayStore). When you start the app in your home network you can reach you Android device by the URL: http://web.android.com. But how does the device tell my wireless router to route this URL to the Android device?

A: This is just a wild guess, but I assume the app gets the device's local ip address, sends it to the airdroid servers, which send it back to the webapp running in the browser on your desktop. Then the webbapp probably uses the ip and ajax or websockets to connect to a webserver running in the airdroid app on the device.

A: When you log in to your Airdroid web app in your browser and also in your phone it has the information stored about your network so when you try to connect to the mobile device by the browser it checks if the IP is of the same network it connects in local mode otherwise if you are on mobile data or in other network it goes by the airdroid server to reach to the device


text:
Q: Hot to put a image as a background in css I am trying to add a image as an background. I believe the follwing code is right, but it does not work. Please anyone help me. My image is inside the folder images which is in the same directory as index.html.
body{
    background-image:('images/background.jpg');
    background-repeat: repeat;
    background-attachment:fixed;
}

In a previous project I had the following: This code works, but the code above doesn't. I can not understand why
body{
background-color:white;
color:#404040;
font-size:11pt;
font-family:Georgia, Garamond, serif;
background-image:url("images/silverware.jpg");
background-repeat:repeat;
background-attachment:fixed;
}

A: It is not working because you left out the url prefix in the background image property:
body{
    background-image:('images/background.jpg');
    background-repeat: repeat;
    background-attachment:fixed;
}

It should be:
body{
    background-image:url('images/background.jpg');
    background-repeat: repeat;
    background-attachment:fixed;
}

A: The answer was in your second code sample. Missing the 'url' parameter
background-image:url('images/background.jpg');

Also make sure, your image path is correct

A: The image url is relative to the css file not to your html file. So if your file structure looks like this:
folder
-css
-images
-js
-index.html
then you will need to add ../ to your background-image url. In this case it would look like this:
body{
    background-image: url('../images/background.jpg');
    background-repeat: repeat;
    background-attachment:fixed;
}

***edit : actually the missing url part of the background image property is the issue.


text:
Q: Parsing hash url to object in JavaScript? I would like to execute a process on the page load depending on what the hash in the URL is. I think I will need RegEx because I am looking for a pure JavaScript solution (no library dependencies).
What I am trying to do is if the hash is "#/products", then I will call "myIndex()"
else if the hash is "#/products/3", then I will call "myDetail(id)" where "id" is a variable to the product number.
Anybody have a good idea on how to achieve this?

A: Here's a solution that checks for the literal string '#/products' first, avoiding the regular expression where it's unnecessary.
var hash = location.hash,
    regexID = /^#\/products\/(\d+)$/,
    matches;

if (hash == '#/products') {
  myIndex();
} else if (matches = hash.match(regexID)) {
  myDetail(matches[1]);
}


text:
Q: How to render view in parent controller I want to pass down values from a parent controller, to the views of the child, or ideally, render the view directly from the parent controller.
Here is my parent controller:
class SuperBlogPostsController < ApplicationController

def index(country)
    if country == "AUSTRALIA"
      @posts = AustraliaBlogPost.all
    hash = { posts: @posts, featured_post: AustraliaBlogPost.find_by(featured_post: true) }
    respond_to do |format|
        format.html {render 'super_blog_post/index'}
        format.json {render json: hash}
    end
end
end

def show(country)
    if country == "AUSTRALIA"
        @post = AustraliaBlogPost.find(params[:id])
        respond_to do |format|
            format.html {render 'super_blog_post/show'}
        format.json {render json: @post}
    end
end

end
And here is my child:
class AustraliaBlogPostsController < SuperBlogPostsController

  def index
    super(country: 'AUSTRALIA')
  end

  def show
    super(country: 'AUSTRALIA')
  end
end

This is the error that I get, even when I append .json at the end of the url:

Is it possible to do the rendering of the view in the parent, or at least pass down the return values of the variables generated by the parent to the  child? If I've been unclear at all, let me know!
Thanks!

A: Your parent controller methods accept a normal parameter, not named parameter.
Instead of:
super(country: 'AUSTRALIA')

You need
super('AUSTRALIA')

But I must say, the entire logic of your controllers doesn't make a lot of sense.


text:
Q: how to save data in an integer during recursion in java I want to write a recursive method that receives a number and a digit. The method should return a second number consisting of only the digits of the first parameter which are divisible by the second parameter.
For example, if the method is called with number = 5369405 and digit = 5, then it should return 505.
So far, I've written the following method but it doesn't work as the index remains at -1 and I'd like to save its value during each recursion. My idea was to save the values to construct the returned number.
Can anyone tell me how I can save the index during every recursion to prevent it from returning -1?
This is the code I've written:
public static int subNumber(int num, int digit)
{
    int index=-1;
    if(num <10)
    {
        if(num%digit==0){
            index++;
            return num*(int)Math.pow(10,index);

        }
        else{
            return 0;
        }
    }
    int mod=(num%10);
    if(mod % digit ==0)
    {
        index++;
        return mod*(int)Math.pow(10,index)+subNumber(num/10,digit);

    }
    else{
        return 0+subNumber(num/10,digit);
    }
}

A: As @markspace has suggested in the comments, you should also pass an index to your method to keep track of the position of every divisible digit in order to properly compute their weight within the final number.
Also, when designing a recursive method you should firstly identify your base cases. In this scenario, your base cases are:

*

*The number passed is smaller than the digit to divide with.

*The number passed is equal to the digit to divide with.

*Additionally, the user could pass an inconsistent index (anything but zero). Usually in these cases, when the user is supposed to pass parameters that are only meant to help you with your recursive computation, you should hide the actual recursive method and only offer a client version of it. Basically, this client version only makes a call to the proper recursive method with the right parameters in order to avoid misuses.
One Method Solution
public static int subNumber(int num, int digit, int index) {
    //Base case where num is smaller than than the digit to divide with
    if (num < digit) {
        return 0;
    }

    //Base case where num corresponds to digit and therefore is divisible
    if (num == digit) {
        return num * ((int) Math.pow(10, index));
    }

    //Retrieving the less significant digit
    int modDigit = (num % 10);

    //If the current mod digit is divisible by digit then its i-th position is defined and the later call results are added to it
    if (modDigit % digit == 0) {
        return modDigit * ((int) Math.pow(10, index)) + subNumber(num / 10, digit, index + 1);
    }

    //Proceeding with the recursion without adding a value to sum (conceptually should be return 0 + subNumber(...))
    return subNumber(num / 10, digit, index);
}

Client Method Solution
public static int subNumberClient(int num, int digit){
    return subNumber(num, digit, 0);
}

private static int subNumber(int num, int digit, int index) {
    //same implementation but with private access modifier
}


text:
Q: Spring 4 vs Jersey for REST web services We are planning to make a new application with spring 4.0.6 version. We use controller that can return "XML" or "JSON".
In the previous project we have successfully implemented Jersey with Spring for REST support using JAX-RS API, but after reading a few articles and suggestions from seniors they said spring is providing pretty good REST support.
Some of the points that really confused me if I use Spring REST support without using JAX-RS and Jersey are:

*

*How marshaling and unmarshaling done in Spring MVC ?

*Is it necessary for marshaling or unmarshaling need to use jax-rs.

*If marshaling and unmarshaling are automatically handled by spring then how does it know about xmlRootElements.
I am still confused if Spring proving very good support of REST then why do people still go with Jersey for REST?
Really looking to know more in details.
If I said anything wrong please ignore it.
Explanation with example is really helpful.

A: AFAIK Spring REST support is based on Spring MVC and its not JAX-RS implementation while Jersey has implemented JAX-RS specification.
Those having Spring (Core, AOP or MVC) in their project chooses Spring ReST support over JAX-RS implementor.
I recommend Jersey as its mature, implements JAX-RS and is easy to use.

A: I'd say both Jersey and Spring MVC are great - each project has its own style and strengths. Anyway, Stack Overflow is not the right place for asking subjective comparisons (your question would be closed quite quickly). If you're already using Spring for everything else and are not required to use JAX-RS, then Spring MVC makes total sense.
Regarding features like (un)marshalling, JAX-RS is just a spec after all - other libraries can offer similar features without implementing the same API.

*

*Instead of MessageBodyReaders/Writers, Spring MVC is using HttpMessageConverters to handle (un)marshalling REST resources. Spring MVC handles content negotiation and chooses the best available converter for the job (you can annotate methods to hint at what media type they produce/consume).

*No, it's not necessary to use JAX-RS to (un)marshall resources. In fact, JAX-RS implementations and Spring MVC use third party serialization libraries to do the job; so it's not tied to a particular standard.

*In its 4.0.6 version, Spring supports many HttpMessageConverters, with Jackson for JSON, JAXB for XML and many others. Spring 4.1.0 added more HttpMessageConverters:

*

*Jackson is now available for both JSON and XML

*Google Protobuf

*Gson for JSON, as an alternative to Jackson

To answer your last point, @XmlRootElement is a JAXB annotation and is not part of JAX-RS. Spring supports JAXB.
For a more complete example with REST in Spring, check out this getting started guide (you'll get a complete example running in 10-15 minutes).
Again the last part of your question is quite subjective - there are many popular solutions for building REST services in the JVM, not just Jersey and Spring (Dropwizard, Play! Framework, etc).


text:
Q: How can Iinux powershell test if a file is a symbolic link? On Linux, I want to replace a bash script with powershell. The script needs to test a file to determine if it is a symbolic link. In bash, one can use the -L operator:
if [[ -L "/tmp/mysteryfile" ]] ; then ; echo "It is a link" ; fi
How can I do the same in powershell on Linux?

A: On my Ubuntu 19.04 this:
PS> gci /bin/bz*|select Mode,LastWriteTime,Length,Name,Attributes,LinkType|ft -auto

yields
Mode   LastWriteTime     Length Name           Attributes LinkType
----   -------------     ------ ----           ---------- --------
--r--l 04.07.19 14:50:14  38984 bzcat            ReadOnly HardLink
-----l 04.07.19 14:50:14      6 bzcmp        ReparsePoint SymbolicLink
--r--- 04.07.19 14:50:14   2227 bzdiff           ReadOnly
-----l 04.07.19 14:50:14      6 bzegrep      ReparsePoint SymbolicLink
--r--- 13.08.18 13:29:27   4877 bzexe            ReadOnly
-----l 04.07.19 14:50:14      6 bzfgrep      ReparsePoint SymbolicLink
--r--- 04.07.19 14:50:14   3641 bzgrep           ReadOnly
--r--l 04.07.19 14:50:14  38984 bzip2            ReadOnly HardLink
--r--- 04.07.19 14:50:14  14328 bzip2recover     ReadOnly
-----l 04.07.19 14:50:14      6 bzless       ReparsePoint SymbolicLink
--r--- 04.07.19 14:50:14   1297 bzmore           ReadOnly

So the Mode l denotes a link, as does the Attribute ReparsePoint denote a SymbolicLink.
But only the LinkType differentiates between Hard-/SymbolicLinks
if((Get-Item "/tmp/mysteryfile").LinkType -eq 'SymbolicLink'){"It is a SymbolicLink"}

or
if($LT=(Get-Item "/tmp/mysteryfile").LinkType){"It is a $LT"}

To see some stats:
PS> gci /bin -rec -force -ea 0|Where LinkType|Group LinkType -NoElement

Count Name
----- ----
    3 HardLink
  276 SymbolicLink


text:
Q: How to implement scrollbar for particular row in html I have table with 10 row.I want vertical scrollbar for 5 row only.Can anybody tell how to add vertical scroll bar for 5 rows

        Company
        Contact
        Country

        Alfreds Futterkiste
        Maria Anders
        Germany

        Centro comercial Moctezuma
        Francisco Chang
        Mexico

        Ernst Handel
        Roland Mendel
        Austria

        Island Trading
        Helen Bennett
        UK

        Laughing Bacchus Winecellars
        Yoshi Tannamuri
        Canada

        Magazzini Alimentari Riuniti
        Giovanni Rovelli
        Italy

        Ernst Handel
        Roland Mendel
        Austria

        Island Trading
        Helen Bennett
        UK

        Laughing Bacchus Winecellars
        Yoshi Tannamuri
        Canada

        Magazzini Alimentari Riuniti
        Giovanni Rovelli
        Italy

        Island Trading
        Helen Bennett
        UK

        Laughing Bacchus Winecellars
        Yoshi Tannamuri
        Canada

        Magazzini Alimentari Riuniti
        Giovanni Rovelli
        Italy

Thanks

A:
Use this table this is fully responsive and you can adjust height of table.

            Company
            Contact
            Country

            Alfreds Futterkiste
            Maria Anders
            Germany

            Centro comercial Moctezuma
            Francisco Chang
            Mexico

            Ernst Handel
            Roland Mendel
            Austria

            Island Trading
            Helen Bennett
            UK

            Laughing Bacchus Winecellars
            Yoshi Tannamuri
            Canada

            Magazzini Alimentari Riuniti
            Giovanni Rovelli
            Italy

            Ernst Handel
            Roland Mendel
            Austria

            Island Trading
            Helen Bennett
            UK

            Laughing Bacchus Winecellars
            Yoshi Tannamuri
            Canada

            Magazzini Alimentari Riuniti
            Giovanni Rovelli
            Italy

            Island Trading
            Helen Bennett
            UK

            Laughing Bacchus Winecellars
            Yoshi Tannamuri
            Canada

            Magazzini Alimentari Riuniti
            Giovanni Rovelli
            Italy

A: You would have to add a class to the particular row, for example:
HTML:

        Company
        Contact
        Country

        Alfreds Futterkiste
        Maria Anders
        Germany

CSS:
.scroll{
 overflow: auto;
 height: 200px
}

Hope this helps.

A: I dont know if i get you very well, my first though was this:

.scroll {
  height: 75;
  overflow: scroll;
}

          Company
          Contact
          Country

          Alfreds Futterkiste
          Maria Anders
          Germany

          Centro comercial Moctezuma
          Francisco Chang
          Mexico

          Ernst Handel
          Roland Mendel
          Austria

          Island Trading
          Helen Bennett
          UK

          Laughing Bacchus Winecellars
          Yoshi Tannamuri
          Canada

          Magazzini Alimentari Riuniti
          Giovanni Rovelli
          Italy

          Ernst Handel
          Roland Mendel
          Austria

        Island Trading
        Helen Bennett
        UK

        Laughing Bacchus Winecellars
        Yoshi Tannamuri
        Canada

        Magazzini Alimentari Riuniti
        Giovanni Rovelli
        Italy

        Island Trading
        Helen Bennett
        UK

        Laughing Bacchus Winecellars
        Yoshi Tannamuri
        Canada

        Magazzini Alimentari Riuniti
        Giovanni Rovelli
        Italy

but now i thing you want to display only 5 rows at a time, so i made this:

.scroll {
  height: 150px;
  overflow-y: scroll;
}

table {
  line-height: 20px;
  font-size: 14px
}

      Company
      Contact
      Country

      Alfreds Futterkiste
      Maria Anders
      Germany

      Centro comercial Moctezuma
      Francisco Chang
      Mexico

      Ernst Handel
      Roland Mendel
      Austria

      Island Trading
      Helen Bennett
      UK

      Laughing Bacchus Winecellars
      Yoshi Tannamuri
      Canada

      Magazzini Alimentari Riuniti
      Giovanni Rovelli
      Italy

      Ernst Handel
      Roland Mendel
      Austria

      Island Trading
      Helen Bennett
      UK

      Laughing Bacchus Winecellars
      Yoshi Tannamuri
      Canada

      Magazzini Alimentari Riuniti
      Giovanni Rovelli
      Italy

      Island Trading
      Helen Bennett
      UK

      Laughing Bacchus Winecellars
      Yoshi Tannamuri
      Canada

      Magazzini Alimentari Riuniti
      Giovanni Rovelli
      Italy

Hope it helps, :)


text:
Q: What's the easiest way to expose a SQL interface to my application? I'm working on an application which stores data in tables, similar to an RDBMS.  I'm looking for a way to let my users query this data using SQL.  Ideally, I'd like to do this without having to implement my own SQL parser, query optimizer, etc.  So far, ripping parts out of something like Apache Derby is looking like the best option, but I'm wondering if there's an easier way.
I think I need:

*

*A SQL parser (JavaCC?)

*A query optimizer

*A way to execute the optimized queries

Alternatively, does anyone know any open source databases where I can replace the data store with my own files/data format?
One last note, I don't really need transactions, primary keys, foreign keys, constraints, etc.  Thanks!
Clarifications

*

*This won't be exposed via the web.  It will only ever be used by trained, trusted users (who have many other, easier, ways at their disposal to destroy the data in question)

*The optimization stage is fairly important, as we're talking potentially hundreds of gigabytes of data in the various tables

*This is intended to be an extension to an existing system.  I can't change the data format, and there's no option to throw away the existing system and replace it with a traditional RDBMS.

*Java-based solutions are preferred :)

Thanks for the responses, guys!

A: MySQL has support for pluggable storage engines. Here is a starting point.
Also, maybe using some kind of JDBC SDK could help.

A: The obvious (and easiest) way is to store your data in a database. It's a little surprising to hear that you need to implement your own database, that there's no existing database that's suitable.

A: You mean your 'tables' aren't really SQL tables? And that you wish to implement a SQL interface to what is not actually a DMBS but your own clone of one?
I think you better use an existing DBMS like Derby and let the users query it directly.
You can offer some query filtering if data damage is what you are concerned about.
All in all, this doesn't look like a wise decision to make.
That said, you can implement your own MySQL storage engine through the "Storage Engine API", which lets you define the file format (and more):

*

*http://solutions.mysql.com/engines.html

*http://dev.mysql.com/doc/refman/6.0/en/storage-engines.html

*http://forge.mysql.com/wiki/MySQL_Internals_Custom_Engine

A: I'm pretty sure that HSQLDB will allow you to do what you want and will also allow you to store data in flat files.
You can also use SQLite, the downside to this is that you there aren't (at least the last time I checked) any pure Java JDBC drivers. This is the SQLite format though.
Both Apache Derby and HSQLDB are pretty lightweight and you shouldn't need to strip them down.
You don't need to write a parser BTW - all you need to do is to capture SQL from the users and execute it.
The optimizer will be the tricky part but this depends on how big you think the tables are going to get - if they are small enough and the machine fast enough, you may not need to bother.
If you are going to expose this via the Web in any form - you may want to think again. What you are proposing is a hackers dream.


text:
Q: Display data from database in a table I've got something like this, the function allows me to display data from the database "demo", from "products" table:
class Product
{
private $conn;
private $id;
private $name;
private $description;
private $price;
private $category_id;
private $category_name;
private $created;

public function __construct($db)
{
    $this->conn = $db;
}

public function readAll()
{
    $stmt = $this->conn->prepare('SELECT name, description, price, CategoryID, created FROM products');
    $stmt->execute();
    while ($result = $stmt->fetch(PDO::FETCH_ASSOC)) {
        $n = $result['name'];
        $d = $result['description'];
        $p = $result['price'];
        $ca = $result['CategoryID'];
        $c = $result['created'];
        echo $n . " - " . $d . " - " . $p . " - " . $ca . " - " . $c . "
" . "
";
    }
}
}

Here is my database connection:
class Database {

public function getConnection() {
    $result = false;
    try {
        $result = new PDO('mysql:host=localhost;dbname=demo', 'root', '');
    } catch(PDOException $e) { }
    return $result;
}
}
$db = new Database();
$conn = $db->getConnection();
if (!$conn) {
die("Error connecting to the database");
}

I can display data like this:

readAll:

        <form action="" method="post">
            Products:
 (Name - Description - Price - Category ID - Creation date):

            <?php
            $cat = new Product($conn);
            echo $cat->readAll();
            ?>
        </form>

But how can I display data from the database in a table?

A: Here's a clue, and it all depends on how your php is structured.
Just before the while loop,
  echo '
';

// you can add table head if you please
 While(...){

    $a = $row['...'];

    echo '

'.$a.'

    ';
   //you can add as many columns as you wish

  }

  echo '

I hope you picked understanding from this

A: Here's a simple way to achieve what you're trying. But before that, let's discuss a for a moment your approach to the application you're building.
First. It's not a good practice to construct the html in your php code. The best way you can go about it is to prepare the data for presentation and simply provide the presentation layer with this data (for a much broader explanation of this mindset, take a look at the MVC pattern).
So, let's prepare the data. In your function, where you get the products, simply return them.
public function getAll()
{
    $stmt = $this->conn->prepare('SELECT name, description, price, CategoryID, created FROM products');
    $stmt->execute();
    $allProducts = $stmt->fetchAll(PDO::FETCH_ASSOC);

    return $allProducts;
}

I've also renamed the function, because for what we're going to build, getAll() is a more descriptive than readAll().
Now, we have a quick and easy way to get the data we need.
Let's do the presentation.
In your view php file, get the data.
<?php
    // Get all products.
    $products = (new Product($conn))->getAll();
?>

If you dig deeper in the MVC (or any MV*) pattern, you'll find out that a view asking for the data is not the best approach (pulling the data). The better one is to push the data to the view. But that's another story now.
So, we have our products in the products array. Let's iterate over it. Don't forget to first check if there are any users at all.
<?php if ( ! empty($products)) : ?>

            Name
            Description
            Price
            CategoryID
            Created

    <?php foreach ($products as $product) : ?>

            <?php $product['name'] ?>
            <?php $product['description'] ?>
            <?php $product['price'] ?>
            <?php $product['CategoryID'] ?>
            <?php $product['created'] ?>

    <?php endforeach; ?>

<?php endif; ?>

That's it. I hope I inspired you to broaden your perspective on best practices. :)


text:
Q: Update MS Word Template Dynamically using C# I've added the Bookmark at particular position and save that file with .dotx. When I run the solutions, it add the date in the Template file but lost all the remaining records store in the template.
I want to add the data in the Work template dynamically, and data can be grow it varies.
object oMissing = Missing.Value;
string DateParameter = DateTime.Today.Date.ToString();

Word._Application word = new Word.Application();
word.Visible = false;

// Template
object oTemplate = @"..\SampleTemplate.dotx";
Word._Document document = word.Documents.Add(ref oTemplate, ref oMissing, ref oMissing, ref oMissing);

object oBookMark = "DateParameter";

Word.Range wrdRng = document.Bookmarks.get_Item(oBookMark).Range;
Microsoft.Office.Interop.Word.Range rng = document.Content;

rng.Text = DateParameter;

document.SaveAs2("TestDocument" + DateTime.Now.Millisecond, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing);

GC.Collect();

Thank you

A: You are replacing the wrong Range.Text.
In your code you are replacing the rng object instead of the wrdRng object which refers to the actual bookmark.
Try this:
 Word.Range wrdRng = document.Bookmarks.get_Item(oBookMark).Range;
 --Microsoft.Office.Interop.Word.Range rng = document.Content;

 wrdRng.Text = DateParameter;


text:
Q: Resizing LUKS encrypted partition - had success but can't use the unallocated space now? Following various guides online, I've attempted to reduce my LUKS-encrypted hard-drive partition (specifically, root / data). I've gotten to the point where GParted recognizes the new unallocated space, but it is "stuck inside" the original partition. In the screenshot below, you can see how the unallocated space is just 1 MB (nothing), but the highlighted data partition is half unallocated internally:

And if you ask what's-up with the data partition, it says it has the unallocated space I want:

So I queue up a resize where I shrink it to to its minimum size (~250 GB), and it shows me this beautiful preview of exactly what I want (giving me the ~198 GB unallocated as a separated partition):

But when I execute the resize, it fails as shown:

It thinks it's already the reduced size? But gah, it doesn't give me that "unallocated space" as a partition! The beautiful preview above reverts back to the first screenshot in this post.
I have also tried the KDE Partition Tool and it behaves basically the same way. Additionally, I've tried carrying out the resize from a separate live disk so that the partition I'm resizing isn't mounted, and again, same exact behavior. Another interesting point is what the Disks utility thinks:

I am definitely not experienced with disk management so I have of course backed up my data and am considering just wiping the machine and making the partition smaller from the start, but I feel like I'm very close here? Is there a simple step missing or is this far from done?

A: The problem is that while you resized the filesystem inside of the partition, the partition itself was not resized. Think of it like putting your foot inside of a shoe that fits perfectly. You have made your foot (the filesystem) smaller, but the shoe (partition) is the same size, thus there is unused space in the shoe. You need to get a smaller shoe.
A partition is just a concept stored in the GPT (GUID Partition Table). It stores the start position and end position of the partition. You need to compute the new end partition of the partition and update the GPT.
The formula is NEW_PARTITION_SECTOR_END = PARTITION_SECTOR_START + (LUKS_SIZE_SECTORS + LUKS_OFFSET_SECTORS) - 1. This I got from https://wiki.archlinux.org/index.php/Resizing_LVM-on-LUKS#Resize_the_partition
In your case, you want to do "sudo parted /dev/nvme0n1" and then use the "resizepart" command. You can get the values of PARTITION_SECTOR_START from parted itself with the print command. The LUKS_OFFSET_SECTORS and LUKS_SIZE_SECTORS can be obtained from "cryptsetup status cryptdata". Add them all together and that will give you the new end value.
Important: Note that when you use parted, make sure to type the "unit" command first to change the units to "s" which stands for sectors.


text:
Q: Vector Analysis in $\mathbb{R}^3$ I'm asked to do this computation from a differential manifolds text: $${d\alpha}=\left(\frac{\partial \:R}{\partial \:y}-\frac{\partial \:Q}{\partial \:z}\right)\left(dy\wedge \:dz\right)+\left(\frac{\partial \:P}{\partial \:z}-\frac{\partial \:R}{\partial \:z}\right)\left(dz\wedge \:dx\right)+\left(\frac{\partial \:Q}{\partial \:x}-\frac{\partial \:P}{\partial \:y}\right)\left(dx\wedge \:dy\right)$$
I've waded through a Calc 1-2 answers-provided book, and started a differential equations book, but I'm really not good at all at calculations of calculus.  Any help?
It comes from the chapter on "Tensor Fields: local theory" under the section "exterior derivative" in a subsection concerning grad, curl, div.  Also, the differential equations textbook it too advanced for me to understand anything except the first chapter. I'm sort of looking at solving math backwards from harder problems to put in place the basics.  It just how my mind works, and it keeps me interested, and interesting.
The one-form $\alpha = Pdx + Qdy + Rdz$ which is analogous to vector field $F = Pi + Qj + Rk$ where $i, j, k$ are $\frac\partial{\partial \:x}, \frac\partial{\partial \:y}, \frac\partial{\partial \:z}$. I hope this makes it more clear.  Thanks.
Also, $$curl F= \left(\frac{\partial \:R}{\partial \:y}-\frac{\partial \:Q}{\partial \:z}\right)i+\left(\frac{\partial \:P}{\partial \:z}-\frac{\partial \:R}{\partial \:z}\right)j+\left(\frac{\partial \:Q}{\partial \:x}-\frac{\partial \:P}{\partial \:y}\right)k$$
I'm starting to see that the computation would entail the relation between the two large equations here.
Rather, thanks Duncan Rampage for pointing me to the beginning of the subsection on Exterior Derivative.  I feel the very definition of it gives the basis for the computing required in the question.  I had read the chapter a week ago without much connection to it.  Feel stupid now for asking, but thank you.


text:
Q: git practice exercise ( merging two branch and dealing with conflict) I have to clone this repo : https://github.com/glo2003/H21-tp1-git and integrate both branches which are :
refactor/structure and fix/ingredients to the main branch
Main currently looks like this :
Framboise
Banane
Champignon

refactor/structure has a new folder called listes with the file liste.txt in it ( so the file structure is listes\listes.txt) :
- Framboise
- Banane
- Champignon

fix/ingredients :
Framboise
Banane
Pommes

The end result wanted is  this one (so champignon is replaced by Pommes and the list has a new format with the ' - ' also the folder structure will be listes\listes.txt
- Framboise
- Banane
- Pommes

What i tried :
git clone https://github.com/glo2003/H21-tp1-git.git
git merge fix/ingredients
git merge refactor/structure
And i did git status to check to situation :

It looks like a listes.txt got deleted but not sure.
From there i wanted to fix the conflict, with vi listes.txt  or vi listes\listes.txt but i don't see any Head tag for the conflict so i am a bit confused ? What am i doing wrong. Thanks a lot.

A: This is a file level conflict, not a textual conflict. To fix it, you manipulate the index: you say git add to preserve a file and git rm to remove a file. Then say git commit to make it so.
For example, if you like what the restructure branch did, you can say
$ git rm liste.txt
$ git add listes/liste.txt
$ git commit -m"finish merge"

But then you have also accepted the contents of that file. If you wanted the contents to match main, you'd need to copy what's in the top level liste.txt into what's in listes/liste.txt before doing those file level things.

In the comments, you've basically said you wish this were a text-level conflict so you could resolve it at text level. To make that so, you need to:

*

*Abort the merge.

*Rearrange the file structure on main to match the file structure on the branch, and add and commit.

*Now perform the merge, specifying it this way:
 git merge -Srecursive -Xno-renames refactor/structure

This will give you the moved liste.txt as a text conflict that you can proceed to resolve in vi or whatever.
So, here's how I solved it, from the start:
$ git clone git@github.com:glo2003/H21-tp1-git.git
$ cd H21-tp1-git/
# create local branches
$ git checkout fix/ingredients
$ git checkout refactor/structure
$ git checkout main
$ git merge fix/ingredients
$ git merge refactor/structure
# file-level conflict, abort
$ git merge --abort
# mimic "theirs" file structure, and merge
$ mkdir listes
$ git mv liste.txt listes/liste.txt
$ git add .
$ git merge -Srecursive -Xno-renames refactor/structure
# now we have the text level conflict you wanted, as we can see:
$ cat listes/liste.txt
<<<<<<< HEAD
Framboise
Banane
Pommes
=======
- Framboise
- Banane
- Champignon
>>>>>>> refactor/structure

A: When you run git merge, git:

*

*Finds some common / shared starting-point.  This is another commit, somewhere in history, from which both "you" (the person running git merge) and "they" (whoever produced the commit you're merging) started.

*Compares the entire contents of the merge base to your current commit.  These are "your changes".  In your case, you changed an existing file, liste.txt.

*Compares the entire contents of the merge base to their commit.  These are "their changes".  In their case, they removed an existing file, liste.txt, and created an entirely different file, listes/listes.txt.

*Combines—or attempts to combine—these two sets of changes.
Conflicts occur when the changes cannot be combined automatically using the simple rules that Git has built in.  Here, the two changes that cannot be combined are:

*

*you modified some file;

*they removed that file entirely.

Git calls this a "modify/delete conflict".
Now, you claim that they renamed liste.txt to listes/listes.txt.  On what basis do you make this claim?  If the file contents of listes/listes.txt were exactly the same as the file contents of the former, now-deleted liste.txt, I might agree with you—and so might Git.  If your basis for this claim is that liste.txt and listes.txt are sufficiently similar, well, I don't see that off-hand.  Git doesn't see it either.  Once you point out that if we replace line 3 and make medium-small changes to lines 1 and 2, this degree of changing would alter the contents of liste.txt to match those in the new file listes/listes.txt, then I might agree—and so might Git.
In the end, what Git does with this, to decide whether some file was renamed, is to compute what Git calls a similarity index.  If the similarity index of the old file and the new file is high enough—meets or exceeds a 50%-similar threshold—Git will declare that the file was renamed, rather than deleting the left-side file (liste.txt) and creating an entirely new and different right-side file (listes/listes.txt).
You can control this rename similarity threshold, using -X find-renames=number.  You can also, as in matt's answer, disable rename detection entirely, using -X no-renames.  That's useful if Git is mis-classifying something as a rename when it shouldn't—but if there are some renames that Git should find, you'll have to deal with them yourself.
In general, Git's similarity detection works pretty well on large files.  The reason it works so poorly on your sample file is that your sample file is tiny, and too many lines are too different.


text:
Q: Why does io.BytesIO prepend a null byte on truncate/flush? I'm trying to migrate a python 2 project to be python 3 compatible, and got hung up when it was harder than expected to replace a StringIO.StringIO with io.BytesIO. After a lot of debugging I think the problem comes down to this difference in behaviors:
Using StringIO.StringIO:
>>> sys.executable
'/Users/michael/.pyenv/versions/2.7.17/bin/python'
>>> s = StringIO.StringIO()
>>> s.truncate(0)
>>> s.write('a')
>>> s.flush()
>>> s.seek(0)
>>> s.read()
'a'
>>> s.truncate(0)
>>> s.write('a')
>>> s.flush()
>>> s.seek(0)
>>> s.read()
'a'

Using io.BytesIO:
>>> sys.executable
'/Users/michael/.pyenv/versions/2.7.17/bin/python'
>>> b = io.BytesIO()
>>> b.truncate(0)
0L
>>> b.write('a')
1L
>>> b.flush()
>>> b.seek(0)
0L
>>> b.read()
'a'
>>> b.truncate(0)
0L
>>> b.write('a')
1L
>>> b.flush()
>>> b.seek(0)
0L
>>> b.read()
'\x00a'

So you can see the second time through, truncating and flushing the buffer the io.BytesIO object gets a null byte at the beginning, but the StringIO.StringIO one does not.
In Python 3.5.8 I can't use StringIO.StringIO, but in io.BytesIO the behavior is the same (noting I explicitly write b'a').
What causes this null byte to be prepended when I try to continually overwrite an io.BytesIO instance, but not when I use StringIO.StringIO?


text:
Q: libpcap static linking in Centos 6.x I downloaded the Libpcap-1.7.4 library . when i want to run libpcap.o and libpcap.so.1.7.4, the following errors appear:
[root@localhost libpcap-1.7.4]# ./libpcap.a
./libpcap.a: line 1: syntax error near unexpected token `newline'
./libpcap.a: line 1: `!<arch>'
[root@localhost libpcap-1.7.4]# ./libpcap.so.1.7.4
Segmentation fault (core dumped)

Could you give me some advice about what I should do?
OS: Centos 6.x

A:
Could you give me some advice about what I should do?

Not try to run libpcap - it's a library, not a program, so you can't run it, you can only link a program with it.
What you need to do is link a program with it, and then run the program.
For example, if you have a C source file named small_sniffer.c, and you want to compile it and link it with libpcap, try
gcc -o small_sniffer small_sniffer.c -lpcap

for dynamic linking and
gcc -static -o small_sniffer small_sniffer.c -lpcap

to link entirely statically


text:
Q: Create a matrix of scatterplots (pairs() equivalent) in ggplot2 Is it possible to plot a matrix of scatter plots with ggplot2, using ggplot's nice features like mapping additional factors to color, shape etc. and adding smoother?
I am thinking about something similar to the base function pairs.

A: You might want to try plotmatrix:
  library(ggplot2)
  data(mtcars)
  plotmatrix(mtcars[,1:3])

to me mpg (first column in mtcars) should not be a factor. I haven't checked it, but there's no reason why it should be one. However I get a scatter plot :)

Note: For future reference, the plotmatrix() function has been replaced by the ggpairs() function from the GGally package as @naught101 suggests in another response below to this question.

A: Try scatterPlotMatrix. It's very flexible and produces nice looking interactive charts.
library(scatterPlotMatrix)
scatterPlotMatrix(iris, zAxisDim = "Species")

A: I keep wanting to do this, but plotmatrix is crap. Hadley recommends using the GGally package instead. It has a function, ggpairs that is a vastly improved pairs plot (lets you use non-continuous variables in your data frames). It plots different plots in each square, depending on the variable types:
library(GGally)
ggpairs(iris, aes(colour = Species, alpha = 0.4))

A: If one wants to obtain a ggplot object (not ggmatrix as in case of ggpairs()), the solution is to melt the data twice, then ggplot with facetting. facet_wrap would be better than facet_grid in limiting the plotted area, given the scales = 'free' parameter is supplied.
require(ggplot2)
require(dplyr)
require(tidyr)

gatherpairs <- function(data, ...,
                        xkey = '.xkey', xvalue = '.xvalue',
                        ykey = '.ykey', yvalue = '.yvalue',
                        na.rm = FALSE, convert = FALSE, factor_key = FALSE) {
  vars <- quos(...)
  xkey <- enquo(xkey)
  xvalue <- enquo(xvalue)
  ykey <- enquo(ykey)
  yvalue <- enquo(yvalue)

  data %>% {
    cbind(gather(., key = !!xkey, value = !!xvalue, !!!vars,
                 na.rm = na.rm, convert = convert, factor_key = factor_key),
          select(., !!!vars))
  } %>% gather(., key = !!ykey, value = !!yvalue, !!!vars,
               na.rm = na.rm, convert = convert, factor_key = factor_key)
}

iris %>%
  gatherpairs(Sepal.Length, Sepal.Width, Petal.Length, Petal.Width) %>% {
  ggplot(., aes(x = .xvalue, y = .yvalue, color = Species)) +
      geom_point() +
      geom_smooth(method = 'lm') +
      facet_wrap(.xkey ~ .ykey, ncol = length(unique(.$.ykey)), scales = 'free', labeller = label_both) +
      scale_color_brewer(type = 'qual')
}


text:
Q: Redirect from typing URL in address bar Let's start with an example,
I have domain (abc.com), and have page abc.com/data-list.
I want to disable user from typing in address bar abc.com/data-list because I used javascript to access content section or refresh content section without refreshing master page. So URL in browser not change and stay at abc.com but in content there is change. If user type abc.com/data-list in address bar, master page is not loaded and only show content without css or js from master page. Any Idea?
How to redirect url from typing in address bar? ex: if user type abc.com/data-list it will redirect to abc.com, but if abc.com/data-list accessed from backend (like from href) there is not redirect to abc.com
Or any correct way to implement refresh content only without refreshing master page with url change depend on it's content?
Thanks

A: Add a HTTP parameter to the backend redirect to the page. Then on the data-list page, before loading the content, check from the backend if the HTTP parameter was passed. If it is not defined, then the user likely accessed from a URL, and you can redirect the user to the main site.

A: If you are trying to only allow ajax calls then laravel provides a convenient method on the Request class to check if it is an ajax call. you can also create a Middleware so that you can conveniently put it into multiple routes.
// inside your controller function or middleware's handle function

if(!$request->ajax()) { // request assumed to be accessible from parameter
  return redirect('/');
}


text:
Q: Отцентровать изображение Как можно отцентровать изображение чтоб оно постоянно не прыгало то вверх то вниз ?
html файл

ЦГОК.РОФ.Фильтрация

        <object id="map-svg" type="image/svg+xml" data="images/FILTRATION_MAIN_1.svg"  height="860px"></object>

css
body, html {
          max-width: 100%;
          max-height: 100%;
          margin: 0;
          font-family: helvetica;
          color: #000000;
          background: black;
}
#map-svg{

    display:block;
    margin:50px auto 20px;
}
header{
    text-align: center;
    color: black;
    background: white;
    font-size: 30px;
}

A: Для отцентровки чего либо в css лучше использовать flexbox. На примере снизу вывел блок который по отношению к его родителю всегда будет по центру.

html, body{
  height: 100%;
}

.parent{
  width: 100%;
  height: 100%;
  background: blue;
  display: flex;
  justify-content: center;
  align-items: center;
}

.children{
  width: 50px;
  height: 50px;
  background: red;
}


text:
Q: Azure AD Graph client library batch processing Could some one tell me whether I can use the batch processing to add group memberships?
if yes can you please give me an example
thanks in advance
kind regards,
Snegha

A: According to the documentation, Graph API support batch processing. The Microsoft Azure Active Directory Client support batch processing.
You can find a lot of samples to use the Azure AD Graph API here :

*

*Azure Samples for active directory
Especially you have a full sample on most of the actions that you can perform with the Graph API here :

*

*Call the Azure AD Graph API from a native client (search for "Batch Operations" in the program.cs file).

Unfortunately batch processing is not working for navigation properties or at least I did not find a way to make it work...
So let's have a look at the documentation.

Graph API support for OData batch requests:

*

*A query is a single query or function invocation.

*A change set is a group of one or more insert, update, or delete operations, action invocations, or service invocations.

*A batch is a container of operations, including one or more change sets and query operations.

  The Graph API supports a subset of the functionality defined by the
  OData specification:

*

*A single batch can contain a maximum of five queries and/or change sets combined.

*A change set can contain a maximum of one source object modification and up to 20 add-link and delete-link operations
  combined. All operations in the change set must be on a single source
  entity.

Here is the batch request syntax :
https://graph.windows.net/TenantName/$batch?api-version=1.6

A batch request is sent to the server with a single POST directive.
The payload is a multi-part MIME message containing the batch and its constituent queries and change sets. The payload includes two types of MIME boundaries:

*

*A batch boundary separates each query and/or change set in the batch.

*A change set boundary separates individual operations within a change set.

An individual request within a change set is identical to a request made when that operation is called by itself. (here is a sample request)
You can find here the full sample code : azure-active-directory-batchprocessing
So Basically, you need to obtain the authentication token:
var authority = "https://login.microsoftonline.com/mytenantName.onmicrosoft.com";
var resource = "https://graph.windows.net/";
var clientId = "ClientId of the application in the Azure Active Directory";
var clientSecret = "ClientSecret of the application in the Azure Active Directory";

var token = new AuthenticationContext(authority, false).AcquireToken(resource,
        new ClientCredential(clientId, clientSecret)).AccessToken;

In your question you'd like to add member to a group (see Graph API Documentation on groups):
// Get the objectId of the group
var groupId = ...

// Get the member ids you'd like to add to the group
var memberIds = ...

Here is the code to add members to a group:
private static async Task AddMemberToGroup(string token, string groupId, IList<string> memberIds)
{
    if (memberIds.Count > 100)
    {
        // A batch can contain up to 5 changesets. Each changeset can contain up to 20 operations.
        throw new InvalidOperationException("Cannot send more than 100 operation in an batch");
    }

    var batch = new BatchRequest("https://graph.windows.net/MyTenantName.onmicrosoft.com");

    // A changeset can contain up to 20 operations
    var takeCount = 20;
    var skipCount = 0;
    var take = memberIds.Skip(skipCount).Take(takeCount).ToList();
    while (take.Count > 0)
    {
        AddChangeset(batch, groupId, take);
        skipCount += takeCount;
        take = memberIds.Skip(skipCount).Take(takeCount).ToList();
    }

    using (var client = new HttpClient())
    {
        client.DefaultRequestHeaders.Add("Authorization", $"Bearer {token}");
        var response = await client.SendAsync(batch.Request);
    }
}

private static void AddChangeset(BatchRequest batch, string groupId, IEnumerable<string> memberIds)
{
    var changeset = batch.AddChangeSet();
    foreach (var memberId in memberIds)
    {
        // Create the HttpRequest to add a member to a group
        var request = AddMemberToGroupRequest(groupId, memberId);

        // Add the operation to the changeset
        changeset.AddOperation(request);
    }
}

private static HttpRequestMessage AddMemberToGroupRequest(string groupId, string memberId)
{
    // Create a request to add a member to a group
    var request = new HttpRequestMessage(HttpMethod.Post,
        $"https://graph.windows.net/MyTenantName.onmicrosoft.com/groups/{groupId}/$links/members?api-version=1.6");

    // Create the body of the request
    var jsonBody =
        JsonConvert.SerializeObject(new DirectoryObject($"https://graph.windows.net/MyTenantName.onmicrosoft.com/directoryObjects/{memberId}"));

    // Set the content
    request.Content = new StringContent(jsonBody, Encoding.UTF8, "application/json");

    // Return the request
    return request;
}

public class BatchRequest
{
    private readonly MultipartContent _batchContent;

    public BatchRequest(string tenantUrl)
    {
        // Create the batch request
        Request = new HttpRequestMessage(HttpMethod.Post,
            $"{tenantUrl}/$batch?api-version=1.6");

        // Initializes the batch content
        _batchContent = new MultipartContent("mixed", "batch_" + Guid.NewGuid());
        Request.Content = _batchContent;
    }

    public HttpRequestMessage Request { get; }

    public ChangeSet AddChangeSet()
    {
        // Create a new changeset
        var changeSet = new ChangeSet();

        // Add the content of the changeset to the batch
        _batchContent.Add(changeSet.Content);

        // return the changeset
        return changeSet;
    }

    public HttpMessageContent CreateOperation(HttpRequestMessage request)
    {
        var content = new HttpMessageContent(request);
        content.Headers.ContentType = new MediaTypeHeaderValue("application/http");
        content.Headers.Add("Content-Transfer-Encoding", "binary");
        return content;
    }
}

public class ChangeSet
{
    public ChangeSet()
    {
        Content = new MultipartContent("mixed", "changeset_" + Guid.NewGuid());
    }

    public MultipartContent Content { get; }

    public void AddOperation(HttpRequestMessage request)
    {
        var operationContent = new HttpMessageContent(request);
        operationContent.Headers.ContentType = new MediaTypeHeaderValue("application/http");
        operationContent.Headers.Add("Content-Transfer-Encoding", "binary");
        Content.Add(operationContent);
    }
}

public class DirectoryObject
{
    public DirectoryObject(string url)
    {
        this.url = url;
    }
        public string url { get; }
}


text:
Q: Calculating Intitial Position given the ratio between the last two seconds of free fall for 1D motion I've tried this problem in multiple different ways and can't seem to come up with an acceptable answer. The question is,

A rock is dropped from the top of a tall building. The rock's displacement in the last second before it hits the ground is 48 % of the entire distance it falls.

I tried using kinematic equations to resolve this in multiple different ways.
For example, setting the position function at t-1 equal to .48 times the position function of t, and then solving for t. I then plugged in t into the position function, and got 52m, which is not correct.
Our textbook was kind enough to give a similar problem, except it used 45% and got the height to be equal to 73m.
What is the proper way to go about solving this problem? What am I doing wrong?

A: This necro-bumped question deserves an answer that touches the delicate matter of finding the right solution when many roots exist.
In most cases, the "wrong" solutions can still be understood what they would hypothetically mean, even if they have no physical realization.
Let's say the time gap (last second) is $t_0$ and the displacement ratio to the total height is $\eta =z/h$ (to avoid explicit numbers).
We have
$$h=\frac12 gt^2;\quad \eta h=\frac12 g(t-t_0)^2$$
Subtracting these, we obtain
$$h(1-\eta)=\frac12 g(2tt_0-t_0^2)$$
Plug it back into the first equation:
$$\frac12 g(2tt_0-t_0^2)\frac{1}{1-\eta}=\frac12 gt^2$$
Cancel and rearrange:
$$(1-\eta)t^2-2tt_0+t_0^2=0$$
Solve:
$$t=t_0\frac{1\pm \sqrt\eta}{1-\eta}=t_0\frac{1}{1\mp\sqrt{\eta}}$$
Your numbers $\eta=0.48$ and $t_0=1\,\rm s$ give solutions $t=\{3.3{\,\rm s},0.6{\,\rm s}\}$
Here, we have to discard the second solution, as it would measure the height between times 0.6s and -0.4s, which was before the fall started (where it would have been, if it wasn't just dropped from the top but thrown upwards, and we just started the clock at the highest position).
If we plug both solutions into the first height equation $\frac12 gt^2$, we get
$$\color{green}{ h(3.3{\,\rm s})=52\,\rm m},\quad \color{red}{h(0.6{\,\rm s})=1.7\,\rm m}$$
Notice how the first solution (computed by the original poster) is correct, as the second one corresponds to the one where the travel time is shorter than the measurement interval.

A: Given the standard kinematics equation $$h = \frac{1}{2} g t^2$$ you have two unknowns, the time $t$ and height $h$.
But with the additional piece of information you can create another equation $$ 0.48 h = \frac{1}{2} (t-1)^2$$ for the same two unknowns.
So two non-linear equations and two unknowns. You  subtract one from the other
$$ h - 0.48 h = \frac{1}{2} g ( t^2 - (t-1)^2 ) $$ to results in a linear relationship between $h$ and $t$ and then use one of the original equations to solve the problem. But the solution will have two roots. It makes sense to pick the one with the least time of the two, and that is not the one with 52m as the answer.


text:
Q: Hook the resolution of assemblies and types loaded in a Xaml context for a good reason we are prefixing our assemblies, with a prefix specific to each application :
e.g. if we have a project named "A" which is a dependency of an application named "MyApplication1" the latest will use a "MA1.A" assembly generated at build-time;
if another application "MyApplication2" has also a dependency on "A" we will transform the output of "A" as "MA2.A" when building the application...
So far so good.
Now we are starting to use WPF and we need to reference some types of "A" in the Xaml :
xmlns:a="clr-namespace:Some.Name.Space;assembly=A"

This is fine at design-time but at runtime there is no more "A" assembly but a "MA1.A" or "MA2.A" assembly,
so the application crashes.
Do you have any idea to workaround this issue without affecting too deeply the development process ?
E.g. loading the Xaml by hand and setting the prefix is not an acceptable solution.
Thanks in advance for any idea.

A: The .NET run-time needs to know what assemblies your assembly depends on. That is why you refer to the assemblies in code so the run-time knows where to find the class(es).
If you decide to rename the classes you will have to inform the CLR of the rename action.
The only way I see is by editing the source code or redirecting at run-time but WPF doesn't like that

for a good reason we are prefixing our assemblies

As much as I would like to believe you; I strongly suggest that you keep the names at compile time equal to the run-time version. It will be much easier to debug and trace errors. But as you didn't mention the reason I might be wrong here.


text:
Q: Analyticity of $f$ in $D$: $|z| < 1$ such that $|f(z)| \leq 1$. $f$ is analytic in $D$: $|z| < 1$ such that $|f(z)| ≤ 1$. $g$: $D → C$ is given by $g(z) = f(z)/z$ when $z \neq 0$ & $f'(0)$ when $z = 0$. Then which of the followings are true:
1) $g$ is analytic on $D$.
2) $|g(z)| ≤ 1$ on $D$.
3) $|f'(z)|≤ 1$ on $D$.
4) $|f'(0)| ≤ 1$.
I used the Taylor series representation of $f$ on $D$ but couldn't come to any conclusion.

A: For (i) and (ii), consider the function $f(z) = z/2+1/2$ on the unit disc, certainly $|f(z)|\le |z|/2+1/2 \le 1$, but $g(z)=1/2+1/(2z)$ has a pole at the origin and so cannot be analytic and $|g(z)|$ is not bounded.
For (iii)  Sugata Adhya provides a counter example.
So (iv) has to be correct, and it follows form lee's suggestion:
recall the Cauchy integral formula for the derivatives:
$$
f^{'}(0) = \frac{n!}{2\pi i }\int_{\partial B(0,r)} \frac{f(z)}{z^2}dz.
$$
where $r<1$ so the ball $B(0,r)$ lies in the unit circle.
Using the standard estimation, we have
$$
|f'(0)|\le \frac{1}{2\pi}(2\pi r) \max_{|z|=r}\{\frac{|f(z)|}{|z|^2}\} \le \frac{1}{r}
$$
since $|f(z)|\le 1$.
Because this is true for every $r < 1$, passing to the limit shows $|f'(0)|\le 1$.


text:
Q: Sorting out similar values in the same column SQL I'm trying to categorize data that seem to similar from my database table.
Here's how the table looks like

id
account

1
011

2
11

3
023

4
23

5
456

I need a select query that will categorize my data as in the table below ignoring the unique values.
I can achieve this in pandas but I would appreciate if I also learn how to achieve the same in SQL

id
account1
account2

1
011
11

2
023
23

A: with data as (
  select
    id,
    account as account1,
    last_value(account) over (partition by account::numeric) as account2
  from your_table
)
select id, account1, account2 from data where account1 != account2;

A: It is not an obvious

*

*data type;

*what mean account2 field the result table;

*which data must place in id field the result table;

Below is the quick and duty solution.
In subquery count unique data by count(*) agregate function.
SELECT id, account::INTEGER
FROM
(select *, count(account::INTEGER) over (partition by account::INTEGER) as count from
(VALUES
(1, '011'),
(2, '11'),
(3, '023'),
(4, '23'),
(5, '456')
) as "ID"(id, account)) as "ID"(id, account)
where count > 1

A: Well the simple answer is properly store account as data type numeric or integer, then just check for duplicates, remove them, and finally put a unique constraint on account - done problem solved. But assuming I will hear I can not change the database becomes a different story. The first thing you need is filter out any non-numeric account values (may just be me but I never trust text columns to actually contain numeric data). Then with that out-of-the-way do a self on the remaining and assign the new id. The result becomes: (see demo)
with num_acct (id, account) as
     (select *
        from test
       where account ~ '^[0-9]+$'
     )
select row_number() over() as id
     , na1.account as account1
     , na2.account as account2
  from num_acct na1
  join num_acct na2
    on (    na1.account::integer = na2.account::integer
        and na1.id < na2.id
       );


text:
Q: Defining a pointer to an OpenGL Vertex Array Object Consider the following OpenGL code snippet:
GLuint vao;
glCreateVertexArrays(1, glBindVertexArray(&vao));

I'm under the impression that what this code does is

*

*Creates a pointer, of type GLuint, that will eventually point to an OpenGL Vertex Array Object. The name of this pointer is vao.

*Indirectly allocates memory through OpenGL for the actual Vertex Array Object (i.e., no use of malloc in C or new in C++). The way that this is done is through the function glCreateVertexArrays. This function also makes the pointer vao point to the Vertex Array Object.

Is my understanding correct? If so, in (1), why is the type of the pointer GLuint and not explicitly defined as a pointer type (for example with * in C/C++ or with the OpenGL type GLintptr)?

A: This code is invalid, glBindVertexArray returns void so you cannot pass its return value as a parameter to glCreateVertexArrays, because there is none.
The correct way to create a VAO, as per OpenGL 4.5 profile, is:
GLuint vao;
glCreateVertexArrays(1, &vao);

As per the meaning of vao and why its type is GLuint: it is not a pointer. It is an opaque value that is used internally to locate the VAO inside the OpenGL implementation tables. The driver may allocate memory on both, the CPU and/or GPU for storing the state associated with the VAO. It is a complex state with quite a lot of book-keeping, which is much more involved than malloc or new. (In particular malloc can't be used to allocate GPU memory.)


text:
Q: retrieving archive from glacier using aws cli Im looking for a way to retrieve archive from glacier, and ended up with below error. couldnt get an idea about "Range is not megabyte aligned" error i'm getting.
#aws glacier initiate-job --account-id - --vault-name first-vault --job-parameters file://job-archive-retrieval_1.json
A client error (InvalidParameterValueException) occurred when calling the InitiateJob operation: Invalid range RetrievalByteRange [0, 536870912] Range is not megabyte aligned

cat job-archive-retrieval_1.json
{
        "Type": "archive-retrieval",
        "ArchiveId": "XXXXXX",
        "Description": "Retrieve archive on 2016-08-09 Part 1",
        "RetrievalByteRange": "0-536870912"
}

cat job-archive-retrieval_2.json
{
        "Type": "archive-retrieval",
        "ArchiveId": "XXXXXX",
        "Description": "Retrieve archive on 2016-08-09 Part 2",
        "RetrievalByteRange": "536870913-1073741823"
}

Any help ?
What I'm trying to do is, to download 1GB test file from Glacier vault, as 2 chunks (512MB) each in 2 jobs, and combine the file into one. Couldn't figure out how to specify the size aligned with MB. This is a testing scenario, and cost doesn't matter.

A: If you choose to provide retrieval byte parameter, it must be in the form StartByte-EndByte. The value provided for StartByte must be megabyte aligned (a multiple of 1,048,576). The value provided for EndByte + 1 must be megabyte aligned if you are retrieving data from somewhere within the archive. If you want to retrieve data from StartByte up to the end of the archive, simply specify a value that is one less than the archive size.
So I guess 0-536870912 should be 0-536870911 and 536870913-1073741823 should be 536870912-1073741823.