text:
Q: How to write NDEF records to NFC tag? How do I write NDEF message to NFC tag?
Do I have to change manifest file?
So far I have code to generate NDEF message:
    public NdefRecord createTextRecord(String payload, Locale locale, boolean encodeInUtf8) {
    byte[] langBytes = locale.getLanguage().getBytes(Charset.forName("US-ASCII"));
    Charset utfEncoding = encodeInUtf8 ? Charset.forName("UTF-8") : Charset.forName("UTF-16");
    byte[] textBytes = payload.getBytes(utfEncoding);
    int utfBit = encodeInUtf8 ? 0 : (1 << 7);
    char status = (char) (utfBit + langBytes.length);
    byte[] data = new byte[1 + langBytes.length + textBytes.length];
    data[0] = (byte) status;
    System.arraycopy(langBytes, 0, data, 1, langBytes.length);
    System.arraycopy(textBytes, 0, data, 1 + langBytes.length, textBytes.length);
    NdefRecord record = new NdefRecord(NdefRecord.TNF_WELL_KNOWN,
            NdefRecord.RTD_TEXT, new byte[0], data);
    return record;
}

How do I discover the TAG?
Can someone help me with that?

A: I would ignore what the Google documentation says for reading at https://developer.android.com/guide/topics/connectivity/nfc/nfc and for read/write at https://developer.android.com/guide/topics/connectivity/nfc/advanced-nfc#read-write as this provides a very poor user experience for writing to Tags and leads to a lot of failed writes because of user behaviour.
To get reliable writing to NFC with Android you should use the newer and much better enableReaderMode API https://developer.android.com/reference/android/nfc/NfcAdapter
Using this newer API leads to a lot less failed writes and corrupted cards because you can control when the notification sound happens. With the old Intent based system the system App pauses your app and then reads the card and makes a notification sound, the user then takes the card way before your App is resumed and has a chance to handle the card data and write to the card.
With the newer enableReaderMode API you turn off the system notification sound and your App is never paused to read the NFC card, you can then read and write to the card and then when you have successfully written to the card you can make the notification sound yourself.
Because any errors are silent, the user will keep trying to present the card until the success Notification. Additional logic is needed not to write the same message to every time a single card is presented or when different cards are presented.
Some example code (adapted from my app the does NFC low level reading and writing (not Ndef Tag technology))

public class NFCActivity extends AppCompatActivity implements NfcAdapter.ReaderCallback{

private NfcAdapter mNfcAdapter;

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

        mNfcAdapter = NfcAdapter.getDefaultAdapter(this);

        // Rest of Activity setup
     }

@Override
    protected void onResume() {
        super.onResume();

        if(mNfcAdapter!= null) {
            Bundle options = new Bundle();
            // Work around for some broken Nfc firmware implementations that poll the card too fast
            options.putInt(NfcAdapter.EXTRA_READER_PRESENCE_CHECK_DELAY, 250);

            // Enable ReaderMode for all types of card and disable platform sounds
            mNfcAdapter.enableReaderMode(this,
                    this,
                    NfcAdapter.FLAG_READER_NFC_A |
                            NfcAdapter.FLAG_READER_NFC_B |
                            NfcAdapter.FLAG_READER_NFC_F |
                            NfcAdapter.FLAG_READER_NFC_V |
                            NfcAdapter.FLAG_READER_NFC_BARCODE |
                            NfcAdapter.FLAG_READER_NO_PLATFORM_SOUNDS,
                    options);
        }

    }

    @Override
    protected void onPause() {
        super.onPause();
        if(mNfcAdapter!= null)
            mNfcAdapter.disableReaderMode(this);
    }

   // This method is run in another thread when a card is discovered
   // !!!! This method cannot cannot direct interact with the UI Thread
   // Use `runOnUiThread` method to change the UI from this method
   public void onTagDiscovered(Tag tag) {

      // Read and or write to Tag here to the appropriate Tag Technology type class
      // in this example the card should be an Ndef Technology Type
      Ndef mNdef = Ndef.get(tag);

      // Check that it is an Ndef capable card
      if (mNdef!= null) {

      // If we want to read
      // As we did not turn on the NfcAdapter.FLAG_READER_SKIP_NDEF_CHECK
      // We can get the cached Ndef message the system read for us.

      NdefMessage mNdefMessage = mNdef.getCachedNdefMessage();

      // Or if we want to write a Ndef message

      // Create a Ndef Record
      NdefRecord mRecord = NdefRecord.createTextRecord("en","English String");

      // Add to a NdefMessage
      NdefMessage mMsg = new NdefMessage(mRecord);

      // Catch errors
      try {
          mNdef.connect();
          mNdef.writeNdefMessage(mMsg);

          // Success if got to here
          runOnUiThread(() -> {
             Toast.makeText(getApplicationContext(),
               "Write to NFC Success",
               Toast.LENGTH_SHORT).show();
          });

          // Make a Sound
          try {
              Uri notification = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
              Ringtone r = RingtoneManager.getRingtone(getApplicationContext(),
                  notification);
              r.play();
              } catch (Exception e) {
                 // Some error playing sound
              }

      } catch (FormatException e) {
        // if the NDEF Message to write is malformed
      } catch (TagLostException e) {
        // Tag went out of range before operations were complete
      } catch (IOException e){
        // if there is an I/O failure, or the operation is cancelled
      } finally {
        // Be nice and try and close the tag to
        // Disable I/O operations to the tag from this TagTechnology object, and release resources.
         try {
                mNdef.close();
             } catch (IOException e) {
               // if there is an I/O failure, or the operation is cancelled
             }
      }

   }

}


text:
Q: dynamically create accordion from jquery I have only a div in html page and i am trying to create an accordion from jQuery. But this does not happen.
HTML Code:

Java Script:
$(document).ready(function(){
    $('#accordion').append("

FirstFloor

First Floor details

");
});

JSFIDDLE

A: Your append string needs to be terminated with single quotes since you are using double quotes with it. Also you need to include Jquery library. If you are using the jquery accordion you also need to include the Jquery UI library.
Also your html is a bit off, here is a working example.
$('document').ready(function(){

$('#accordion').append('
First Floor

Welcome to da first floor.

Floor numbah 2

you are now on floor 2

');
$( "#accordion" ).accordion();

});

http://jsfiddle.net/EEnSb/19/

redpajama_set_name: RedPajamaStackExchange


text:
Q: Как сделать чтоб объект двигался в любом направлении? Захотелось украсить свою 3D игру разными питомцами, и для красоты сделать чтоб они и передвигались, а не стояли как камень.
Например как в Minecraft, там животные передвигаются куда хотят.
Как это сделать? Если надо -  моя версия Unity является 2019.4.29f1. Выше версию скачать нету возможности. Прошу помочь.

A: Может быть, взять координаты питомца, вычислить случайное число (допустим от 1 до 10 метров), выбрать траекторию (тоже случайно), и плавно изменять координаты питомца, а после достижения цели подождать немного и сделать все с начала?


text:
Q: How to make a long vibration in iOS I want to make a button that you press and your phone vibrates. When you release, the vibration should stop. Ideally, it will have touch sensitivity, so the harder you press, the stronger the buzz.
AudioServicesPlaySystemSound(kSystemSoundID_Vibrate)

Currently this just plays 1 buzz, and a loop still has a slight disconnect, but a loop is still an unwanted workaround.

A: Apparently, you can make the phone vibrate with:
import UIKit
import AudioToolbox

class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        AudioServicesPlayAlertSound(SystemSoundID(kSystemSoundID_Vibrate))
    }

}

(This example is from a post here)
If you wanted vibration to be indefinite and continuous, you could use timers to play it in sequence. But apparently, this is a common cause of app rejection from the App store, so I wouldn't recommend it.
I'm not sure if there's an API for increasing the velocity of haptic feedback/system vibrate.


text:
Q: Android 2.3: HttpClient SSL certificate problem: Intermediate certificate lacks BasicConstraints I'm running into a problem using this method to address a "javax.net.ssl.SSLPeerUnverifiedException: No peer certificate" exception encountered using HttpClient 4. This, however, caused the following javax.net.ssl.SSLHandshakeException: java.security.cert.CertPathValidatorException:
System.err  W  javax.net.ssl.SSLHandshakeException: java.security.cert.CertPathValidatorException: Intermediate certificate lacks BasicCon
               straints
System.err  W   at org.apache.harmony.xnet.provider.jsse.OpenSSLSocketImpl.startHandshake(OpenSSLSocketImpl.java:477)
System.err  W   at org.apache.harmony.xnet.provider.jsse.OpenSSLSocketImpl$SSLInputStream.<init>(OpenSSLSocketImpl.java:750)
System.err  W   at org.apache.harmony.xnet.provider.jsse.OpenSSLSocketImpl.getInputStream(OpenSSLSocketImpl.java:692)
System.err  W   at org.apache.http.impl.io.SocketInputBuffer.<init>(SocketInputBuffer.java:93)
System.err  W   at org.apache.http.impl.SocketHttpClientConnection.createSessionInputBuffer(SocketHttpClientConnection.java:83)
System.err  W   at org.apache.http.impl.conn.DefaultClientConnection.createSessionInputBuffer(DefaultClientConnection.java:170)
System.err  W   at org.apache.http.impl.SocketHttpClientConnection.bind(SocketHttpClientConnection.java:106)
System.err  W   at org.apache.http.impl.conn.DefaultClientConnection.openCompleted(DefaultClientConnection.java:129)
System.err  W   at org.apache.http.impl.conn.DefaultClientConnectionOperator.openConnection(DefaultClientConnectionOperator.java:171)
System.err  W   at org.apache.http.impl.conn.AbstractPoolEntry.open(AbstractPoolEntry.java:164)
System.err  W   at org.apache.http.impl.conn.AbstractPooledConnAdapter.open(AbstractPooledConnAdapter.java:119)
System.err  W   at org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:359)
System.err  W   at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:555)
System.err  W   at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:487)
System.err  W   at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:465)
System.err  W   at com.example.activities.AuthTest.onCreate(AuthTest.java:69)
System.err  W   at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)
System.err  W   at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1722)
System.err  W   at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1784)
System.err  W   at android.app.ActivityThread.access$1500(ActivityThread.java:123)
System.err  W   at android.app.ActivityThread$H.handleMessage(ActivityThread.java:939)
System.err  W   at android.os.Handler.dispatchMessage(Handler.java:99)
System.err  W   at android.os.Looper.loop(Looper.java:130)
System.err  W   at android.app.ActivityThread.main(ActivityThread.java:3835)
System.err  W   at java.lang.reflect.Method.invokeNative(Native Method)
System.err  W   at java.lang.reflect.Method.invoke(Method.java:507)
System.err  W   at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:847)
System.err  W   at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:605)
System.err  W   at dalvik.system.NativeStart.main(Native Method)
System.err  W  Caused by: java.security.cert.CertificateException: java.security.cert.CertPathValidatorException: Intermediate certificate
                lacks BasicConstraints
System.err  W   at org.apache.harmony.xnet.provider.jsse.TrustManagerImpl.checkServerTrusted(TrustManagerImpl.java:161)
System.err  W   at com.example.models.EasyX509TrustManager.checkServerTrusted(EasyX509TrustManager.java:80)
System.err  W   at org.apache.harmony.xnet.provider.jsse.OpenSSLSocketImpl.verifyCertificateChain(OpenSSLSocketImpl.java:664)
System.err  W   at org.apache.harmony.xnet.provider.jsse.NativeCrypto.SSL_do_handshake(Native Method)
System.err  W   at org.apache.harmony.xnet.provider.jsse.OpenSSLSocketImpl.startHandshake(OpenSSLSocketImpl.java:474)
System.err  W   ... 28 more
System.err  W  Caused by: java.security.cert.CertPathValidatorException: Intermediate certificate lacks BasicConstraints
System.err  W   at org.bouncycastle.jce.provider.RFC3280CertPathUtilities.prepareNextCertK(RFC3280CertPathUtilities.java:2127)
System.err  W   at org.bouncycastle.jce.provider.PKIXCertPathValidatorSpi.engineValidate(PKIXCertPathValidatorSpi.java:384)
System.err  W   at java.security.cert.CertPathValidator.validate(CertPathValidator.java:197)
System.err  W   at org.apache.harmony.xnet.provider.jsse.TrustManagerImpl.checkServerTrusted(TrustManagerImpl.java:156)
System.err  W   ... 32 more

I got around that by commenting out the following else block found in EasyX509TrustManager.java:
public void checkServerTrusted( X509Certificate[] certificates, String authType )
    throws CertificateException
{
    if ( ( certificates != null ) && ( certificates.length == 1 ) )
    {
        certificates[0].checkValidity();
    }
    //else
    //{
    //    standardTrustManager.checkServerTrusted( certificates, authType );
    //}
}

Voila! And everything works as it should. The problem is that I really have no idea what the "Intermediate certificate lacks BasicCosntraints" exception means or if commenting out that else block introduces a security risk where I may be trusting invalid certificates.
The original SSLPeerUnverifiedException did not occur on either Android 2.1 or 2.2, so this seems to be just a problem on Android 2.3+.
Could someone please help me understand what exactly that exception means? And if this is a security risk, how would I begin to go about resolving this issue?

A: Basic constraints specify whether a certificate can issue other certificates (is it Certificate Authority; technically can its public key sign other certificates), and whether the certificates it issued can in turn issue other certificates (who long the chain can be). So if some one fakes it, you can be made to use/trust a certificate issued by someone who is not supposed to issue certificates in the first place. Commenting out checkServerTrusted is bad: you are basically saying: I don't care whose certificate this is, as long as it's not broken and not expired. This kind of defeats the purpose, because anyone can issue a valid certificate.
Possibly 2.1 and 2.2 didn't care about checking constraints and 2.3 started to and that is why you are getting an error. Can you post a link to those certificates?
All the gory details are in RFC 3280.


text:
Q: JPA automatic refresh after save My setup is Spring JPA / Hibernate / Oracle.
There's a trigger in the DB that performs some basic operation on multiple fields in a row (e.g. perform rounding on a decimal saved as string).
Naturally, when I save said row from the ORM, it doesn't pick up the changes made by the trigger, unless I do an em.refresh(myRow).
Since I am using interfaces extending JpaRepository, I can only do that wherever the repos are being used (or implement this particular repository and override the save methods).
There is also a @Generated annotation from Hibernate which might work, although it's more like a hack, since that's not what it was made for.
Can it be done in any other way?


text:
Q: Subtypes and default values in ArcGIS Online I am trying to create subtypes with default values for ArcGIS Online. So far, I've not gotten success when published to ArcGIS Online. Is it true to assume that ArcGIS Online doesn't support subtypes and default values?

A: To get dropdowns and default values for new features, try creating a feature template for each subtype.
In ArcMap, right click the current template in the Create Features window, and select copy. Then adjust the values accordingly.
Or in ArcGIS Online, after opening the add new features panel, hit Manage at the bottom right of the panel, then hit Add new Type of Feature.
This support article may also be helpful: http://support.esri.com/technical-article/000012361


text:
Q: Criando Collections do Azure Cosmos DB Bom eu estava criando uma Poc com Interface Genérica para manipulação dos meus dados, mas tive dificuldades de fazer com WebApi MVC, fiz com bom e velho MVC. Mas por toda questão do JSON, creio que perco muito se não trabalhar com REST.
Vocês poderiam me ajudar?
Repositório:
public static class DocumentDBRepository<T> where T : class
{
    private static readonly string DatabaseId = ConfigurationManager.AppSettings["database"];
    private static readonly string CollectionId = ConfigurationManager.AppSettings["collection"];
    private static DocumentClient client;

    public static async Task<T> GetItemAsync(string id)
    {
        try
        {
            Document document = await client.ReadDocumentAsync(UriFactory.CreateDocumentUri(DatabaseId, CollectionId, id));
            return (T)(dynamic)document;
        }
        catch (DocumentClientException e)
        {
            if (e.StatusCode == System.Net.HttpStatusCode.NotFound)
            {
                return null;
            }
            else
            {
                throw;
            }
        }
    }

    public static async Task<IEnumerable<T>> GetItemsAsync(Expression<Func<T, bool>> predicate)
    {
        IDocumentQuery<T> query = client.CreateDocumentQuery<T>(
            UriFactory.CreateDocumentCollectionUri(DatabaseId, CollectionId),
            new FeedOptions { MaxItemCount = -1 })
            .Where(predicate)
            .AsDocumentQuery();

        List<T> results = new List<T>();
        while (query.HasMoreResults)
        {
            results.AddRange(await query.ExecuteNextAsync<T>());
        }

        return results;
    }

    public static async Task<Document> CreateItemAsync(T item)
    {
        return await client.CreateDocumentAsync(UriFactory.CreateDocumentCollectionUri(DatabaseId, CollectionId), item);
    }

    public static async Task<Document> UpdateItemAsync(string id, T item)
    {
        return await client.ReplaceDocumentAsync(UriFactory.CreateDocumentUri(DatabaseId, CollectionId, id), item);
    }

    public static async Task DeleteItemAsync(string id)
    {
        await client.DeleteDocumentAsync(UriFactory.CreateDocumentUri(DatabaseId, CollectionId, id));
    }

    public static void Initialize()
    {
        client = new DocumentClient(new Uri(ConfigurationManager.AppSettings["endpoint"]), ConfigurationManager.AppSettings["authKey"]);
        CreateDatabaseIfNotExistsAsync().Wait();
        CreateCollectionIfNotExistsAsync().Wait();
    }

    private static async Task CreateDatabaseIfNotExistsAsync()
    {
        try
        {
            await client.ReadDatabaseAsync(UriFactory.CreateDatabaseUri(DatabaseId));
        }
        catch (DocumentClientException e)
        {
            if (e.StatusCode == System.Net.HttpStatusCode.NotFound)
            {
                await client.CreateDatabaseAsync(new Database { Id = DatabaseId });
            }
            else
            {
                throw;
            }
        }
    }

    private static async Task CreateCollectionIfNotExistsAsync()
    {
        try
        {
            await client.ReadDocumentCollectionAsync(UriFactory.CreateDocumentCollectionUri(DatabaseId, CollectionId));
        }
        catch (DocumentClientException e)
        {
            if (e.StatusCode == System.Net.HttpStatusCode.NotFound)
            {
                await client.CreateDocumentCollectionAsync(
                    UriFactory.CreateDatabaseUri(DatabaseId),
                    new DocumentCollection { Id = CollectionId },
                    new RequestOptions { OfferThroughput = 1000 });
            }
            else
            {
                throw;
            }
        }
    }
}

Model:
public class Item
{
    [JsonProperty(PropertyName = "id")]
    public string Id { get; set; }

    [JsonProperty(PropertyName = "titulo")]
    public string Titulo { get; set; }

    [JsonProperty(PropertyName = "descricao")]
    public string Descricao { get; set; }

    [JsonProperty(PropertyName = "status")]
    public bool Status { get; set; }
}

Controller:
public class ItemController : Controller
{
    [ActionName("Index")]
    public async Task<ActionResult> IndexAsync()
    {
        var items = await DocumentDBRepository<Item>.GetItemsAsync(d => d.Status);
        if (items != null)
            return View(items);

        return View();
    }

    [ActionName("Create")]
    public async Task<ActionResult> CreateAsync()
    {
        return View();
    }

    [HttpPost]
    [ActionName("Create")]
    [ValidateAntiForgeryToken]
    public async Task<ActionResult> CreateAsync([Bind(Include = "id,titulo,descricao,status")] Item item)
    {
        if (ModelState.IsValid)
        {
            await DocumentDBRepository<Item>.CreateItemAsync(item);
            return RedirectToAction("Index");
        }

        return View(item);
    }

    [HttpPost]
    [ActionName("Edit")]
    [ValidateAntiForgeryToken]
    public async Task<ActionResult> EditAsync([Bind(Include = "id,titulo,descricao,status")] Item item)
    {
        if (ModelState.IsValid)
        {
            await DocumentDBRepository<Item>.UpdateItemAsync(item.Id, item);
            return RedirectToAction("Index");
        }

        return View(item);
    }

    [ActionName("Edit")]
    public async Task<ActionResult> EditAsync(string id)
    {
        if (id == null)
        {
            return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
        }

        Item item = await DocumentDBRepository<Item>.GetItemAsync(id);
        if (item == null)
        {
            return HttpNotFound();
        }

        return View(item);
    }

    [ActionName("Delete")]
    public async Task<ActionResult> DeleteAsync(string id)
    {
        if (id == null)
        {
            return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
        }

        Item item = await DocumentDBRepository<Item>.GetItemAsync(id);
        if (item == null)
        {
            return HttpNotFound();
        }

        return View(item);
    }

    [HttpPost]
    [ActionName("Delete")]
    [ValidateAntiForgeryToken]
    public async Task<ActionResult> DeleteConfirmedAsync([Bind(Include = "id")] string id)
    {
        await DocumentDBRepository<Item>.DeleteItemAsync(id);
        return RedirectToAction("Index");
    }

    [ActionName("Details")]
    public async Task<ActionResult> DetailsAsync(string id)
    {
        Item item = await DocumentDBRepository<Item>.GetItemAsync(id);
        return View(item);
    }
}


text:
Q: Get both min/max value for 24 hours of each day between two dates I have Two table [FuelTankHistory] and [Product]
CREATE TABLE [dbo].[FuelTankHistory](
    [Id] [bigint] IDENTITY(1,1) NOT NULL,
    [FuelLevel] [decimal](18, 2) NULL,
    [FuelLevelTime] [datetime] NULL,
    [TankId] [bigint] NULL,
    [Volume] [decimal](18, 2) NULL,
    [ProductId] [bigint] NOT NULL
)
GO

CREATE TABLE [dbo].[Product](
    [ProductId] [bigint] IDENTITY(1,1) NOT NULL,
    [ProductName] [varchar](50) NULL,
    [IsActive] [bit] NULL)
GO

click here to view on SQL Fiddle.
Now I want to Generate a report Like Below (sale report for petrol)
ReportDate  sale_petrol
2021-08-01  113.000
2021-08-02  348.000
2021-08-03  -134.000
2021-08-04  519.000
2021-08-05  0.000

I my case tank 1 and 2 are petrol tanks,
now the tricky thing is I need to get sale of petrol between some date range.

if the date is '2021-08-02'

I want to get
first level between '2021-08-01 13:00:00' and '2021-08-02 13:00:00' (opening_stock of 24 hour)
and
last level between '2021-08-01 13:00:00' and '2021-08-02 13:00:00' (closing_stock of 24 hour)
for every tank, then get total sale done from every tank which is (opening_stock - closing_stock).
then get SUM of all tanks (in my case petrol tanks), in my case which is equal to 348.000 !
I have created a query to do this. but its taking too long to generate report for a month because history table have millions of records and I don't think looping is a good way to do this.

If you are facing any problem to understand my problem, please visit
SQL Fiddle by clicking the given link

Schema and data
CREATE TABLE [dbo].[FuelTankHistory](
    [Id] [bigint] IDENTITY(1,1) NOT NULL,
    [FuelLevel] [decimal](18, 2) NULL,
    [FuelLevelTime] [datetime] NULL,
    [TankId] [bigint] NULL,
    [Volume] [decimal](18, 2) NULL,
    [ProductId] [bigint] NOT NULL
) ON [PRIMARY]
GO

CREATE TABLE [dbo].[Product](
    [ProductId] [bigint] IDENTITY(1,1) NOT NULL,
    [ProductName] [varchar](50) NULL,
    [IsActive] [bit] NULL)
GO
SET IDENTITY_INSERT [dbo].[FuelTankHistory] ON
GO
INSERT [dbo].[FuelTankHistory] ([Id], [FuelLevel], [FuelLevelTime], [TankId], [Volume], [ProductId]) VALUES (1, CAST(124.00 AS Decimal(18, 2)), CAST(N'2021-08-01T01:05:12.000' AS DateTime), 1, CAST(120.00 AS Decimal(18, 2)), 1)
GO
INSERT [dbo].[FuelTankHistory] ([Id], [FuelLevel], [FuelLevelTime], [TankId], [Volume], [ProductId]) VALUES (2, CAST(665.00 AS Decimal(18, 2)), CAST(N'2021-08-01T12:05:12.000' AS DateTime), 2, CAST(333.00 AS Decimal(18, 2)), 1)
GO
INSERT [dbo].[FuelTankHistory] ([Id], [FuelLevel], [FuelLevelTime], [TankId], [Volume], [ProductId]) VALUES (3, CAST(879.00 AS Decimal(18, 2)), CAST(N'2021-08-01T07:05:12.000' AS DateTime), 2, CAST(345.00 AS Decimal(18, 2)), 1)
GO
INSERT [dbo].[FuelTankHistory] ([Id], [FuelLevel], [FuelLevelTime], [TankId], [Volume], [ProductId]) VALUES (4, CAST(675.00 AS Decimal(18, 2)), CAST(N'2021-08-01T18:05:12.000' AS DateTime), 2, CAST(567.00 AS Decimal(18, 2)), 1)
GO
INSERT [dbo].[FuelTankHistory] ([Id], [FuelLevel], [FuelLevelTime], [TankId], [Volume], [ProductId]) VALUES (5, CAST(434.00 AS Decimal(18, 2)), CAST(N'2021-08-01T20:05:12.000' AS DateTime), 2, CAST(744.00 AS Decimal(18, 2)), 1)
GO
INSERT [dbo].[FuelTankHistory] ([Id], [FuelLevel], [FuelLevelTime], [TankId], [Volume], [ProductId]) VALUES (6, CAST(552.00 AS Decimal(18, 2)), CAST(N'2021-08-01T05:05:12.000' AS DateTime), 2, CAST(346.00 AS Decimal(18, 2)), 1)
GO
INSERT [dbo].[FuelTankHistory] ([Id], [FuelLevel], [FuelLevelTime], [TankId], [Volume], [ProductId]) VALUES (7, CAST(835.00 AS Decimal(18, 2)), CAST(N'2021-08-02T08:05:12.000' AS DateTime), 1, CAST(643.00 AS Decimal(18, 2)), 1)
GO
INSERT [dbo].[FuelTankHistory] ([Id], [FuelLevel], [FuelLevelTime], [TankId], [Volume], [ProductId]) VALUES (8, CAST(246.00 AS Decimal(18, 2)), CAST(N'2021-08-02T04:05:12.000' AS DateTime), 1, CAST(897.00 AS Decimal(18, 2)), 1)
GO
INSERT [dbo].[FuelTankHistory] ([Id], [FuelLevel], [FuelLevelTime], [TankId], [Volume], [ProductId]) VALUES (9, CAST(477.00 AS Decimal(18, 2)), CAST(N'2021-08-02T13:05:12.000' AS DateTime), 2, CAST(675.00 AS Decimal(18, 2)), 1)
GO
INSERT [dbo].[FuelTankHistory] ([Id], [FuelLevel], [FuelLevelTime], [TankId], [Volume], [ProductId]) VALUES (10, CAST(235.00 AS Decimal(18, 2)), CAST(N'2021-08-03T23:05:12.000' AS DateTime), 1, CAST(67.00 AS Decimal(18, 2)), 1)
GO
INSERT [dbo].[FuelTankHistory] ([Id], [FuelLevel], [FuelLevelTime], [TankId], [Volume], [ProductId]) VALUES (11, CAST(88.00 AS Decimal(18, 2)), CAST(N'2021-08-03T19:05:12.000' AS DateTime), 2, CAST(87.00 AS Decimal(18, 2)), 1)
GO
INSERT [dbo].[FuelTankHistory] ([Id], [FuelLevel], [FuelLevelTime], [TankId], [Volume], [ProductId]) VALUES (12, CAST(345.00 AS Decimal(18, 2)), CAST(N'2021-08-03T02:05:12.000' AS DateTime), 1, CAST(67.00 AS Decimal(18, 2)), 1)
GO
INSERT [dbo].[FuelTankHistory] ([Id], [FuelLevel], [FuelLevelTime], [TankId], [Volume], [ProductId]) VALUES (13, CAST(255.00 AS Decimal(18, 2)), CAST(N'2021-08-03T07:05:12.000' AS DateTime), 2, CAST(65.00 AS Decimal(18, 2)), 1)
GO
INSERT [dbo].[FuelTankHistory] ([Id], [FuelLevel], [FuelLevelTime], [TankId], [Volume], [ProductId]) VALUES (14, CAST(433.00 AS Decimal(18, 2)), CAST(N'2021-08-03T04:05:12.000' AS DateTime), 1, CAST(345.00 AS Decimal(18, 2)), 1)
GO
INSERT [dbo].[FuelTankHistory] ([Id], [FuelLevel], [FuelLevelTime], [TankId], [Volume], [ProductId]) VALUES (15, CAST(567.00 AS Decimal(18, 2)), CAST(N'2021-08-03T17:05:12.000' AS DateTime), 2, CAST(565.00 AS Decimal(18, 2)), 1)
GO
INSERT [dbo].[FuelTankHistory] ([Id], [FuelLevel], [FuelLevelTime], [TankId], [Volume], [ProductId]) VALUES (16, CAST(388.00 AS Decimal(18, 2)), CAST(N'2021-08-04T22:05:12.000' AS DateTime), 1, CAST(45.00 AS Decimal(18, 2)), 1)
GO
INSERT [dbo].[FuelTankHistory] ([Id], [FuelLevel], [FuelLevelTime], [TankId], [Volume], [ProductId]) VALUES (17, CAST(234.00 AS Decimal(18, 2)), CAST(N'2021-08-04T06:05:12.000' AS DateTime), 1, CAST(34.00 AS Decimal(18, 2)), 1)
GO
INSERT [dbo].[FuelTankHistory] ([Id], [FuelLevel], [FuelLevelTime], [TankId], [Volume], [ProductId]) VALUES (18, CAST(976.00 AS Decimal(18, 2)), CAST(N'2021-08-04T09:05:12.000' AS DateTime), 1, CAST(124.00 AS Decimal(18, 2)), 1)
GO
INSERT [dbo].[FuelTankHistory] ([Id], [FuelLevel], [FuelLevelTime], [TankId], [Volume], [ProductId]) VALUES (19, CAST(345.00 AS Decimal(18, 2)), CAST(N'2021-08-04T11:05:12.000' AS DateTime), 2, CAST(45.00 AS Decimal(18, 2)), 1)
GO
SET IDENTITY_INSERT [dbo].[FuelTankHistory] OFF
GO
SET IDENTITY_INSERT [dbo].[Product] ON
GO
INSERT [dbo].[Product] ([ProductId], [ProductName], [IsActive]) VALUES (1, N'Petrol', 1)
GO
INSERT [dbo].[Product] ([ProductId], [ProductName], [IsActive]) VALUES (2, N'Diesel', 1)
GO
INSERT [dbo].[Product] ([ProductId], [ProductName], [IsActive]) VALUES (3, N'CNG', 1)
GO
SET IDENTITY_INSERT [dbo].[Product] OFF
GO

My Query to generate Report
declare @dt1 date='2021-08-01'
declare @dt2 date='2021-08-22'
DECLARE @tbl_temp_max TABLE(max_fuelLevel decimal(18,3),FuelStationTankId bigint,ReportDate date)
DECLARE @tbl_temp_min TABLE(min_fuelLevel decimal(18,3),FuelStationTankId bigint,ReportDate date)
-- is there any way to get both max and min in single query?
-- and do the same thing without using loop
WHILE ( @dt1 <= @dt2)
BEGIN
    -- declare loop variables
    DECLARE @date2 datetime= CAST(CAST(@dt1 AS DATE) AS DATETIME)
    set @date2 = DATEADD(HOUR, 13,@date2)
    DECLARE @date1 datetime= DATEADD(DAY, -1, @date2)
    --------------- Get Opening -------------------------------------------------------------------------------------------------
    insert into @tbl_temp_min
    select tbl.[FuelLevel],tbl.TankId ,@dt1
    from [dbo].[FuelTankHistory] tbl
    inner join (
    select min(t.[FuelLevelTime]) [date],t.TankId
      from [dbo].[FuelTankHistory] t
      where t.[FuelLevelTime] between @date1 and @date2 and t.TankId in (1,2) and t.ProductId=1
      group by t.TankId
    ) temp on tbl.TankId=temp.TankId and temp.[date]=tbl.[FuelLevelTime]
    --------------- Get Closing -------------------------------------------------------------------------------------------------
    insert into @tbl_temp_max
   select tbl.[FuelLevel],tbl.TankId ,@dt1
    from [dbo].[FuelTankHistory] tbl
    inner join (
    select max(t.[FuelLevelTime]) [date],t.TankId
      from [dbo].[FuelTankHistory] t
      where t.[FuelLevelTime] between @date1 and @date2 and t.TankId in (1,2) and t.ProductId=1
      group by t.TankId
    ) temp on tbl.TankId=temp.TankId and temp.[date]=tbl.[FuelLevelTime]
    ----------------------------------------------------------------------------------------------------------------
    SET @dt1= DATEADD(DAY, 1, @dt1)
END

select ReportDate,sum(sale) sale_petrol from
(select [max].*,ISNULL([min].min_fuelLevel, 0 ) [min_fuelLevel],(ISNULL([max].max_fuelLevel, 0 )-ISNULL([min].min_fuelLevel, 0 )) sale from @tbl_temp_max [max]
full join @tbl_temp_min [min] on [max].ReportDate=[min].ReportDate and [max].FuelStationTankId=[min].FuelStationTankId) total
group by ReportDate;

MODIFIED CONTENT
One more thing is I want the opening stock of current date should be equal to closing stock of previous date. I have millions of data which have hundreds of records for a minute. and this query skips one or more record while getting opening stock for current day.For example 2021-08-01 12:59:45 level is 100 & 2021-08-01 13:00:01 level is 90. now previous day closing level is 100 and current day opening level is 90 which is not acceptable. current day opening should be 100 also.

A: Based on your description, you can get get the first and last volumes on each date.  The calculation is a bit complicated, because you need to subtract 13 hours to get the date you really want.
Then aggregate:
select  DATEADD(day,1,FuelLevelDate) AS ReportDate, sum(last_fuel_level - first_fuel_level)
from (select distinct fth.TankId, v.FuelLevelDate,
             first_value(fth.FuelLevel) over (partition by fth.TankId, v.FuelLevelDate order by fth.FuelLevelTime) as first_fuel_level,
             first_value(fth.FuelLevel) over (partition by fth.TankId, v.FuelLevelDate order by fth.FuelLevelTime desc) as last_fuel_level
      from FuelTankHistory fth cross apply
           (values (convert(date, dateadd(hour, -13, fth.FuelLevelTime)))
           ) v(FuelLevelDate)
      ) fth
group by FuelLevelDate;

A: Here's a working and, I hope, faster code: http://sqlfiddle.com/#!18/b554a/64
Because of the platform (sqlfiddle) constraints, I could not use the input as variables, hence they are embedded in the code.
Also, the day column is off by a day and embeds the time.
Please, if it's a valid solution, after you work on these nuisances, feel free to edit this answer with the final conde.
The complete solution is:
WITH Dates(day) AS
(
    SELECT CAST('20210731 13:00:00' as DATETIME) as day
    --
    UNION ALL
    --
    SELECT
      DATEADD(day, 1, day) as day
    FROM Dates
    WHERE day <= '20210822'
)
select
  agg.day,
  sum(
    agg.FuelLevelEnd -
    agg.FuelLevelStart
  )
from
  (
    select distinct
        dt.day,
        t.TankId,
        --
        first_value(fth.FuelLevel)
          over(
            partition by dt.day, t.TankId
            order by fth.FuelLevelTime
          ) as FuelLevelStart,
        --
        first_value(fth.FuelLevel)
          over(
            partition by dt.day, t.TankId
            order by fth.FuelLevelTime desc
          ) as FuelLevelEnd
    from
      (
        Dates dt
          cross join(
            select distinct TankId
            from FuelTankHistory
          ) t
      )
        left outer join FuelTankHistory fth
        on(
              fth.TankId = t.TankId
          --
          and fth.FuelLevelTime >= dt.day
          and fth.FuelLevelTIme <  DATEADD(day, 1, dt.day)
        )
  ) agg
  group by agg.day

Which yields the expected result, and, as a bonus, NULL for missing ranges :-)

day
result

2021-07-31T13:00:00Z
113

2021-08-01T13:00:00Z
348

2021-08-02T13:00:00Z
-134

2021-08-03T13:00:00Z
519

2021-08-04T13:00:00Z
0

2021-08-05T13:00:00Z
(null)

2021-08-06T13:00:00Z
(null)

A: A solution can be the following which first obtains a single value of type DATE for the first and second half of the stock period and which is used for groupings through PARTITION BY, and then still correctly distinguish the beginning and the end of the interval due to proper sequencing maintained by the value FuelLevelTime of type DATETIME.
WITH FTH_tfix AS (
  SELECT Id,
    CASE
      /* proper sequence ordering maintained by FuelLevelTime */
      WHEN CAST(FuelLevelTime AS Time) >= '13:00:00' THEN 0   /* 1st half (today) */
      WHEN CAST(FuelLevelTime AS Time) <  '13:00:00' THEN -1  /* 2nd half (tomorrow) */
    END AS t_fix
  FROM FuelTankHistory),
FTH_tfixed AS (
  SELECT /* FTH.Id, */
    TankId,
    FuelLevel,
    DATEADD(day, t_fix, CONVERT(DATE, FuelLevelTime)) AS t_fixed_day,
    FuelLevelTime
  FROM FuelTankHistory FTH
    INNER JOIN FTH_tfix ON FTH.Id = FTH_tfix.Id),
FTH_tfixed_start_end AS (
  SELECT
    TankId,
    t_fixed_day,
    /* FuelLevelTime is a Datetime and preserves sequence ordering in t_fixed_day ranges */
    FIRST_VALUE(FuelLevel) OVER(PARTITION BY TankId, t_fixed_day ORDER BY FuelLevelTime ASC ) AS OpeningStockAmount,
    FIRST_VALUE(FuelLevel) OVER(PARTITION BY TankId, t_fixed_day ORDER BY FuelLevelTime DESC) AS ClosingStockAmount
  FROM FTH_tfixed),
FTH_final_helper AS (
  SELECT TankId, t_fixed_day,
    MIN(OpeningStockAmount) AS OpeningStockAmount,
    MIN(ClosingStockAmount) AS ClosingStockAmount
  FROM FTH_tfixed_start_end
  GROUP BY TankId, t_fixed_day)
SELECT t_fixed_day, SUM(OpeningStockAmount - ClosingStockAmount)
FROM FTH_final_helper
GROUP BY t_fixed_day

http://sqlfiddle.com/#!18/fcdab0/1

A:
The OpeningStock of the Current Date should be equal to the Closing Stock of the previos Date.

This Query gives the Opening Stock for 2021-08-02 and the Closing Stock for 2021-08-01.
SELECT FuelLevel
FROM [dbo].[FuelTankHistory]
WHERE [TankId] = 1
AND [FuelLevelTime] < '20210802 13:00:00'
ORDER BY FuelLevelTime DESC
OFFSET 0 ROWS FETCH NEXT 1 ROWS ONLY;

The following lists OpingStock, ClosingStock and Sale for every Date in Calendar and TankId in Tank.
SELECT date, TankId, OpeningStock, ClosingStock, OpeningStock - ClosingStock sale
FROM [dbo].[Calendar] c
CROSS APPLY (SELECT 1 UNION ALL SELECT 2) Tank(TankId)
CROSS APPLY (SELECT FuelLevel FROM [dbo].[FuelTankHistory]
            WHERE [TankId] = Tank.TankId
            AND   [FuelLevelTime] < DATEADD(day, -1, c.[Date])
            ORDER BY FuelLevelTime DESC
            OFFSET 0 ROWS FETCH NEXT 1 ROWS ONLY) as t(OpeningStock)
CROSS APPLY (SELECT FuelLevel FROM [dbo].[FuelTankHistory]
            WHERE [TankId] = Tank.TankId
            AND   [FuelLevelTime] <  c.[Date]
            ORDER BY FuelLevelTime DESC
            OFFSET 0 ROWS FETCH NEXT 1 ROWS ONLY) as t2(ClosingStock))

|                 date | TankId | OpeningStock | ClosingStock | sale |
|----------------------|--------|--------------|--------------|------|
| 2021-08-01T13:00:00Z |      1 |          124 |          835 | -711 |
| 2021-08-01T13:00:00Z |      2 |          665 |          434 |  231 |
| 2021-08-02T13:00:00Z |      1 |          835 |          433 |  402 |
| 2021-08-02T13:00:00Z |      2 |          434 |          255 |  179 |
| 2021-08-03T13:00:00Z |      1 |          433 |          976 | -543 |
| 2021-08-03T13:00:00Z |      2 |          255 |          345 |  -90 |
| 2021-08-04T13:00:00Z |      1 |          976 |          388 |  588 |
| 2021-08-04T13:00:00Z |      2 |          345 |          345 |    0 |
| 2021-08-05T13:00:00Z |      1 |          388 |          388 |    0 |
| 2021-08-05T13:00:00Z |      2 |          345 |          345 |    0 |
| 2021-08-06T13:00:00Z |      1 |          388 |          388 |    0 |
| 2021-08-06T13:00:00Z |      2 |          345 |          345 |    0 |
| 2021-08-07T13:00:00Z |      1 |          388 |          388 |    0 |
| 2021-08-07T13:00:00Z |      2 |          345 |          345 |    0 |
| 2021-08-08T13:00:00Z |      1 |          388 |          388 |    0 |
| 2021-08-08T13:00:00Z |      2 |          345 |          345 |    0 |
| 2021-08-09T13:00:00Z |      1 |          388 |          388 |    0 |
| 2021-08-09T13:00:00Z |      2 |          345 |          345 |    0 |

WITH a as (
  SELECT date, TankId, OpeningStock, ClosingStock, OpeningStock - ClosingStock sale
  FROM [dbo].[Calendar] c
  CROSS APPLY (SELECT 1 UNION ALL SELECT 2) Tank(TankId)
  CROSS APPLY (SELECT FuelLevel FROM [dbo].[FuelTankHistory]
               WHERE [TankId] = Tank.TankId
               AND   [FuelLevelTime] < DATEADD(day, -1, c.[Date])
               ORDER BY FuelLevelTime DESC
               OFFSET 0 ROWS FETCH NEXT 1 ROWS ONLY) as t(OpeningStock)
  CROSS APPLY (SELECT FuelLevel FROM [dbo].[FuelTankHistory]
               WHERE [TankId] = Tank.TankId
               AND   [FuelLevelTime] <  c.[Date]
               ORDER BY FuelLevelTime DESC
               OFFSET 0 ROWS FETCH NEXT 1 ROWS ONLY) as t2(ClosingStock))
SELECT date ReportDate, sum(sale) sale_petrol
FROM a
WHERE date BETWEEN '20210801 00:00:00' AND '20210810 00:00:00'
GROUP BY date;

|           ReportDate | sale_petrol |
|----------------------|-------------|
| 2021-08-01T13:00:00Z |        -789 |
| 2021-08-02T13:00:00Z |        -480 |
| 2021-08-03T13:00:00Z |         581 |
| 2021-08-04T13:00:00Z |        -633 |
| 2021-08-05T13:00:00Z |         588 |
| 2021-08-06T13:00:00Z |           0 |
| 2021-08-07T13:00:00Z |           0 |
| 2021-08-08T13:00:00Z |           0 |
| 2021-08-09T13:00:00Z |           0 |

Changes to the Schema
[dbo].[Calendar]  is created with the following Query
WITH CALENDAR(date) AS (
      SELECT CAST('20210630 13:00:00' as DATETIME) as date
      UNION ALL SELECT DATEADD(day, 1, date) as date
      FROM CALENDAR
      WHERE date <= '20210822'
)
SELECT *
INTO [dbo].[Calendar]
FROM CALENDAR
OPTION (MAXRECURSION 0);
GO

These rows are a OpeningStocks for any Date after 19010101
INSERT [dbo].[FuelTankHistory] ([Id], [FuelLevel], [FuelLevelTime], [TankId], [Volume], [ProductId]) VALUES (1, CAST(0.0 AS Decimal(18, 2)), CAST(N'1901-01-01T00:00:00.000' AS DateTime), 1, CAST(0 AS Decimal(18, 2)), 1)
GO
INSERT [dbo].[FuelTankHistory] ([Id], [FuelLevel], [FuelLevelTime], [TankId], [Volume], [ProductId]) VALUES (1, CAST(0.0 AS Decimal(18, 2)), CAST(N'1901-01-01T00:00:00.000' AS DateTime), 2, CAST(0 AS Decimal(18, 2)), 1)
GO

SqlFiddle: http://sqlfiddle.com/#!18/1334c/7

A: ♂
WITH x AS (
  SELECT FuelLevelTime
       , DateAdd( -- Bit of a cheat to adjust the `FuelLevelTime` to the correct reporting date
            day
          , CASE WHEN DatePart(hour, FuelLevelTime) >= 13 THEN 1 ELSE 0 END  -- Consider 1PM onwards part of the "next" day
          , Cast(FuelLevelTime AS date)
         ) AS fuel_level_date
       , FuelLevel
       , Volume
       , TankId
       , ProductId
  FROM   dbo.FuelTankHistory
  WHERE  EXISTS ( -- Filter to only petrol products.
           SELECT *
           FROM   dbo.Product
           WHERE  Product.ProductName = 'Petrol'
           AND    Product.ProductId = FuelTankHistory.ProductId
         )
)
, y AS (
  -- Add a couple of row numbers in each group.
  -- This allows us to identify the "first" and "last" rows in each group
  SELECT fuel_level_date
       , TankId
       , FuelLevelTime
       , FuelLevel
       , First_Value(FuelLevel) OVER (PARTITION BY TankId, fuel_level_date ORDER BY FuelLevelTime DESC) AS opening_stock
       , First_Value(FuelLevel) OVER (PARTITION BY TankId, fuel_level_date ORDER BY FuelLevelTime  ASC) AS closing_stock
       , Row_Number() OVER (PARTITION BY TankId, fuel_level_date ORDER BY FuelLevelTime ASC) AS row_num
  FROM   x
)
SELECT fuel_level_date
     , Sum(opening_stock - closing_stock) AS sale_petrol
FROM   y
WHERE  row_num = 1
GROUP
    BY fuel_level_date
ORDER
    BY fuel_level_date
;

http://sqlfiddle.com/#!18/b554a/299/0
Forgive the badly named CTEs.
But it does give the output you've requested, with no additional objects or anything particularly funky/complex.
I had considered using First_Value() instead of Row_Number() but to get that to work I threw in a DISTINCT (or another Row_Number()) which just didn't feel right.

EDIT: here's the version using First_Value()
; WITH x AS (
  SELECT Id
       , FuelLevelTime
       , DateAdd( -- Bit of a cheat to adjust the `FuelLevelTime` to the correct reporting date
            day
          , CASE WHEN DatePart(hour, FuelLevelTime) >= 13 THEN 1 ELSE 0 END  -- Consider 1PM onwards part of the "next" day
          , Cast(FuelLevelTime AS date)
         ) AS fuel_level_date
       , FuelLevel
       , Volume
       , TankId
       , ProductId
  FROM   dbo.FuelTankHistory
  WHERE  EXISTS ( -- Filter to only petrol products.
           SELECT *
           FROM   dbo.Product
           WHERE  Product.ProductName = 'Petrol'
           AND    Product.ProductId = FuelTankHistory.ProductId
         )
)
, y AS (
  -- Add a couple of row numbers in each group.
  -- This allows us to identify the "first" and "last" rows in each group
  SELECT Id
       , fuel_level_date
       , TankId
       , FuelLevelTime
       , FuelLevel
       , First_Value(FuelLevel) OVER (PARTITION BY TankId, fuel_level_date ORDER BY FuelLevelTime DESC) AS opening_stock
       , First_Value(FuelLevel) OVER (PARTITION BY TankId, fuel_level_date ORDER BY FuelLevelTime  ASC) AS closing_stock
       , Min(Id) OVER (PARTITION BY TankId, fuel_level_date) AS min_id  -- this will be used as a tie-breaker to reduce the set to a single row per group
  FROM   x
)
SELECT fuel_level_date
     , Sum(opening_stock - closing_stock) AS sale_petrol
FROM   y
WHERE  min_id = Id  -- Filter down to a single row per group
GROUP
    BY fuel_level_date
ORDER
    BY fuel_level_date
;


text:
Q: How to correlate time series to a variable In an experiment, heart rate of participants is collected for 60 seconds (1 reading per seconds) and pupil diameter whilst performing one of three tasks. The success of the task is measured with a binary value (success/failure) indicating whether they achieved the expected result or not.
What is a good statistical model to find a correlation between two time series and the success/failure variable? I'm not trying to correlate the two time series, I'm trying to correlate both of them individually or together with the success/failure variable.
Data look like this
```
Time, HR Reading, pupil size
0, 75, 0.01
1, 78, 0.012
2, 76, 0.011
...
...
59, 98, 0.04

```
Observation for this data is true.

A: As I've understood it, you basically want the probability of success depending the twao variables. In this case, a probit/logit model would be a good point to start:
$\pi_t=\alpha+\beta_1HR+\beta_2PS$
$P(y_t=1)=\Phi(\pi_t)$
with HR as the heart rate and PS as the pupil size.
Best wishes,
Richard


text:
Q: Using fitted GLM model to simulate y's from new x-values I have a fitted GLM model: m1=glm(y~x,family=poisson,data=data).  I would like to use this fitted model to simulate new data but simulate(m1,nsim=1) results only in y's for the original x-values used to fit the model.  Can the simulate function be used to generate y's from new x-values?

A: How about this.  First make some fake data to test on
x <- rnorm(100)
y <- rpois(rep(1,100), exp(x)) ## poisson regression with slope=1
## fit model
m1 <- glm(y ~ x,family=poisson)

Now decide on your new x points
new.data <- data.frame(x=seq(-3,3,.1))

get the predicted expected value of y for these points
mu.y <- predict(m1, newdata=new.data, type='response')

and generate k sets of simulated y at these new points. Your question has k=1 but we may as well be general.
sim.y <- replicate(k, rpois(rep(1, length(mu.y)), mu.y))

Now sim.y is a matrix with as many rows as new.data and k columns, each containing a possible set of y values assuming the model is correct.


text:
Q: ASP.NET auto-generate aspx.designer.cs turn off? As I'm working on a asp.net/c# project, I'm confronted with the foobar.aspx.designer.cs that auto generates it's content. eg, when I'm changing the code/designer, the designer.cs automatically updates it's content.
As I'm bit of a control-dude, I'd like to maintain the code myself. I'm not happy with the overkill of comments I don't need. Like:
    /// <summary>
    /// Form1 control.
    /// </summary>
    /// <remarks>
    /// Auto-generated field.
    /// To modify move field declaration from designer file to code-behind file.
    /// </remarks>
    protected global::System.Web.UI.HtmlControls.HtmlForm Form1;

While I'd like to see the following:
    protected global::System.Web.UI.HtmlControls.HtmlForm Form1;
    protected global::System.Web.UI.WebControls.Button Button3;
    etc, etc

(don't mind the naming, ofcourse I'd give it some distinguishing nameing)
How to fix this? I checked google on this one, but couldn't find an answer so quickly...

A: I am not sure if you can disable the automatic generation of this file. Nor if it would be good idea to do so... If you really want (need?) to interfere with it I would rather look for a way to change its behaviour/format. Unfortunately I cannot provide a solution/hint for this either. You might have to look in the field of "custom tools" (for code generation) though.
Why are you so unhappy with the format of the file? I almost never even look at it :) And according to Scott Guthrie the designer file has been introduced in VS 2005 as "a place where Visual Studio is allowed to write 'ugly' code": Tutorial 2: Code-Behind with VS 2005 Web Application Projects.
Edit: Maybe this article by Scott Hanselman could be of any help? T4 (Text Template Transformation Toolkit) Code Generation - Best Kept Visual Studio Secret.

A: You could read the comments, they tell you what to do.
Move the declarations to your codebehind and delete the designer file.
But I have to make an observation:
Expression of this kind of concern and especially the expenditure of effort in trying to undo the kindness that VS is showing you belies a degree of naiveté and inexperience.
Perhaps your time would be better spent coding? ;-)


text:
Q: GitHub ESLint action failing with "Permission Denied" I'm writing a CI workflow (GitHub actions), and it seems that eslint is failing with "Permission Denied" code 126. I can't seem to fix it.
Can someone explain why ESlint is failing with permission denied? If so, is there a solution?
Here's a link to the pr where it's failing.

A: If a GitHub action fails with Permission Denied there are two possibilities:
1. You are trying to run a command that requires elevated privileges
To solve this just prefix sudo. E.g. npx eslint > sudo npx eslint. The GitHub Docs specify:

The Linux and macOS virtual machines both run using passwordless sudo.

2. A shell script does not have the execute filesystem permission set
If you have a unix/bash shell handy, you can change that with:
chmod +x ./.github/scripts/xxx.sh

If not, you can tell git to add the permission with this command:
git update-index --chmod=+x ./.github/scripts/xxx.sh

update-index is similar to add in that it adds the change to the index, so you'll have to commit and push as usual.


text:
Q: Tinting a terrain model in a radius around a given point in XNA 4.0 I'm writing a game in Visual Studio 2010, using the XNA 4.0 framework. I have a 3D terrain model generated from a height map. What I'm trying to accomplish is to tint this model in a given radius around a certain point, the end goal being to display to the player the radius in which a unit can move in a given turn. The method I'm using to draw the model at the moment is this:
void DrawModel(Model model, Matrix worldMatrix)
    {
        Matrix[] boneTransforms = new Matrix[model.Bones.Count];
        model.CopyAbsoluteBoneTransformsTo(boneTransforms);

        foreach (ModelMesh mesh in model.Meshes)
        {
            foreach (BasicEffect effect in mesh.Effects)
            {
                effect.World = boneTransforms[mesh.ParentBone.Index] * worldMatrix;
                effect.View = camera.viewMatrix;
                effect.Projection = camera.projectionMatrix;

                effect.EnableDefaultLighting();
                effect.EmissiveColor = Color.Green.ToVector3();
                effect.PreferPerPixelLighting = true;

                // Set the fog to match the black background color
                effect.FogEnabled = true;
                effect.FogColor = Color.CornflowerBlue.ToVector3();
                effect.FogStart = 1000;
                effect.FogEnd = 3200;
            }

            mesh.Draw();
        }
    }

Also, in case it's relevant, I followed this tutorial http://create.msdn.com/en-US/education/catalog/sample/collision_3d_heightmap to create my heightmap and terrain.
Thanks in advance for any help!

A: You can use a shader to achieve that...
you only would need to pass as argument the world position of the center and the radius,
and let the pixel shader receive the pixel world position interpolated from the vertex shader as a texture coord...
then only have to check the distance of the pixel position to the center and tint it with a color if the pixel position is in range...

A: The technique you are looking for is called decaling.
You have to extract the part of the terrain, where the circle will be drawn, apply an appropriate texture to that part and draw it blending it with the terrain.
For the case of a terrain based on a uniform grid, this will look like the following:
You have the center position of the decal and its radius. Then you can determine min and max row/col in the grid, so that the cells include every drawn region. Create a new vertex buffer from these vertices. Positions can be read from the heightmap. You have to alter the texture coordinates, so the texture will be placed at the right position. Assume, the center position has coordinate (0.5, 0.5), center position + (radius, radius) has coordinate (1, 1) and so on. With that you should be able to find an equation for the texture coordinates for each vertex.

In the above example, the top left red vertex has texture coordinates of about (-0.12, -0.05)
Then you have the subgrid of the terrain. Apply the decal texture to it. Set an appropriate depth bias (you have to try out some values). In most cases, a negative SlopeScaleDepthBias will work. Turn off texture coordinate wrapping in the sampler. Draw the subgrid.
Here's some VB SlimDX Code I wrote for that purpose:
Public Sub Init()
    Verts = (Math.Ceiling(2 * Radius / TriAngleWidth) + 2) ^ 2
    Tris = (Math.Ceiling(2 * Radius / TriAngleWidth) + 1) ^ 2 * 2

    Dim Indices(Tris * 3 - 1) As Integer
    Dim curN As Integer
    Dim w As Integer
    w = (Math.Ceiling(2 * Radius / TriAngleWidth) + 2)
    For y As Integer = 0 To w - 2
        For x As Integer = 0 To w - 2
            Indices(curN) = x + y * w : curN += 1
            Indices(curN) = x + (y + 1) * w : curN += 1
            Indices(curN) = (x + 1) + (y) * w : curN += 1
            Indices(curN) = x + (y + 1) * w : curN += 1
            Indices(curN) = (x + 1) + (y + 1) * w : curN += 1
            Indices(curN) = (x + 1) + y * w : curN += 1
        Next
    Next

    VB = New Buffer(D3DDevice, New BufferDescription(Verts * VertexPosTexColor.Struct.SizeOfBytes, ResourceUsage.Dynamic, BindFlags.VertexBuffer, CpuAccessFlags.Write, ResourceOptionFlags.None, VertexPosTexColor.Struct.SizeOfBytes))
    IB = New Buffer(D3DDevice, New DataStream(Indices, False, False), New BufferDescription(4 * Tris * 3, ResourceUsage.Default, BindFlags.IndexBuffer, CpuAccessFlags.None, ResourceOptionFlags.None, 4))
End Sub

Public Sub Update()
    Dim Vertex(Verts - 1) As VertexPosTexColor.Struct
    Dim curN As Integer
    Dim rad As Single 'The decal radius
    Dim height As Single
    Dim p As Vector2
    Dim yx, yz As Integer
    Dim t As Vector2 'texture coordinates
    Dim center As Vector2 'decal center
    For y As Integer = Math.Floor((center.Y - rad) / TriAngleWidth) To Math.Floor((center.Y - rad) / TriAngleWidth) + Math.Ceiling(2 * rad / TriAngleWidth) + 1
        For x As Integer = Math.Floor((center.X - rad) / TriAngleWidth) To Math.Floor((center.X - rad) / TriAngleWidth) + Math.Ceiling(2 * rad / TriAngleWidth) + 1
            p.X = x * TriAngleWidth
            p.Y = y * TriAngleWidth

            yx = x : yz = y
            If yx < 0 Then yx = 0
            If yx > HeightMap.GetUpperBound(0) Then yx = HeightMap.GetUpperBound(0)
            If yz < 0 Then yz = 0
            If yz > HeightMap.GetUpperBound(1) Then yz = HeightMap.GetUpperBound(1)
            height = HeightMap(yx, yz)
            t.X = (p.X - center.X) / (2 * rad)  + 0.5
            t.Y = (p.Y - center.Y) / (2 * rad) + 0.5
            Vertex(curN) = New VertexPosTexColor.Struct With {.Position = New Vector3(p.X, hoehe, p.Y), .TexCoord = t, .Color = New Color4(1, 1, 1, 1)} : curN += 1
        Next
    Next
    Dim data = D3DContext.MapSubresource(VB, MapMode.WriteDiscard, MapFlags.None)
    data.Data.WriteRange(Vertex)
    D3DContext.UnmapSubresource(VB, 0)
End Sub

And here's the according C# code.
public void Init()
{
    Verts = Math.Pow(Math.Ceiling(2 * Radius / TriAngleWidth) + 2, 2);
    Tris = Math.Pow(Math.Ceiling(2 * Radius / TriAngleWidth) + 1, 2) * 2;

    int[] Indices = new int[Tris * 3];
    int curN;
    int w;
    w = (Math.Ceiling(2 * Radius / TriAngleWidth) + 2);
    for(int y = 0; y <= w - 2; ++y)
    {
        for(int x = 0; x <= w - 2; ++x)
        {
            Indices[curN] = x + y * w ; curN += 1;
            Indices[curN] = x + (y + 1) * w ; curN += 1;
            Indices[curN] = (x + 1) + (y) * w ; curN += 1;
            Indices[curN] = x + (y + 1) * w ; curN += 1;
            Indices[curN] = (x + 1) + (y + 1) * w ; curN += 1;
            Indices[curN] = (x + 1) + y * w ; curN += 1;
        }
    }

    VB = new Buffer(D3DDevice, new BufferDescription(Verts * VertexPosTexColor.Struct.SizeOfBytes, ResourceUsage.Dynamic, BindFlags.VertexBuffer, CpuAccessFlags.Write, ResourceOptionFlags.None, VertexPosTexColor.Struct.SizeOfBytes));
    IB = new Buffer(D3DDevice, new DataStream(Indices, False, False), new BufferDescription(4 * Tris * 3, ResourceUsage.Default, BindFlags.IndexBuffer, CpuAccessFlags.None, ResourceOptionFlags.None, 4));
}

public void Update()
{
    VertexPosTexColor.Struct[] Vertex = new VertexPosTexColor.Struct[Verts] ;
    int curN;
    float rad; //The decal radius
    float height;
    Vector2 p;
    int yx, yz;
    Vector2 t; //texture coordinates
    Vector2 center; //decal center
    for(int y = Math.Floor((center.Y - rad) / TriAngleWidth); y <= Math.Floor((center.Y - rad) / TriAngleWidth) + Math.Ceiling(2 * rad / TriAngleWidth) + 1; ++y)
        for(int x = Math.Floor((center.X - rad) / TriAngleWidth); x <= Math.Floor((center.X - rad) / TriAngleWidth) + Math.Ceiling(2 * rad / TriAngleWidth) + 1; ++x)
        {
            p.X = x * TriAngleWidth;
            p.Y = y * TriAngleWidth;

            yx = x ; yz = y;
            if( yx < 0)
                yx = 0;
            if (yx > HeightMap.GetUpperBound(0))
                yx = HeightMap.GetUpperBound(0);
            if (yz < 0)
                yz = 0;
            if (yz > HeightMap.GetUpperBound(1))
                yz = HeightMap.GetUpperBound(1);
            height = HeightMap[yx, yz];
            t.X = (p.X - center.X) / (2 * rad)  + 0.5;
            t.Y = (p.Y - center.Y) / (2 * rad) + 0.5;
            Vertex[curN] = new VertexPosTexColor.Struct() {Position = new Vector3(p.X, hoehe, p.Y), TexCoord = t, Color = New Color4(1, 1, 1, 1)}; curN += 1;
        }
    }
    var data = D3DContext.MapSubresource(VB, MapMode.WriteDiscard, MapFlags.None);
    data.Data.WriteRange(Vertex);
    D3DContext.UnmapSubresource(VB, 0);
}


text:
Q: Can't type AltGr characters in the OSX Terminal I probably messed up something and I can't type tilde and brackets in my terminal. I'm on Mac OS X but I thought this has something to do with Emacs that I use just from yesterday for an online course. What can I check?

A: You can use Emacs in the X11 environemnt. Then you can forget about the Meta-Key in default terminal.

A: I solved unchecking the "use option as meta key" in my preference's terminal. But I fear it's not a solution because I need that for emacs.

A: You should try iTerm2. It's generally better than Terminal.app. Sometimes you need to type reset to reset the terminal, it could be that too.


text:
Q: Angular - How can i optimize my code for improving load time ? Current load time is 2.45sec I'm trying to optimize the speed (happens to make my code faster). How can I optimize below piece of code so that load time get optimize further. And if possible, please suggest what I should usually keep in mind.
As of now Finish time = 2.45sec.
TS
export class AppComponent implements OnInit {
  searchKeywords: string;
  CoffeeItemList: any = [];
  type: string;
  search: string;
  selectedType = '';
  showLoader: boolean;
  empty = false;
  data: any = [];

  // tslint:disable-next-line:max-line-length
  constructor(private getDataListingService: DataListingService) {}
  ngOnInit(): void {
    this.getGlobalSearchList('');
    this.getAllData();
    this.getSmartSearchValues('');
    if (this.CoffeeItemList.length === 0) {
      this.empty = true;
      }
  }
  getAllData() {
    this.showLoader = true;
    this.getDataListingService.getAllDataLists().subscribe(value => {
      this.CoffeeItemList = value.data;
      this.showLoader = false;
    });
  }
  getGlobalSearchList(type: string) {
    this.selectedType = type;
    this.CoffeeItemList = [];
    this.getDataListingService.getAllDataLists().subscribe(value => {
        this.data = value.data;
        console.log(this.data);
        // tslint:disable-next-line:prefer-for-of
        for (let i = 0; i < this.data.length; i++) {
            if (this.data[i].type === type) {
                this.CoffeeItemList.push(this.data[i]);
            }
        }
    });
}
getSmartSearchValues(search: string) {
  if (search === '' ) {
      this.getAllData();
      return false;
  }
  if (search.length >= 3) {
    this.getDataListingService.searchList(search).subscribe(value => {
        this.data = value.data;
        this.CoffeeItemList = value.data;
        // check selected type either coffee, mobile or ALL.
        if (this.selectedType && this.selectedType !== '' ) {
            this.CoffeeItemList = [];
            // tslint:disable-next-line:prefer-for-of
            for (let i = 0; i < this.data.length; i++) {
                if (this.data[i].type === this.selectedType) {
                    this.CoffeeItemList.push(this.data[i]);
                }
            }
        }
    });
  }
}
}

A: First of all you call getAllDataLists twice why?
Can't one of these subscribe be made redundant?
Second try to filter out more data cause atleast 1 second for a call is alot of data getAllDataLists should be filter before you load all the data into your application.
Either it's to much data so you should check your network tab. Or the html is to complicated and load way to much data and that's why your aplication is getting so slow.
Also I see you're making the same mistakes with subscription?
You know it will trigger everytime data get changed? So with your current setup and if you subscribe on every keyup you will create 100 of subsciptions that never finish and keep poling for changes.
https://stackoverflow.com/a/60389896/7672014

A: I can see that you call your service getDataListingService three times in ngOnInit() and every time you make a request and, I suppose, you collect data and then you work on data.
I'd like to see your HTML file as well. Maybe you don't need to make that much requests on init.

A: Based on the code you have shared:

*

*You need to add some sort of pagination to your 'getAllDataLists' & 'searchList' methods i.e. you always get results in chunks instead of getting larger data results to render on the UI.

*The following methods when called are performing API calls that can all be combined into 1 single API call to reduce the memory load and reduce wait time for user to see results/data being rendered on the page.
this.getGlobalSearchList('');
this.getAllData();
this.getSmartSearchValues('');

*Optimize your API call e.g. send the 'selectedType' in the API itself to already get filtered results from the backend instead of adding a check of if (this.selectedType && this.selectedType !== '' )


text:
Q: How to iterate with for loop over numbers starting with 0 in PHP? I'm trying to iterate with for loop through 8 digit numbers starting with 0. For example, the first number is: 00000000 and I would like to display next 5 numbers.
So far I managed to accomplish sth. like that:
<?php

     $start = 00000000;
     $number = 5;

     for ($i = $start; $i < $start + $number; $i++) {
        $url = sprintf("http://test.com/id/%08d", $i);
        echo $url . "\r\n";
     }
?>

Result:
http://test.com/id/00000000
http://test.com/id/00000001
http://test.com/id/00000002
http://test.com/id/00000003
http://test.com/id/00000004

There's everything fine with this example, however, problems start with such an example:
<?php

         $start = 00050200;
         $number = 5;

         for ($i = $start; $i < $start + $number; $i++) {
            $url = sprintf("http://test.com/id/%08d", $i);
            echo $url . "\r\n";
         }
    ?>

The for loop produces:
http://test.com/id/00020608
http://test.com/id/00020609
http://test.com/id/00020610
http://test.com/id/00020611
http://test.com/id/00020612

while I expect:
http://test.com/id/00050200
http://test.com/id/00050201
http://test.com/id/00050202
http://test.com/id/00050203
http://test.com/id/00050204

A: It doesn't work because numbers beginning with a 0 are interpreted as octal numbers. From the Integers page of the PHP Documentation (Emphasis mine) :

Integers can be specified in decimal (base 10), hexadecimal (base 16),
  octal (base 8) or binary (base 2) notation, optionally preceded by a
  sign (- or +).
Binary integer literals are available since PHP 5.4.0.
To use octal notation, precede the number with a 0 (zero). To use
  hexadecimal notation precede the number with 0x. To use binary
  notation precede the number with 0b.

Simply use :
 $start = 50200;

At the beginning of your code and everything should work fine.

A: The reason you get other numbers is that a leading zero makes your number octal. So you start by setting $start = 00050200;, this makes $start octal.
Just remove these leading zeroes and the code will be fine.


text:
Q: ¿Como insertar las imágenes siguientes en página de Wordpress, de manera que en cada Patrocinio o Fila de Imágenes se tenga un tamaño diferente? Quisiera pasar estas imágenes, a Wordpress de manera que cada Fila de Imágenes o patrocinio tenga definido con CSS un tamaño distinto:
Ejemplo: Fila de Imágenes de Patrocinio 1: width: 300px; height: 225px ;
Ejemplo: Fila de Imágenes de Patrocinio 2: width: 200px; height: 125px ;
Ejemplo: Fila de Imágenes de Patrocinio 3: width: 400px; height: 325px ;
¿Como debo pasar el código html al editor de wordpress, que debo omitir de código posteado, y en que parte debó colocar el código CSS para asignar los tamaños?

<!DOCTYPE html>

   <title>Ejemplo de imágenes</title>

Album de imágenes de ejemplo

Patrocinio 1

Patrocinio 2

Patrocinio 3

A: Tendrías que envolver cada una de tus filas en un contenedor de tal manera que pudieras darle una clase en común a cada uno de los elementos contenidos en éste.
Luego en tu css le asignarías ancho y alto a las img dentro de la clase

* { text-align: center; }
      h1 { font-family: arial; text-align: center;}
      p { font-family: arial; text-align: justify; margin: 25px;}
      img {width: 300px; height: 225px ; margin: 10px;float:left }

.patrocinio1, .patrocinio2, .patrocinio3 {
 clear:left;
 float:left;
}

.patrocinio1 img {
   width: 300px; height: 225px ;
}

.patrocinio2 img {
   width: 200px; height: 125px ;
}

.patrocinio3 img {
  width: 400px; height: 325px ;
}

Album de imágenes de ejemplo

Patrocinio 1

Patrocinio 2

Patrocinio 3

Esto se puede hacer de muchas maneras. El div puede ser un span, o puede ser tu mismo elemento p si éste envolviese a las imágenes. En vez de clase puede ser un id, y así sucesivamente. El código que te pongo es sólo una manera más.
EDIT añadí un estilo para que las imagenes se puedan alinear horizontalmente, eso si es que su ancho lo permite.


text:
Q: Load views - Error with codeigniter I'm a newbie with codigniter, I'm doing a menu, so I put all the links not in the same main file for not repeat all time.
My code is:
In the main.php
    <?=$this->load->view('headers/menu');?>

In the menu.php
    <a href="<?=base_url()?>main/agregar">Agregar
    <a href="<?=base_url()?>main/modificar">Modificar
    <a href="<?=base_url()?>main/eliminar">Eliminar
    <a href="<?=base_url()?>main/buscar">Buscar

So, the following error appears and I don't know why...
any ideas??? Thank you so much

A PHP Error was encountered
Severity: 4096
Message: Object of class CI_Loader could not be converted to string
Filename: views/main.php
Line Number: 15
Backtrace:
File: C:\xampp\htdocs\everisgas\application\views\main.php Line: 15
  Function: _error_handler
File: C:\xampp\htdocs\everisgas\application\controllers\main.php Line:
  9 Function: view
File: C:\xampp\htdocs\everisgas\index.php Line: 292 Function:
  require_once

A: if you want to load the content of the view and print it, then you have to tell CI to return the view content as a string, by passing the 3rd parameter as true, if you dont set the 3rd parameter to TRUE it will return the CI_Loader instance for the purpose of chaining.
<?=$this->load->view('headers/menu', '', TRUE);?>

A: Can you try using like below in your main view:
<?php $this->load->view('headers/menu'); ?>

This will load your menu view file in main view file.

A: Don't use
<?=

because it is the same as
<?php echo

But $this->load->view return not a string, so you just need to use
<?php $this->load->view('some_template');?>

without echo!

A: This can be about the version of your framework. For example in CI 2.6
    <?php echo $this->load->view('headers/menu');?>

works but in CI 3.0
    <?php $this->load->view('headers/menu');?>

is the usage.

A: Why are you echoing <?=$this->load->view('headers/menu');?>
instead of doing this load it in your controller before loading main view or use include 'menu.php' if main.php and menu.php in same directory.

A: In Codeigniter version 1.5.4(or lower) using load->view('headers/menu');?> will load the view file but in Codeigniter version 3.0 this wont work anymore instead you simply use like this load->view('headers/menu'); ?>

A: you can makey your coding like this
<?php $this->load->view('vadmin/menu'); ?>

this is can solve your problem


text:
Q: Creating a Vertical menu using jquery How can I create a page like this?

When I click a link in the left side menu a page must be loaded in the content area, but the whole page must not load.
How to do this using jquery is there any plugin to do that?

A: i thing you need to load everything on page and selected content [who you want to show] is show by using jquery.show() and all other content [unselect] is hide using jqury.hide();
if you use link as hyperlink you must need first to disable him using preventdefault() or you need to make a event on div click.


text:
Q: Create Installation Package Including SQL Silent Installation and a C# Winforms Project I want to create an installer file that includes installer file for SQL Server and a C# project so that user don't have to do it separately.
I have seen a few solutions but want to get recommendations for the best possible solution available in market.

A: Some previous answers you can check:

*

*List View of Common Windows Installer Deployment Tools

*How to create windows installer (with links to non-Windows Installer tools as well)

Commercial deployment tools Advanced Installer and Installshield have some built-in support to install various prerequisites such as SQL Server Express - a quick description here. The open source and free WiX with its Burn component also allows you to install prerequisites, but you have to write XML markup code to accomplish the task. No real GUI apart from Visual Studio as editor (or another editor for that matter).

Some Links:

*

*How to create a MSI file which simply copies a directory to Program Files?

*Wrap C# application in .msi installer

*Application setup


text:
Q: python type hints on module properties (like Protocol for module) I have multiple modules that act as a plugin system.
Each module has identical funcions and properties, but different endpoints.
For example, module1.py and module2.py each have a def go() and a VALUE_1 constant.
Now I am looking to type annotate this when I would pas a module to a function:
import module1

def do_stuff_with_module(a_module):
    a_module.go()

So I guess I am looking for a structural type checker for a module like we have a Protocol for classes. Anyone any idea ?
Thanks !

A: look here: https://www.python.org/dev/peps/pep-0544/#modules-as-implementations-of-protocols
Guido took care of it..


text:
Q: Swap values and indexes of a vector I have a std::vector<int> with contiguous shuffled values from 0 to N and want to swap, as efficiently as possible, each value with its position in the vector.
Example:
v[6] = 3;

becomes
v[3] = 6;

This is a simple problem, but I do not know how to handle it in order to make it trivial and, above all, very fast. Thank you very much for your suggestions.

A: Given N at compile time and given the array contains each index in [0,N) exactly once,
it's relatively straight forward (as long as it doesn't have to be in-place, as mentioned in the comments above) :
Construct a new array so that v'[n] = find_index(v, n) and assign it to the old one.
Here I used variadic templates with std::index_sequence to roll it into a single assignment:
template<typename T, std::size_t N>
std::size_t find_index(const std::array<T,N>& arr, std::size_t index) {
    return static_cast<std::size_t>(std::distance(arr.begin(), std::find(arr.begin(), arr.end(), index)));
}

template<typename T, std::size_t N, std::size_t... Index>
void swap_index_value(std::array<T,N>& arr, std::index_sequence<Index...> seq){
    arr = { find_index(arr, Index)... };
}

template<typename Integer, std::size_t N>
void swap_index_value(std::array<Integer,N>& arr) {
    swap_index_value(arr, std::make_index_sequence<N>{});
}

The complexity of this is does not look great though. Calling find_index(arr, n) for each n in [0,N)
will take N * (N+1) / 2 comparisons total (std::sort would only take N * log(N)).
However, since we know each index is present in the array, we could just fill out an array of indices
as we walk over the original array, and assuming T is an integral type we can skip some std::size_t <-> T conversions, too:
template<typename T, std::size_t N>
void swap_index_value(std::array<T,N>& arr){
    std::array<T, N> indices;
    for (T i = 0; i < N; ++i)
        indices[arr[i]] = i;

    arr = indices;
}

We're still using twice the space and doing some randomly ordered writes to our array,
but essentially we're down to 2*N assignments, and the code is simpler than before.
Alternatively, we could also std::sort if we keep a copy to do lookups in:
template<typename T, std::size_t N>
void swap_index_value(std::array<T,N>& arr){
    std::sort(arr.begin(), arr.end(), [copy = arr](const T& lhs, const T& rhs) {
        return copy[lhs] < copy[rhs];
    });
}

First version here,
second version here,
std::sort version here
Benchmarking which one is faster is left as an exercise to the reader ;)


text:
Q: Как я могу разбить строку по регулярному выражению? Есть строки формата
     tom 18 Moscow
     anna 21
     kate is old
     yura lives in London

Как я могу разбить с помощью регулярных выражений C++ (boost) каждую из строк на первое слово и остальные?
Я помню, что в перле есть что-то вроде (\w+)(\s+)(\w+) а дальше можно получить значения каждой из скобок в формате $1, $2, $3.  А вот как я могу проделать это на boost?
Пробовал разбивать строку через istringstream. Но в этом случаи получается vector n-ого размера, где n-число слов. А нужно, чтобы было 2 части, т.к затем вторая часть строки будет париться по тому же принципу, что и начальная строка, но только, например, по другому разделителю (соответственно нужно будет объединять myvector.at(1)..myvector.at(myvector.size()-1) и начитать все сначала. А также нужно каждый раз проверять размер myvector, чтобы не было выхода за диапазон). С учетом того, что вариантов формата строки может быть много, не удобно для каждого варианта прописывать кучу кода, гораздо проще прописать для каждого варианта свой regexp.
Подскажите, как я могу проделать похожее на перл (или не похожее) получения слов со строки на С++? спасибо
P.S или может вы знаете другой способ, как можно решить это?
A: Вот решение в лоб:
#include <iostream>
using namespace std;
std::string get_head(std::string s) {
    size_t n = s.find(' ');
    return s.substr(0, n);
}

std::string get_tail(std::string s) {
    size_t n = s.find(' ');
    return s.substr(n+1, s.length());
}
int main() {
    std::string s = "test qwerty asdf";
    std::cout << get_head(s) << std::endl << get_tail(s) << std::endl;
    return 0;
}

можно ещё один параметр добавить для разделителя. Но чувствую, что Вам в основном нужна будет только функция get_head.
В бусте есть много. Есть регулярки (хотя они есть и в последнем стандарте и многие компиляторы поддерживают их с коробки), есть специальная библиотека для написания парсеров - Spirit + примеры с хабра.
A: В boost'е не шарю, но регулярку предложу http://regex101.com/r/uR4lZ3
A: Если нужно выбрать несколько первых слов из строк char[] (или char *) можете  использовать
// strtos.c
#include <string.h>
#include <stdarg.h>

#define SPACES " \t\n\r\f\v"
int
strtowv (const char *src, char **tail, ...)
{
  va_list ap;
  va_start(ap, tail);
  char **x;
  int n = 0;

  while (x = va_arg(ap, char **)) {
    if (!*(src += strspn(src, SPACES)))
      break;
    const char *s = src;
    src += strcspn(src, SPACES);
    *x = strndup(s, src - s);
    n++;
  }
  if (tail)
    *tail = (char *)src;
  va_end(ap);

  return n;
}

int
strtowa (const char *src, char **arr, int n, char **tail)
{
  int i = 0;

  while (*(src += strspn(src, SPACES)) && i < n) {
    const char *s = src;
    src += strcspn(src, SPACES);
    arr[i++] = strndup(s, src - s);
    if (i == n)
      break;
  }
  if (tail)
    *tail = (char *)src;

  return i;
}

как в С++, так и в  Си.
strtowv похожа на sscanf() и принимает переменное число параметров типа char ** для результата своей работы. Этот список надо завершать нулем (как в execl()).
strtowa возвращает результат разбора в массиве char *[] размер которого ей передается.
Обе функции возвращают количество успешно выделенных слов, и в своих аргументах (кроме аргумента tail) копию слов в динамической памяти. (Освобождать надо вызовом free()).
В tail возвращается адрес символа где прекратился разбор первого аргумента.
Пример для Вашего вопроса:
avp@avp-ubu1:t2info$ gcc tss.c strtos.o
avp@avp-ubu1:t2info$ ./a.out
strtowa:  <wrd1  wrd2 222>
n = 1 [wrd1] tail: [  wrd2 222]
strtowv: <wrd1  wrd2 222>
n = 1 [wrd1] tail: [  wrd2 222]
avp@avp-ubu1:t2info$ cat tss.c
#include <stdio.h>
#include <stdlib.h>

int strtowa (const char *src, char **arr, int n, char **tail);
int strtowv (const char *src, char **tail, ...);

int
main ()
{
  int n;
  char *w = 0, *tail;
  const char *tst = "wrd1  wrd2 222";

  printf ("strtowa:  <%s>\n", tst);
  n = strtowa(tst, &w, 1, &tail);
  printf("n = %d [%s] tail: [%s]\n", n, n > 0 ? w : "", tail);
  free(w);

  printf ("strtowv: <%s>\n", tst);
  n = strtowv(tst, &tail, &w, 0);
  printf("n = %d [%s] tail: [%s]\n",
         n, n > 0 ? w : "", tail);
}

avp@avp-ubu1:t2info$


text:
Q: Boost Graph Library: possible to combine Bundled Properties with Interior Properties? I'm using this typedef for my BGL graph type, Graph, using struct VertexProperty as a bundled vertex property:
struct VertexProperty {
    BeamType beam;
    size_t index;
};

typedef typename boost::adjacency_list<
        boost::listS,
        boost::listS,
        boost::bidirectionalS,
        VertexProperty
> Graph;

Before a recent change in my project, I'd been using the VertexProperty::index to construct a two_bit_color_map for use with depth_first_search:
auto colorMap = boost::make_two_bit_color_map(
        boost::num_vertices(graph_),
        get(&VertexProperty::index, graph_));

(the graph_ argument is a member variable of type Graph from above).  My recent change re-purposed VertexProperty::index to store a vertex index number read in from a file, rather than automatically generated by my code.  My code had previously been creating these indices as 0-based consecutive indices, incremented for each new vertex added to graph_.  With the change, I wish to no longer assume the indices are consecutive or that they will remain smaller than graph_.size() - 1; I just don't want to put that constraint on users.  However, I continued to use Vertex::index as the property for the two_bit_color_map, and this led to a run-time assertion failure with the message:
Assertion failed!

Program: D:\school\thesis\code\build\test\bin\testChain.exe
File: D:\programming\lib\boost\boost_1_54_0/boost/graph/two_bit_color_map.hpp, Line 72

Expression: (std::size_t)i < pm.n

I know I have VertexProperty::index values that go higher than or equal to graph_.size(); is my conclusion correct that this is what is causing the assertion failure?  I can't find in the BGL docs if there is any such constraint on the index property used with make_two_bit_color_map.
So, my main quesion is: Is it possible to use both interior properties, specifically property<vertex_index_t, int> and bundled vertex properties with a BGL graph, or am I stuck with one or the other?  (I'd like to avoid implementing the consecutive indices again with a new member in VertexProperty).  I imagine this might look something like this, though probably with other exact syntax:
typedef typename boost::adjacency_list<
        boost::listS,
        boost::listS,
        boost::bidirectionalS,
        property<vertex_index_t, int, property<VertexProperty>>
> Graph;

A: I think you are chasing a wrong problem.
Majority of BGL search algorithms needs a mapping "index" --> "vertex" where index varies in interval [0, num_vertices(g)). For example, DFS, BFS, connectivity component, A*, etc. need to init each vertex to "white" color first. Instead, they essentially use a vector of size num_vertices(g).
In BGL this central mapping is called "vertex_index" property map and algorithms simply cannot work if this property map is incorrect.
So your task, AFAICT, is to make sure you can enumerate your vertices correctly, in a continuous way. Quite often one needs a combination of vector with some extra hash- or STL map for this purpose.
In any case, as you fix this index mapping issue you will likely end up with some class which implements the mapping. Then your next step will be to teach Boost that this is your vertex-index property.
If your class MyMappingClass behaves as associative container (i.e. is implemented as STL map, or Boost unordered_map) than you can pass it to DFS-like algorithms using an idiom make_assoc_property_map(mymap) where mymap is of type MyMappingClass.
Alternatively, you can do it in more elaborate but also more flexible way described below. This flexibility can translate into more efficient code.
Since usually this property is read-only, you add a code like:
namespace boost {
template<>
struct property_map< MyGraph, vertex_index_t > {
    typedef MyMappingClass const_type;
    //typedef const_type type;
    //-- we do not define type as "vertex_index_t" map is read-only
};
}

Next, your class MyMappingClass could be a fully-compliant BGL property map, meaning it would have some declarations like
class MyMappingClass
{
public:
    typedef readable_property_map_tag category;
    typedef int value_type;
    typedef value_type reference;
    typedef MyGraph::vertex_descriptor key_type;
};

Besides, to work with such BGL-compliant property map one has to provide two different "get" functions: first is how to "get" property map from your graph (may be unnecessary or trivial if you make the class MyMappingClass a property of the graph).
The second function is how to "get" property value (aka "vertex_descriptor") from a given value of property key (aka integer in the interval [0,num_vertices(g))).
This second function can have a prototype similar to following:
MyMappingClass::value_type //aka index
get(  MyMappingClass mymap,
      MyMappingClass::key_type key) //aka vertex_descriptor

(Note, according to BGL, MyMappingClass should be a light-weight and copy constructable).


text:
Q: parsing error JSON.parse(unexpected token u) var storage = chrome.storage.local;
var cachedStorage = {};

this is js file.It shows unexpected token u.even though I've done parsing correctly.and it also shows unexpected token for  for its html source page.can any one suggest me how to sort this out.

var defaultStorage = [{
  savedPatterns: JSON.stringify([
    [{
      "en": "English"
    }, {
      "it": "Italian"
    }, "25", true],
    [{
      "en": "English"
    }, {
      "la": "Latin"
    }, "15", false]
  ]),

}];

error occurs here unexpected token u

function createPattern() {
  console.log('createPattern begin');
  var patterns = JSON.parse(S('savedPatterns'));
  var srce = [],
    trg = [],
    prb = [];
  console.log(S('savedPatterns'));
  console.debug(S('savedPatterns'));
  var translator = document.getElementById('translatorService');
  var service = translator.children[translator.selectedIndex].value;
  srce[0] = document.getElementById('sourceLanguage');
  srce[1] = srce[0].children[srce[0].selectedIndex].value;
  srce[2] = srce[0].children[srce[0].selectedIndex].text;
  trg[0] = document.getElementById('targetLanguage');
  trg[1] = trg[0].children[trg[0].selectedIndex].value;
  trg[2] = trg[0].children[trg[0].selectedIndex].text;
  prb[0] = document.getElementById('translationProbability');
  prb[1] = prb[0].children[prb[0].selectedIndex].value;

  patterns.push([
    [srce[1], srce[2]],
    [trg[1], trg[2]],
    prb[1],
    false,
    service
  ]);
  saveBulk({
    'savedPatterns': JSON.stringify(patterns)
  }, 'Saved Pattern');
  console.log('createPattern end');
}

function S(key) {
  return cachedStorage[key];
}

function loadStorageAndUpdate(callback) {
  storage.get(null, function(data) {
    console.log('data: ' + data + ' : ' + JSON.stringify(data));
    var d = {};
    if (!data || JSON.stringify(data) == '{}') { // in this case, storage was not initialized yet
      console.log('setting storage to defaultStorage (stringified): ');
      console.log(JSON.stringify(defaultStorage));
      storage.set(defaultStorage);
      d = defaultStorage;
    } else {
      d = data;
    }

    cachedStorage = d;
    if (!!callback) {
      callback(d);
    }
  });
}

A: Error Unexpected token comes when JSON.parse fails and depending on character (u in this case), you can assume its cause.

*

*u is if value is undefined

*o is if value is object

try {
  JSON.parse(undefined)
} catch (ex) {
  document.write(ex.message + "<br/>")
}

try {
  JSON.parse({})
} catch (ex) {
  document.write(ex.message)
}

You can try something like this:
function s(key) {
  var obj = {
    foo: "foo",
    bar: "bar"
  }
  var v = null;

  try {
    v = JSON.parse(obj[key]);
  } catch () {
    v = obj[key];
  }

  return v;
}

function main() {
  var v = s("foo");
}

Please refer following post for more information. Uncaught SyntaxError: Unexpected token with JSON.parse

A: You're trying to parse undefined. When you call JSON.parse(), you're passing in S('savedPatterns'), which in turn tries to access cachedStorage['savedPatterns'], but that starts as undefined, which you can't parse. You could just initialize your cachedStorage as:
var cachedStorage = {
  savedPatterns: JSON.stringify([])
};


text:
Q: second order ODE and Numerical integration I want to solve a second-order ODE
y''(x)+A*y'(x)+B*y(x)+c1*y(x)^2=0

I have written the code as
 B = 0.4; C2 = 0.5;F=0.6;

 sol2[A_] :=
 First@NDSolve[{y''[x] + A*y'[x] + B*y[x] + C2*y[x] == 0, y[1] == 1,
    y'[0] == -0.2}, y, {x, 0, 1}]

   Plot[{Evaluate[y[x] /. sol2[0.2]], Evaluate[y[x] /. sol2[0.5]]}, {x,
  0, 1}, PlotStyle -> {Red, Green}, Frame -> True,
 FrameLabel -> {X, \[Theta][X]}]

and then want to calculate the Numerical integration of 3*y[x]+F*y[x] from 0 to 1how can I do the integration and plot it.

A: This system can be solved exactly using DSolve.
Clear["Global`*"]

$Version

(* "12.2.0 for Mac OS X x86 (64-bit) (December 12, 2020)" *)

Use exact values for the known parameters,
B = 2/5; C2 = 1/2; F = 3/5;

eqns = {y''[x] + A*y'[x] + B*y[x] + C2*y[x] == 0,
  y[1] == 1, y'[0] == -1/5};

sol = DSolve[eqns, y, x];

Verifying the solution,
eqns /. sol // Simplify

(* {{True, True, True}} *)

The solution is then
sol2[A_, x_] = y[x] /. sol[[1]] // FullSimplify

(* (E^(-(1/10) (5 A + Sqrt[-90 + 25 A^2]) x) (2 E^
      Sqrt[-(18/5) + A^2] + (-5 A + Sqrt[-90 + 25 A^2]) E^(
      1/10 (5 A + Sqrt[-90 + 25 A^2])) -
     2 E^(Sqrt[-(18/5) + A^2] x) + (5 A + Sqrt[-90 + 25 A^2]) E^(
      1/10 (5 A + Sqrt[-90 + 25 A^2] (1 + 2 x)))))/(5 A (-1 + E^
      Sqrt[-(18/5) + A^2]) + Sqrt[-90 + 25 A^2] (1 + E^Sqrt[-(18/5) + A^2])) *)

Plotting,
Plot3D[sol2[A, x], {x, 0, 1}, {A, -1, 2},
 AxesLabel -> (Style[#, 14, Bold] & /@ {"x", "A", "y"})]

or
Plot[Evaluate[Tooltip[sol2[#, x], #] & /@ Range[-1, 1, 0.2]],
 {x, 0, 1},
 Frame -> True,
 FrameLabel ->
  (Style[#, 14, Bold] & /@ {"x", "y"}),
 PlotLegends -> LineLegend[Range[-1, 1, 0.25], LegendLabel -> "A"]]

The requested integral is
int[A_] = Integrate[3*y[x] + F*y[x] /. sol[[1]], {x, 0, 1}] //
  FullSimplify

(* (8 E^(1/2 Sqrt[-(18/5) +
     A^2]) ((1 + 5 A) Sqrt[-90 + 25 A^2]
       Cosh[A/2] - (1 + 5 A) Sqrt[-90 + 25 A^2]
       Cosh[1/2 Sqrt[-(18/5) + A^2]] +
     45 Sinh[1/2 Sqrt[-(18/5) + A^2]] + (-1 +
        5 A) (Sqrt[-90 + 25 A^2] Sinh[A/2] -
        5 A Sinh[1/2 Sqrt[-(18/5) + A^2]])))/(5 (5 A (-1 + E^
        Sqrt[-(18/5) + A^2]) +
     Sqrt[-90 + 25 A^2] (1 + E^Sqrt[-(18/5) + A^2]))) *)

Plotting,
Plot[int[A], {A, -1, 1},
 AxesLabel -> (Style[#, 14, Bold] & /@ {"A", "int"})]

EDIT: For the nonlinear equation,
eqns2 = {y''[x] + A*y'[x] + B*y[x] + C2*y[x]^2 == 0,
   y[1] == 1, y'[0] == -1/5};

Use ParametricNDSolve
sol2 = ParametricNDSolve[eqns2, y, {x, 0, 1}, {A},
   WorkingPrecision -> 15,
   NormFunction -> (Norm[#, 2] &)];

Plot3D[y[A][x] /. sol2, {x, 10^-3, 1 - 10^-3}, {A, 0, 1}]

Plot[Integrate[y[A][x] /. sol2, {x, 0, 1}], {A, 0, 1},
 AxesLabel -> (Style[#, 14, Bold] & /@ {"A", "int"})]


text:
Q: Should I specify the delegate when passing a callback? I was looking through some tutorials on async web requests using HttpWebRequest and came upon this example: https://msdn.microsoft.com/en-us/library/system.net.httpwebrequest.begingetrequeststream%28v=vs.100%29.aspx.
At request.BeginGetRequestStream(new AsyncCallback(GetRequestStreamCallback), request); the delegate is explicitly stated, wrapping the callback. Is there any advantage in doing this, compared to: request.BeginGetRequestStream(GetRequestStreamCallback, request); ?

A: Both codes are absolutely equivalent and it will boil down to the same IL. The C# compiler is sufficiently advanced enough to infer the proper type in the second case. So basically it's a matter of personal preference whether you prefer to write more characters than necessary and be more explicit.


text:
Q: What happen actually when TextBox got selected ? or got focused..? I am trying to code for "Hint Text in Text Box" in C#. It works this way:

*

*Initially show "Hint Text" with inactive caption color

*Blank the text box if all the hint text is selected

*Shows the user input text (after typing in this)

*If user deletes his text and goes to the next control, then it shows the hint text again.

I need a help on 2nd point: It's not clearing the text box if its content is not selected. It receives the input text mixed with "hint text".
On which event I need to write the code txtBox1.Clear(); to achieve my aim?

A: Assuming this is WinForms: Look at the Enter and Leave events. They will be called when a control gets or loses focus. You then need to decide whether the value in the text box is your default hint or entered by the user.
For WPF: There are nice solutions out there that use adorners to achieve what you want. You could google for WPF textbox watermark adorner.