text:
Q: Compile error without brackets surrounding ternary operator when creating Tuples in C# I have encountered an error in C# with the new Tuple feature. If I use a ternary operator to determine a value for the tuple I must surround it with brackets. I didn't expect this, because in method calls this isn't the case.
Are there any reasons for this or is it a bug?
Setup:

*

*Visual Studio 2017

*.Net Standard 1.6 Class Library

*System.ValueTuple (v4.3.0 - from Nuget)

My Code:
public class Test
{
    public bool Ok { get; set; }
    public string Text { get; set; }
}

public class Class1
{
    public void TestMethod()
    {
        //
        // FROM OBJECT
        //
        Test obj = new Test() { Ok = true, Text = "asdf" };

        StringMethod(true, obj.Ok ? obj.Text : "fsda");      // <-- OK
        var result1 = (true, obj.Ok ? obj.Text : "fsda");    // <-- Error
        var result2 = (true, (obj.Ok ? obj.Text : "fsda"));  // <-- OK (Same as line above, but with addional brackets)

        //
        // FROM OTHER TUPLE
        //
        var tuple = OtherTuple();

        StringMethod(true, tuple.ok ? tuple.text : "fdsa");     // <-- OK
        var result3 = (true, tuple.ok ? tuple.text : "fdsa");   // <-- Error
        var result4 = (true, (tuple.ok ? tuple.text : "fdsa")); // <-- OK (Same as line above, but with addional brackets)
    }

    public void StringMethod(bool state, string anyString)
    {

    }

    public (bool ok, string text) OtherTuple()
    {
        return (true, "asdf");
    }
}

A: I think the var cannot define that you are trying to set the value of a Tuple on this line
 var result3 = (true, tuple.ok ? tuple.text : "fdsa");

Maybe if you be more clear like this:
 var result3 = Tuple.Create(true, tuple.ok ? tuple.text : "fdsa");

This makes the code easy to read.


text:
Q: FileUpload.HasFile always shows false Iam loading three fileupload controls dynamically thru the following code.
protected void Page_Load(object sender, EventArgs e)
{
       Table tblDocuments = new Table();
        tblDocuments.CellPadding=8;
        tblDocuments.CellSpacing=8;

        TableRow tr7 = new TableRow();

        TableCell tc13 = new TableCell();
        Label lblSRV=new Label();
        lblSRV.Text="SRV:";
        tc13.BackColor = System.Drawing.ColorTranslator.FromHtml("#4FB0B0");
        lblSRV.ForeColor=System.Drawing.Color.Black;
        lblSRV.Font.Bold=true;
        tc13.Controls.Add(lblSRV);
        tr7.Cells.Add(tc13);

        TableCell tc14 = new TableCell();
        fuUploadSRV.ID = "SRV";
        tc14.Controls.Add(fuUploadSRV);
        tc14.HorizontalAlign = HorizontalAlign.Center;
        tc14.VerticalAlign = VerticalAlign.Middle;

        tr7.Cells.Add(tc14);
        tblDocuments.Rows.Add(tr7);

        TableRow tr8 = new TableRow();

        TableCell tc15 = new TableCell();
        Label lblMAtrialCertificate = new Label();
        lblMAtrialCertificate.Text = "Material/Product Certificate:";
        lblMAtrialCertificate.ForeColor = System.Drawing.Color.Black;
        lblMAtrialCertificate.Font.Bold = true;
        tc15.BackColor = System.Drawing.ColorTranslator.FromHtml("#4FB0B0");
        tc15.Controls.Add(lblMAtrialCertificate);
        tr8.Cells.Add(tc15);

        TableCell tc16 = new TableCell();
        fuUploadMaterialCertificate.ID = "MaterialCertificate";
        tc16.Controls.Add(fuUploadMaterialCertificate);
        tc16.HorizontalAlign = HorizontalAlign.Center;
        tc16.VerticalAlign = VerticalAlign.Middle;

        tr8.Cells.Add(tc16);
        tblDocuments.Rows.Add(tr8);

        TableRow tr9 = new TableRow();

        TableCell tc17 = new TableCell();
        Label lblPurchaseOrder = new Label();
        lblPurchaseOrder.Text = "Purchase Order:";
        lblPurchaseOrder.ForeColor = System.Drawing.Color.Black;
        lblPurchaseOrder.Font.Bold = true;
        tc17.BackColor = System.Drawing.ColorTranslator.FromHtml("#4FB0B0");
        tc17.Controls.Add(lblPurchaseOrder);
        tr9.Cells.Add(tc17);

        TableCell tc18 = new TableCell();
        fuUploadPurchaseOrder.ID="Purchase";
        tc18.Controls.Add(fuUploadPurchaseOrder);
        tc18.HorizontalAlign = HorizontalAlign.Center;
        tc18.VerticalAlign = VerticalAlign.Middle;

        tr9.Cells.Add(tc18);
        tblDocuments.Rows.Add(tr9);

        placeSubmit.Controls.Add(tblDocuments);

}
Iam processing the file in the button click event
void btnSubmit_Click(object sender, EventArgs e)
{

   if (fuUploadSRV.HasFile)
        {
            string srvFilename = Path.GetFileName(fuUploadSRV.PostedFile.FileName);
            Stream fs = fuUploadSRV.PostedFile.InputStream;
            int filesize = fuUploadSRV.PostedFile.ContentLength;
            BinaryReader br = new BinaryReader(fs);
            byte[] content = br.ReadBytes(filesize);
            Objects.UpdateSRVFileDetails(srvFilename, content,txtSRV.Text.ToString().Trim());

        }

        if (fuUploadMaterialCertificate.HasFile)
        {
            string materialFilename = Path.GetFileName(fuUploadMaterialCertificate.PostedFile.FileName);
            Stream fs = fuUploadMaterialCertificate.PostedFile.InputStream;
            int filesize = fuUploadMaterialCertificate.PostedFile.ContentLength;
            BinaryReader br = new BinaryReader(fs);
            byte[] content = br.ReadBytes(filesize);
            Objects.UpdateMaterialCertificateFileDetails(materialFilename, content, txtSRV.Text.ToString().Trim());
        }

        if (fuUploadPurchaseOrder.HasFile)
        {
            string poFilename = Path.GetFileName(fuUploadPurchaseOrder.PostedFile.FileName);
            Stream fs = fuUploadPurchaseOrder.PostedFile.InputStream;
            int filesize = fuUploadPurchaseOrder.PostedFile.ContentLength;
            BinaryReader br = new BinaryReader(fs);
            byte[] content = br.ReadBytes(filesize);
            Objects.UpdatePurchaseOrderFileDetails(poFilename, content, txtPurchaseOrderNo.Text.ToString().Trim());
        }

}
Now while debugging, though I am choosing a file, the fuUploadSRV.HasFile,fuUploadMaterialCertificate.HasFile,fuUploadPurchaseOrder.HasFile is always returning false.
Am I missing something?

A: Did you try updating your <form runat="server" to include enctype="multipart/form-data"?
Weird things may happen without it!

A: The file upload control is in update panel. When I removed the update panel, the control worked as predicted. But I dint understand how update panel played a role, but removing this has solved my problem.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Detect if the original node failed in tomcat cluster I have two nodes in a cluster. Node1 initially servers requests. Loadbalancer redirects the request to node 2 if the first node fails. I would like to know if there is a way for the Node 2 to detect if it is getting the request that was supposed for the node 1 or in other words to know if the node1  just failed.
I am using Tomcat 6 with session replication.

A: "Detect" as in you want your own code to realize that the session was failed over? Why do you need your code to be aware of failover?
If you have set jvmRoute for the appropriate Tomcat Engine, Tomcat should automatically append .<jvmRoute> to the JSESSIONID cookie value. Therefore looking at the incoming JSESSIONID cookie is one way to detect failover I suppose.


text:
Q: ExpressJS GET-request with multiple arguments I have a GET request, and I want to be able to pass along multiple arguments, seperated by /. I want them to be available to me as an array on the server.
I used an answer here, and got the route:  '/myRoute/(:someValue)*, then:
var values = [req.params.someValue].concat(req.params[0].split('/').slice(1));

Problem is that all the arguments are strings consisting of numbers, letters and some _, e.g. 172394_G_S. This works fine for the second, third etc. arguments, but for the first one (someValue), I simply get the first character. That is: I get the first character of someValue, but for the rest of my arguments I get a complete string.
What am I doing wrong?

A: Can you try to change your route to
'/myRoute/(:someValue)/*'

With the above route, I get :someValue as a complete string


text:
Q: Difference between Icon and ImageIcon? Icon bug = new ImageIcon( getClass().getResource( "bug1.png" ) );
ImageIcon bug = new ImageIcon( getClass().getResource( "bug1.png" ) );

What's the difference between these two? My book always uses the way in the first line to declare an ImageIcon but wouldn't it be better to declare it the second way because more specifically it is an ImageIcon?

A: Icon is an Interface, whereas ImageIcon is an implementation of that interface.
The first is better because it means you can change your ImageIcon for another implementation of Icon later without needing to change the rest of your application.

A: Their nature and application is different. Image is an abstract superclass of all classes that represent graphical images. ImageIcon is an implementation of Icon interface that uses Image as its source.

Think of an Image as something that could be rendered and an ImageIcon as something that will be rendered as an Icon when its paintIcon() method is called.
Quoted from here

Hope this is what you're looking for ;)

A: You should start by taking a read through JavaDocs for ImageIcon.
You will notice that ImageIcon implements Icon, meaning that it can be used where ever an Icon is expected (such as JButton and JLabel for example) but it also provides the means by which you can obtain an instance of Image which allows you to paint it using Graphics without the need for a Component reference, which Icon needs

A: see
java-imageicon-vs-image-difference
It is a thread about the difference between image and imageicon, but in the comments they also talk about Icon and such. Maybe this helps.

A: both are similar but the first one is the best because ImageIcon is Icon but not the reverse.When i say ImageIcon is Icon ImageIcon implements Icon.


text:
Q: Hangfire running recurring jobs on different web servers We have multiple web servers running our sites, with load balancers, so users are directed to different servers depending on the load. The code is the same for each instance on each server, and we have recurring jobs that are run. Obviously we dont want the jobs to run at the same time on both servers.
Does hangfire implement a lock when a job is run so it is not run again automatically?
Currently we have this already on each method that is run [Hangfire.DisableConcurrentExecution(60 * 60 * 5)] will that stop both servers running the code at the same time?

A: In order to get around this in the end, i did the following
These attributes are added to my interfaces
[PingUrlToKeepAlive]
[SkipWhenPreviousJobIsRunning]
[DisableConcurrentExecution(10)]
[Queue("{0}")]

PingUrl is an attribute created to stop the IIS process from shutting down after 20 minutes on either server, nothing to do with this fix, just thought i would mention it
Queue is the recommended way now according to hangfire.
DisableConcurrentExecution is the attribute i thought i needed only, but you also need the one below.
SkipWhenPreviousJobIsRunning is a new attribute, that looks like this
public class SkipWhenPreviousJobIsRunningAttribute: JobFilterAttribute, IClientFilter, IApplyStateFilter
{
    public void OnCreating(CreatingContext context)
    {
        var connection = context.Connection as JobStorageConnection;

        // We can't handle old storages
        if (connection == null) return;

        // We should run this filter only for background jobs based on
        // recurring ones
        if (!context.Parameters.ContainsKey("RecurringJobId")) return;

        var recurringJobId = context.Parameters["RecurringJobId"] as string;

        // RecurringJobId is malformed. This should not happen, but anyway.
        if (string.IsNullOrWhiteSpace(recurringJobId)) return;

        var running = connection.GetValueFromHash($"recurring-job:{recurringJobId}", "Running");
        if ("yes".Equals(running, StringComparison.OrdinalIgnoreCase))
        {
            context.Canceled = true;
        }
    }

    public void OnCreated(CreatedContext filterContext)
    {
    }

    public void OnStateApplied(ApplyStateContext context, IWriteOnlyTransaction transaction)
    {
        if (context.NewState is EnqueuedState)
        {
            var recurringJobId = SerializationHelper.Deserialize<string>(context.Connection.GetJobParameter(context.BackgroundJob.Id, "RecurringJobId"));
            if (string.IsNullOrWhiteSpace(recurringJobId)) return;

            transaction.SetRangeInHash(
                $"recurring-job:{recurringJobId}",
                new[] { new KeyValuePair<string, string>("Running", "yes") });
        }
        else if (context.NewState.IsFinal /* || context.NewState is FailedState*/)
        {
            var recurringJobId = SerializationHelper.Deserialize<string>(context.Connection.GetJobParameter(context.BackgroundJob.Id, "RecurringJobId"));
            if (string.IsNullOrWhiteSpace(recurringJobId)) return;

            transaction.SetRangeInHash(
                $"recurring-job:{recurringJobId}",
                new[] { new KeyValuePair<string, string>("Running", "no") });
        }
    }

    public void OnStateUnapplied(ApplyStateContext context, IWriteOnlyTransaction transaction)
    {
    }
}

Basically this checks to see if the job is already running and if so, cancels it.  We now have no problems with jobs running on both servers at the same time.

A: Take a look on Mutexes. They will prevent the execution two processes in the same time which need access to one resource.

Mutex prevents concurrent execution of multiple background
jobs that share the same resource identifier. Unlike other primitives,
they are created dynamically so we don't need to use
IThrottlingManager to create them first. All we need is to decorate
our background job methods with the MutexAttribute filter and define
what resource identifier should be used.

[Mutex("my-resource")]
public void MyMethod()
{
    // ...
}

When we create multiple background jobs based on this method, they
will be executed one after another on a best-effort basis with the
limitations described below. If there's a background job protected by
a mutex currently executing, other executions will be throttled
(rescheduled by default a minute later), allowing a worker to process
other jobs without waiting.

Source: https://docs.hangfire.io/en/latest/background-processing/throttling.html#


text:
Q: how to post attachments using Upload Collection - pending I am trying to use the same code wrt official upload collection pending
and in controller where upload is called :
onStartUpload: function(oEvent) {
            var oUploadCollection = this.byId("UploadCollection");
            var cFiles = oUploadCollection.getItems().length;
            var uploadInfo = cFiles + " file(s)";

            if (cFiles > 0) {
                oUploadCollection.upload();
                MessageBox.information("Uploaded " + uploadInfo);
            }
        },

I have set all required header parameters in onChange as:
onChange: function(oEvent) {
              var oUploadCollection = oEvent.getSource();
              // Header Token
              var oCustomerHeaderEmailToken = new UploadCollectionParameter({
                  name: "xxxx",
                  value: xxxxx
              });
              // Header Token
              var oCustomerHeaderAuthToken = new UploadCollectionParameter({
                  name: "xxxx",
                  value: "xxxx"
              });
              oUploadCollection.addHeaderParameter(oCustomerHeaderEmailToken);
              oUploadCollection.addHeaderParameter(oCustomerHeaderAuthToken);
          },

When i tried uploading in BE it gave me error as :

*

*current request is not a multipart request

Then I tried adding to onChange :
var oCustomerHeaderContentType = new UploadCollectionParameter({
                  name: "Content-Type",
                  value: "multipart/form-data; boundary=----WebKitFormBoundarycXEQN6de4OdX0FBe"
              });
 oUploadCollection.addHeaderParameter(oCustomerHeaderContentType);

It didn't work even though the error is gone ,
The API works fine and tested in postman but why not with upload collection ? May i know the request sent is a multipart form-data ? Do I need to add any extra parameters ?

*

*How does a simple back end API (if JAVA/Python) would be to collect files from when upload collection is used ? as there is no name to refer in server side like fileuploader and if the request is a multipart in upload collection

hope the experts help me out with this ... thanks :)


text:
Q: File Handling Text file or Binary file Which file handling technique is better to apply for making a project of library management system in C++. As in both everything can be done as updating and deleting of the records entered, but which is preferred.

*

*Text files

*Binary files

A: I did the same project back in time. I chose a text file format, so I would prefer text files because you can read the data you stored.
I think regarding performance there is no difference.
EDIT: OK, apparently there is a slight performance difference as   stefaanv mentioned.

Binary format typically uses fewer CPU cycles. However that is
  relevant only if your application is CPU bound and you intend to do
  serialization and/or unserialization on an inner loop/bottleneck.
  Remember: 90% of the CPU time is spent in 10% of the code, which means
  there won't be any practical performance benefit unless your "CPU
  meter" is pegged at 100%, and your serialization and/or
  unserialization code is consuming a healthy portion of that 100%.

A: One of the difference that i know that in a text file the text and characters are stored one character per byte, as we expect. But numbers are stored as strings of characters. Thus, 12345, even though it occupies 4 bytes in memory, when transferred to the disk using fprintf(), would occupy 5 bytes, one byte per character. Here if large amount of data is to be stored in a disk file, using text mode may turn out to be insufficient. The solution is to open the file in binary mode and use those functions (fread() and fwrite()) ) which store the numbers in binary format. It means each number would occupy same number of bytes on disks as it occupies in memory.
This will result different size of your file.


text:
Q: OData Expand fails on Client Win8.1 universal app Just a quick question, is this not supported in a Win 8.1 universal class library? Or if it is, can anyone help with what i'm doing wrong.
http://jbsapplication.azurewebsites.net/Modules?$filter=Name%20eq%20'JBS%20Electronic%20forms'&$expand=Menus

When I do this from the browser or Fiddler I receive the correct response.
My code in the client view model class is as follows (using the OData Client v2 code generated objects)
var application = new UriBuilder(ServiceBaseAddress);
var context = new Models.Application(application.Uri);

var modulesQuery = context.Modules.Expand(m=>m.Menus).Where(m => m.Name == ApplicationName);
var modules = await ((DataServiceQuery<Module>) modulesQuery).ExecuteAsync();
_currentModule = modules.FirstOrDefault();

The following exception is generated on the last line
A first chance exception of type 'Microsoft.OData.Core.ODataException' occurred in Microsoft.OData.Core.DLL
Additional information: When writing a JSON response, a user model must be specified and the entity set and entity type must be passed to the ODataMessageWriter.CreateODataEntryWriter method or the ODataFeedAndEntrySerializationInfo must be set on the ODataEntry or ODataFeed that is being writen.
If I remove the Expand portion of the request, everything is fine, but I need to then perform another round trip to get the menus.
A cut down reference for the Module class:
[Key("Id")]
public class Module: BindableBase
{
    public string Name
    {
        get { return _name; }
        set { SetProperty(ref _name, value); }
    }

    DataServiceCollection<Menu> _menus = new DataServiceCollection<Menu>(null,TrackingMode.AutoChangeTracking);

    public DataServiceCollection<Menu> Menus
    {
        get { return _menus; }
        set
        {
            _menus = value;
            OnPropertyChanged("Menus");
        }
    }
}

A: I have encountered the problem you describe when I forgot to add the expanding entity into the ODataModelBuilder as an EntitySet. Try this in your ASP.NET OData Web API:
builder.EntitySet<Menus>("Menus");

A: Models with an ID property need to be explicitly expanded by clients, and expandable models need to be registered as entitysets with the builder for the auto-generated OData client to be able to call expand.


text:
Q: Python CSV failing to write I have this code that iterates through a txt file of URLs and searches for files to download:
URLS = open("urlfile.txt").readlines()

def downloader():
    with open('data.csv', 'w') as csvfile:
        writer = csv.writer(csvfile)
        for url in downloadtools.URLS:
            try:
                html_data = urlopen(url)
            except:
                print 'Error opening URL: ' + url
                pass

            #Creates a BS object out of the open URL.
            soup = bs(html_data)
            #Parsing the URL for later use
            urlinfo = urlparse.urlparse(url)
            domain = urlparse.urlunparse((urlinfo.scheme, urlinfo.netloc, '', '', '', ''))
            path = urlinfo.path.rsplit('/', 1)[0]

            FILETYPE = ['\.pdf$', '\.ppt$', '\.pptx$', '\.doc$', '\.docx$', '\.xls$', '\.xlsx$', '\.wmv$', '\.mp4$', '\.mp3$']

            #Loop iterates through list of file types for open URL.
            for types in FILETYPE:
                for link in soup.findAll(href = compile(types)):
                    urlfile = link.get('href')
                    filename = urlfile.split('/')[-1]
                    while os.path.exists(filename):
                        try:
                            fileprefix = filename.split('_')[0]
                            filetype = filename.split('.')[-1]
                            num = int(filename.split('.')[0].split('_')[1])
                            filename = fileprefix + '_' + str(num + 1) + '.' + filetype
                        except:
                            filetype = filename.split('.')[1]
                            fileprefix = filename.split('.')[0] + '_' + str(1)
                            filename = fileprefix + '.' + filetype

                    #Creates a full URL if needed.
                    if '://' not in urlfile and not urlfile.startswith('//'):
                        if not urlfile.startswith('/'):
                            urlfile = urlparse.urljoin(path, urlfile)
                        urlfile = urlparse.urljoin(domain, urlfile)

                    #Downloads the urlfile or returns error for manual inspection
                    try:
                        urlretrieve(urlfile, filename, Percentage)
                        writer.writerow(['SUCCESS', url, urlfile, filename])
                        print "     SUCCESS"
                    except:
                        print "     ERROR"
                        writer.writerow(['ERROR', url, urlfile, filename])

Everything works fine except the fact that the data is not being written to the CSV.  No directories are being changed (that I know of, at least...)
The script iterates through the external list of URLs, finds the files, downloads them properly, and prints "SUCCESS" or "ERROR" without issue.  The only thing it's NOT doing is writing the data to the CSV file.  It will run through in its entirety without writing any CSV data.
I tried running it in a virtualenv to make sure there wasn't any weird package issues.
Is there something going on with my embedded loops that causing the CSV data to fail to write?

A: Try with open('data.csv', 'wb') as csvfile: instead.
http://docs.python.org/2/tutorial/inputoutput.html#reading-and-writing-files
or, build an iterable in place of writerow and later use writerows. If you run you script in interactive mode you can peek inside the contents of your iterable of rows. (i.e. [['SUCCESS',...],['SUCCESS',...],...])
import csv
with open('some.csv', 'wb') as f:
    writer = csv.writer(f)
    writer.writerows(someiterable)

A: So, I let the script run in its entirety and for some reason the data started writing to the CSV after it had been running for a while.  I'm not sure how to explain that.  The data had been somehow stored to memory and began writing at a random time?  I don't know, but the data is accurate compared to the log printed in my terminal.
Weird.


text:
Q: SQL Type Providers with ROP - F# I'm attempting to use Railway Oriented Programming principals http://fsharpforfunandprofit.com/rop/ and this http://indiedevspot.azurewebsites.net/2015/01/20/two-track-coding-rop-for-dummies-part-2/ for reference
I have successfully implemented this for most of the codebase, except now we are getting to putting items into SQL and wish to use ROP for validation of those types.  The typical pattern is
Figure 1:
let createSomething a b c = {A = a; B = b; C = c}
let createValidSomething so =
    createSomething
    <!> validateFunction1 so.param1
    <*> validateFunction2 so.param2
    <*> ...so forth and so on

You will notice that createSomething is a function that returns a record type instantiation a -> b -> c -> a' -> b' -> c'
The SQL Type providers return a mutable type (non record).  Lets look at my attempt to build a similar createSomething function
Figure 2:
    let createSQS(a, b, c, d, e, f, g) =
    let sqs = context.``[dbo].[Something]``.Create(a, b, c, d, e, f, g)
    sqs

At this point, we know this already will not work, we have a->b->c->d->e->f->g->context.[dbo].[Something].Entity
I know I can have an intermediary record type and follow ROP principals, match on success/failure and then create my object off of the already validated.  But does that not seem like too many steps?
Does anybody know of a good pattern for this?  Ideally we could have a function similar to Figure1 that generates a Record Type that is compatible with the Type Providers.
I'm open to trying things and hanging out on Skype :).

A: Should your function createSQS not be better like this:
let createSQS a b c d e f g =
    context.``[dbo].[Something]``.Create(a, b, c, d, e, f, g)

This one would have the needed signature of a->b->c->d->e->f->g->context.[dbo].[Something].Entity

A: So we came up with an answer at our dev meeting, and decided that we in fact WANT to execute each part in its own function.  For the inner binds we invented our own operator; similar to plus (&&&) (which I will blog about on my site www.indiedevspot.com) and at the top level we ran with a normal bind.
Our top level code looks like this:
[<HttpPost>]
x.member Add(sa:Something) =
           sa|>ValidateSomething
           >>= converttoSSA
           >>= persistSSA

We decided to separate the concerns due to independent testability of validation, conversion and persistence.  The theory is that functional composition if made up of functions that are guaranteed to work, is itself inherently guaranteed to work (or have a much better chance).
If we went with the proposed method (which we have not yet solved), we would be mixing concerns of creation, validation and conversion.  That would also end up creating an additional record type which was un-necessary.


text:
Q: Explicity trigger useeffect without changing dependencies I have below sample code
  useEffect(() => {
    const fetchData = async _ => {
        let payload = { }
      post("getdata", payload)
        .then(results => {
         console.log("results: ", results);
         })
        .catch(err => {
           console.log(err);
        });
    };

  }, [
    dep1,
    dep2,
    dep3
  ]);

I don't want to create separate function and put that insdie useeffect.
How can I trigger this use effect without changing any dependencies
Thanks

A: Refactor the fetchData function out from the useEffect hook and wrap it with a useCallback hook which you can call it elsewhere inside the component:

Pass an inline callback and an array of dependencies. useCallback will return a memoized version of the callback that only changes if one of the dependencies has changed. Docs

const fetchData = useCallback(() => {
  let payload = {};
  post("getdata", payload)
    .then((results) => {
      console.log("results: ", results);
    })
    .catch((err) => {
      console.log(err);
    });
}, [dep1, dep2, dep3]);

useEffect(() => {
  fetchData(); // call when fetchData has changed (due to dep1/dep2/dep3 change)
}, [fetchData]);

As a side note, make sure the variables in the dependency list(dep1, dep2, dep3) are actually used inside the hook since I am not sure if the implementation of the fetchData function you provided is completed or not.


text:
Q: installing and using ffmpeg-php in my wamp apache hey there i am developing a video sharing site and i need to change the video format and get its thumbnail etc i know this can be done by ffmpeg-php library.
but i have never used any php lib before .
i have successfully installed ffmpeg to my system (laptop) i can check it by typing library ffmpeg -version to my comand prompt it says something like this
  Microsoft Windows [Version 6.1.7600]
Copyright (c) 2009 Microsoft Corporation.  All rights reserved.

   C:\Windows\system32>ffmpeg -version
  ffmpeg version N-73818-g9ebe041 Copyright (c) 2000-2015 the FFmpeg developers
    built with gcc 4.9.2 (GCC)
  configuration: --enable-gpl --enable-version3 --disable-w32threads --      enable-avis
  ynth --enable-bzlib --enable-fontconfig --enable-frei0r --enable-gnutls --enable
   -iconv --enable-libass --enable-libbluray --enable-libbs2b --enable-libcaca --en
 able-libdcadec --enable-libfreetype --enable-libgme --enable-libgsm --enable-lib
     ilbc --enable-libmodplug --enable-libmp3lame --enable-libopencore-amrnb --enable
 -libopencore-amrwb --enable-libopenjpeg --enable-libopus --enable-librtmp --enab
    le-libschroedinger --enable-libsoxr --enable-libspeex --enable-libtheora --enabl
   e-libtwolame --enable-libvidstab --enable-libvo-aacenc --enable-libvo-amrwbenc -
     -enable-libvorbis --enable-libvpx --enable-libwavpack --enable-libwebp --enable-
    libx264 --enable-libx265 --enable-libxavs --enable-libxvid --enable-lzma --enabl
   e-decklink --enable-zlib
  libavutil      54. 28.100 / 54. 28.100
  libavcodec     56. 49.101 / 56. 49.101
  libavformat    56. 40.101 / 56. 40.101
 libavdevice    56.  4.100 / 56.  4.100
 libavfilter     5. 25.100 /  5. 25.100
  libswscale      3.  1.101 /  3.  1.101
  libswresample   1.  2.101 /  1.  2.101
   libpostproc    53.  3.100 / 53.  3.100

but i am having problem with accessing the library by my php code i think i have't installed it to my php module
here is what my wamp shows me
  Server Configuration
  Apache Version :
  2.4.9   - Documentation
  PHP Version :
   5.5.12   - Documentation
   Server Software:
    Apache/2.4.9 (Win64) PHP/5.5.12
       Loaded Extensions :
            apache2handlerbcmathbz2calendarcom_dotnetCorectypecurlda
     tedomeregexiffileinfofil[![enter image description here][1]][1]terftpgdgettextgmphashiconvimapjsonlib
      xmlmbstringmcryptmhashmysqlmysqlimysqlndod
      bcopensslpcrePDOpdo_mysqlpdo_sqlitePharReflectio
     nsessionshmopSimpleXMLsoapsocket    sSPLsqlite3standardtokenizerwddxxdebugxmlxmlreaderxmlrpcxmlwriterxslzipzlib
       MySQL Version :
       5.6.17  -  Documentation

if possible please tell me the next step so that i can access the ffmpeg lib from my php code .
a little help is also appreciated.
1.please tell me any link availabe to get the ffmpeg-php module and how to installl it
2.how to access the module/lib from my code justa small code example.
THANK YOU.


text:
Q: How do I convert epoch time to date and time zone is defined in offset in millisecond I am parsing one api date related to the weather app.
Here I am getting time in epoch time I want to convert into Date time format.
I am getting sunrise time that is epoch time. It is 1569494827(input Time).
I want to convert this time into a date.
It has offset time in milliseconds -14400(offset in millisecond).
This time is New York Morning time. Its Output will be 06:47 AM
but I am unable to convert this epoch time to Output time
This is a response: I have to convert into Date
"city": {
        "id": 5128581,
        "name": "New York",
        "coord": {
            "lat": 40.7306,
            "lon": -73.9867
        },
        "country": "US",
        "population": 8175133,
        "timezone": -14400,
        "sunrise": 1569494827,
        "sunset": 1569538053
    }

A: java.time and ThreeTenABP
    int offsetSeconds = -14_400;
    long sunriseSeconds = 1_569_494_827L;

    ZoneOffset offset = ZoneOffset.ofTotalSeconds(offsetSeconds);
    Instant sunriseInstant = Instant.ofEpochSecond(sunriseSeconds);
    OffsetDateTime sunriseDateTime = sunriseInstant.atOffset(offset);
    System.out.println("Sunrise: " + sunriseDateTime);

Output is:

Sunrise: 2019-09-26T06:47:07-04:00

It may be needless to say that sunset goes in the same fashion.
Avoid java.util.Date
If by i have to convert into Date you meant java.util.Date: don't. That class is poorly designed and long outdated and also cannot hold an offset. You're much better off using java.time. Only if you need a Date for a legacy API not yet upgraded to java.time, you need to convert. In this case you can ignore the offset ("timezone") completely since the Date cannot take it into account anyway. Just convert the Instant that we got:
    Date oldfashionedDate = DateTimeUtils.toDate(sunriseInstant);
    System.out.println("As old-fashioned Date object: " + oldfashionedDate);

As old-fashioned Date object: Thu Sep 26 12:47:07 CEST 2019

A Date always prints in the default time zone of the JVM, in my case Central European Summer Time (CEST), which is why we don't get 6:47 in the morning (it's a quite annoying and confusing behaviour).
Question: Can I use java.time on Android below API level 26?
Yes, java.time works nicely on older and newer Android devices. It just requires at least Java 6.

*

*In Java 8 and later and on newer Android devices (from API level 26) the modern API comes built-in. In this case the conversion is: Date.from(sunriseInstant) (a bit simpler).

*In Java 6 and 7 get the ThreeTen Backport, the backport of the modern classes (ThreeTen for JSR 310; see the links at the bottom).

*On (older) Android use the Android edition of ThreeTen Backport. It's called ThreeTenABP. And make sure you import the date and time classes from org.threeten.bp with subpackages.

Links

*

*Oracle tutorial: Date Time explaining how to use java.time.

*Java Specification Request (JSR) 310, where java.time was first described.

*ThreeTen Backport project, the backport of java.time to Java 6 and 7 (ThreeTen for JSR-310).

*ThreeTenABP, Android edition of ThreeTen Backport

*Question: How to use ThreeTenABP in Android Project, with a very thorough explanation.


text:
Q: Delphi - In which Uses Clause is 'Self' defined? Delphi Tokyo - I have a standalone UNIT I am using as a utility/library... aka there is NO form associated with it.  One of the routines creates and displays an 'OpenDialog' component. When I try to compile the code, I am getting the error:
 Undeclared identifier 'Self'.  My code is simple...
    var
      ExcelOpenDialog1: TOpenDialog;
    begin

     ExcelOpenDialog1 := TOpenDialog.Create(Self);
     ...

This leads me to the conclusion that I don't have an entry in the USES clause that I need, but I have no idea which one I am missing.  My current USES clause is...
uses
  Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants,
  System.Classes, Vcl.Graphics, System.UITypes, ComObj,  Office_TLB, Excel_TLB,
  Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.ComCtrls, Vcl.ExtCtrls, Vcl.StdCtrls,
  System.IOUtils, System.StrUtils, Generics.Collections, Generics.Defaults;

What do I need to add to get this to compile?  When I add the TOpenDialog component to a form, (and it compiles), I find that all the entries in the USES clause are already included in my library unit...

A: As already metioned by @whosrdaddy you do not have an object here, so you should use NIL as value for the owner parameter.
In this case you are responsible for cleaning up after you are done with the dialog, for example like this
var
  ExcelOpenDialog1: TOpenDialog;
begin
  ExcelOpenDialog1 := TOpenDialog.Create(NIL);
  try
    // do your stuff here with ExcelOpenDialog1
  finally
    ExcelOpenDialog1.Free;
  end;


text:
Q: Check-boxes Addition ($_POST) I was wondering how to make it so when I click two check-boxes then submit, a value appears; in this case the wanted value is "15 percent"
I have tried to make it work in several ways & read about the '$_POST' in the PHP manual but can't figure out how to solve this problem

PHP Lab 04
        <form name="orderform" action="<?php echo $_SERVER['PHP_SELF'];?>" method="post">

            Discount

        <input type="checkbox" name="discount" value="student"/>Customer one 15%

        <input type="checkbox" name="discount" value="senior"/>Customer two 10%

        <input type="checkbox" name="discount" value="klant"/>Customer three 5%

   <input type="image" src="button.jpg" value="order" />

        </form>

 Total discount

    <?php
           if(isset($_POST['discount']))
           {

            if($_POST['discount']=="student")
            {
               echo "15 percent";
            }
            else if($_POST['discount']=="senior")
            {
               echo "10 percent";
            }
            else if($_POST['discount']=="klant")
            {
               echo "5 percent";
            }
            else if($_POST['discount']=="senior" && $_POST['discount']=="klant")
            {
                echo "15 percent";
            }
           }

        ?>

Results of customer two & customer three
http://i.stack.imgur.com/qsUqU.png

A: you should use radio instead of checkbox try the following:
    <form name="orderform" action="<?php echo $_SERVER['PHP_SELF'];?>" method="post">

        Discount

    <input type="radio" name="discount" value="student"/>Customer one 15%

    <input type="radio" name="discount" value="senior"/>Customer two 10%

    <input type="radio" name="discount" value="klant"/>Customer three 5%

   <input type="image" src="button.jpg" value="order" />

    </form>

I assume you only want one of those selected at a time, not multiple.
UPDATE:
If you want to do what you mentioned in the comment then you have to do like @5parc mentioned. here is the code, "although I think there is a better way to accomplish what you are trying to do":
    <form name="orderform" action="<?php echo $_SERVER['PHP_SELF'];?>" method="post">

        Discount

    <input type="checkbox" name="discount[]" value="student"/>Customer one 15%

    <input type="checkbox" name="discount[]" value="senior"/>Customer two 10%

    <input type="checkbox" name="discount[]" value="klant"/>Customer three 5%

   <input type="image" src="button.jpg" value="order" />

    </form>

 Total discount

<?php
       if(isset($_POST['discount']))
       {

        if(in_array('senior', $_POST['discount']) && in_array('klant', $_POST['discount'])) {
          echo "15 percent";
        }
        else if(in_array('student', $_POST['discount']))
        {
           echo "15 percent";
        }
        else if(in_array('senior', $_POST['discount']))
        {
           echo "10 percent";
        }
        else if(in_array('klant', $_POST['discount']))
        {
           echo "5 percent";
        }

       }

    ?>


text:
Q: Is it possible to create an automation that exports a list (not a DE) to an FTP? I need a way to automatically export a list (not DE) to an FTP. I know this is possible when using DE's, data extracts, and file transfer activities. However, no documentation seems to exists when trying to perform the same function on lists.

A: Found the answer after I posted, thought others may want to know.
I created a query that looked at the _ListSubscribers data view. Example below:
Select [EmailAddress]
FROM
_ListSubscribers
WHERE
ListID = XXXXXXXX

Then, I created an automation that runs this query, performs a data extract of the target DE, then a file transfer activity to move the target DE to an FTP.
This worked for my needs and may for others.


text:
Q: Spring security form-login for struts We have struts MVC in our app and want to now integrate spring security.
I am able to integrate it successfully and able to deploy application.
In order to get custom login page we must add form-login to spring security xml file. I am having difficulty in integrating custom login pages.
Struts global forward
<global-forwards>
    <forward name="login" path="/" redirect="true"/>
</global-forwards>

When not logged in it will take us to login page
Web xml login config
<login-config>
    <auth-method>FORM</auth-method>
    <form-login-config>
        <form-login-page>/login.vm</form-login-page>
        <form-error-page>/loginError.vm</form-error-page>
    </form-login-config>
</login-config>

Above section in web.xml is removed as part of integrating with spring security. Rather I have following section in spring security
<intercept-url pattern="/**" access="hasRole('ROLE')" />
<form-login login-page="/login.vm"
            authentication-failure-url="/loginError.vm" />

But when I try to login I won't get custom login page rather it just points url to IP:PORT/APP/login.vm and page is not present.
Login form has j_spring_security
action="j_spring_security_check"

What changes are required in order to get custom login?
Should strut config be changed?

A: I'm guessing here, but I suspect that you are getting this as Spring Security does not understand/know about Velocity. I had a similair problem when I intergrated Spring Security into my Struts app using .jsp pages. In the end, I pointed login-page and  authentication-failure-url to point to actions and loaded the jsp pages from there. I suggest that you try the same.


text:
Q: Dropdown selection using Server Side dataTable | PHP, SQL Server I have a problem when selecting the dropdown in server-side data table. This is based on this example: https://datatables.net/examples/api/multi_filter_select.html.
I have this guide on how to fix it, but I don't know how to set it up.
https://datatables.net/forums/discussion/48780/server-side-column-filtering-with-drop-down-get-all-options
I'm using SQL Server 2012, XAMPP, and connected via SQLSRV.
The data table seems to work fine.

It filters all the result into the dropdown.

My problem is, when I select one of the dropdown, it shows no result (no match found).

This is my code.
For my table.

                Series No
                Account Type
                Tools

                Series No
                Account Type
                Tools

This is my script


text:
Q: Is there a known problem with array of objects ? when assigning a value e.g. to a[0].name, the element a[1].name gets also the same value I'm assigning a value to an array element, e.g. array1[0].name, then array1[1].name, array1[2].name,... gets also the value assigned only to array1[0].name.
The following code, is very symplified:
the following object is passed over to this function as an argument, and has the structure:
var reccurenceObject = {
   howOften:,
}

the code:
for (var j = 0; j < cycle; j++) {
      eventsArray[j].howOften = reccurenceObject[j].howOften;
}

Any idea why elements with different index are getting the values also ?
Thank you for any Helo.
Dani


text:
Q: Synchronous Web Pages I have a situation where an event have to affect several web pages on an event is triggered.
Its like in GMail. I am developing a project based on online stocking trading system for my college. There are asking for a facility where the administrator or the dealer doesn't need to refresh his end of the application to view the new orders placed by the customers at the other end of the application.
As I said its like GMail, wait for the event to happen, listen to it and update the page.
I am good at JavaScript and jQuery that I can do this within a page: event listeners. But how to do this across several pages.
You can also consider another situation: A waiter, a cashier and a cook in a hotel, all have a PDA with them, any of them doesn't have to refresh their instance of web page to update the orders placed.
How can I achieve this? Is this possible?
I say I am good at javascript but I have my limits and doubts.
I use jQuery and PHP.
Thanks in advance.
PS: I know how to refresh the page or iFrame for every 5 seconds or so.
Edit 1:
As for additional details, I want to something similar to below that is done in java
synchronised(sync)
{
   sync.wait()
}

The code may not be accurate, this was from my lab experiments. But the concept is similar. Server waits till the client made a move and this is repeated for a lot of time.
Edit 2:
Another best example is a situation we always face in the internet: Complete a survey or something to enable a content to be downloaded.
My trading system needs such a thing. The dealer page always listens for the client page to act with the server. Upon such thing, the dealer page is reacted to that action. In this case placing an order.

A: Look into a long-polling or "comet" architecture. This is widely used by event driven AJAX applications and will provide what you are looking for.
See https://en.wikipedia.org/wiki/Comet_(programming) for more info.

A: If there is several page instances on one browser, you can use javascript web worker.
ELSE
Use "Long pooling" OR "ajax quering"
Long pooling demo: How do I implement basic "Long Polling"?
What you do, you always query server for new information. If there is new information, you return it. Then javascript will see that there is new information and it will show it.


text:
Q: Problems with gradle dependencies and apache POI - CellType I am relatively new to using gradle, and am having trouble understanding dependencies. I have been using the Apache POI library to read from excel for a project, and initially I downloaded the JARs into my project and it worked completely fine. I decided to use gradle dependencies when I put my project on GitLab (from what I understand it is the same as using JARs but better when sharing the project since you don't have to download them?). This worked for most of the imports; however, for some reason my project is no longer able to import CellType. I redownloaded the JARs for the time being and it works again.
 A summary of the question(s):
Why is CellType the only thing that stopped working, and why did it stop working? What is different about it?
Edit: here is the dependencies section from my build.gradle
compile 'com.google.apis:google-api-services-sheets:v4-rev499-1.23.0'
testCompile group: 'org.testng', name: 'testng', version: '6.9.10'
compile group: 'org.seleniumhq.selenium', name: 'selenium-java', version: '3.8.1'
// https://mvnrepository.com/artifact/com.google.oauth-client/google-oauth-client-java6
compile group: 'com.google.oauth-client', name: 'google-oauth-client-java6', version: '1.11.0-beta'
// https://mvnrepository.com/artifact/com.google.oauth-client/google-oauth-client-jetty
compile group: 'com.google.oauth-client', name: 'google-oauth-client-jetty', version: '1.11.0-beta'
// https://mvnrepository.com/artifact/org.apache.poi/poi
compile group: 'org.apache.poi', name: 'poi', version: '3.9'
// https://mvnrepository.com/artifact/org.apache.poi/poi-ooxml
compile group: 'org.apache.poi', name: 'poi-ooxml', version: '3.9'
// https://mvnrepository.com/artifact/org.apache.poi/poi-ooxml-schemas
compile group: 'org.apache.poi', name: 'poi-ooxml-schemas', version: '3.17'

// https://mvnrepository.com/artifact/org.apache.commons/commons-collections4
compile group: 'org.apache.commons', name: 'commons-collections4', version: '4.1'

(Sorry for the messiness :/ )

The compile error I was getting was something like "cannot resolve" (the import statement was turning red)

import org.apache.poi.ss.usermodel.CellType;


text:
Q: Connection string that allows sql authentication I am struggling to connect my C program to MS SQL Server database.
My connection string is like this:
#define CONNECTION_STRING       "DRIVER={SQL Server};SERVER=/* */;DATABASE = /* */;Integrated Security = no; User Id = /* */;Password = /* */;"

But when I try to connect with it the program says:

[Microsoft][ODBC SQL Server Driver][SQL Server]Login failed for user
'MY\My_windows_name'.

It always try to connect with windows authentication. But why? According to the official Microsoft documentation concerning Integrated Security parameter:

When false, User ID and Password are specified in the connection. When
true, the current Windows account credentials are used for
authentication.

Also I believe that database settings are fine because I can connect to it with PHP with no problems at all. Also when I connect using SSMS and SQL Authentication it will pass me through as well. Seems like the connection string is the problem.
EDIT.
Let me paste my attempts I've tried since my initial post.
#define CONNECTION_STRING       "DRIVER={SQL Server};SERVER=/* */;DATABASE = /* */;UID = /* */;PWD= /* */;"
#define CONNECTION_STRING       "DRIVER={SQL Server};SERVER=/* */;DATABASE = /* */;UID  = /* */;PWD = /* */;Trusted_Connection=no;"
#define CONNECTION_STRING       "DRIVER={SQL Server};SERVER=/* */;DATABASE = /* */; User ID = /* */; Password = /* */; Trusted_Connection=no;"

All result with the same...
Let me also add that I am trying to run it on Windows Server 2019 Standard

A: I finally managed to make it work.
Here is a connection string that works for me:
#define CONNECTION_STRING       "DRIVER={SQL Server};SERVER=/* */;DATABASE = /* */;Authentication=SqlPassword;UID  = /* */;PWD = /* */;Trusted_Connection=no;Encrypt=no;"

It looks this line below was required to force it to log with SQL authentication.

Authentication=SqlPassword


text:
Q: CMD Batch - Search for last occurence of character while looping through file I have a .txt file which I loop through every line and spool to another file. Ok no problem so far. But I want NOT to spool lines, which have following criteria:
they contain more slashes. Find the last slash. After this one search the rest of the string for .*** (* = wildcard). If not found don´t spool, else spool.
Input file content for example:
c:/abc/abc/
c:/abc/abc/test.txt
c:/eee/
c:/eee/test.cfg
c:/test/abc/test/xxx/bbb/ccc/aaa/test.txt
c:/test/abc/test/xxx/bbb/ccc/aaa/

Output should look like:
c:/abc/abc/test.txt
c:/eee/test.cfg
c:/test/abc/test/xxx/bbb/ccc/aaa/test.txt

It is not static, where this lines appear, which should be removed. So I thought about finding the last slash and take all after that and look if there the last thing is ".***" If so keep else don´t echo
I don´t want to use other tools for this. It must be done via native command-line functionality.
Maybe somebody can help me out.
Code:
 >OUTPUT.txt (
FOR /F "usebackq delims=" %%I IN ("FILE.txt") DO (
set "line=%%I"
setlocal enabledelayedexpansion
rem DO SOMEHTING HERE I DON`T KNOW HOW TO DO
echo(!line!)
)
)

A: just do it in one line using findstr and its regular expression mode (\....$ means all strings ending with . followed by 3 characters):
findstr /R \....$ FILE.txt

result:
c:/abc/abc/test.txt
c:/eee/test.cfg
c:/test/abc/test/xxx/bbb/ccc/aaa/test.txt


text:
Q: php array replace recursive does not update key with empty array array_replace_recursive not updating second level key of array with empty array, below is the code
$base = ['elm1' => 'Foo', 'elm2' => ['subElm1' => 'bar', 'subElm2' => ['a','b']]];
$replacement = ['elm2' => ['subElm2' => []]];
$result = array_replace_recursive($base, $replacement);
print_r($result);

Output is:
Array ( [elm1] => Foo [elm2] => Array ( [subElm1] => bar [subElm2] => Array ( [0] => a [1] => b ) ) )

Expected output:
Array ( [elm1] => Foo [elm2] => Array ( [subElm1] => bar [subElm2] => Array ( ) ) )

A: manual for array_replace_recursive states:

When the value in array1 is scalar, it will be replaced by the value in array2, may it be scalar or array. When the value in array1 and array2 are both arrays, array_replace_recursive() will replace their respective value recursively.

now, when it comes to subElm2 - which both are arrays - it will replace recursively ... so:
[0=>'a', 1=>'b']    and    []

now, since the second array doesn't contain any elements, no replacement occurs. Happy times. if the second array was just null it would overwrite.
array_replace_recursive doesn't know when to stop. if faced with two arrays to replace, it has to recurse ;o)


text:
Q: Swift Package Manager with multiple target executables? Does anyone know whether the Swift Package Manager has any support for generating multiple executables from in one package?  I have a C program that needs to be migrated to Swift, and it is currently packaged as a makefile with multiple targets.  I am struggling a bit with how that might map to a Swift package, or is it 'packages'?

A: Yes:
project/
project/Sources/foo/main.swift
project/Sources/bar/main.swift

Will generate two executables, one foo, one bar.
There is documentation here.


text:
Q: CSS media query not working when resizing browser I'm trying to use a media query to make a div responsive on a site (using IE11).
This is my CSS:
@media screen and (max-width: 400px) { // Tried with "only screen" also

  .divStyle {
      background-image:none;
      background-color:red;
      background-position:right;
      color:#fff!important;
      height:140px;
      position:relative;
      top:-6px;

    }

}

.divStyle {
  background-image:url('/images/image.jpg');
  background-position:right;
  color:#fff!important;
  padding:20px;
  height:190px;
  position:relative;
  top:-6px;

}

I've also added the metatag in the Head section.
<meta name="viewport" content="width=device-width, initial-scale=1" />

But it still doesn't respond when I'm resizing the window.

A: In your case the rule without the media query follows after the one with the media query. So it overwrites the rule.
Change their order to this.
.divStyle {
  background-image:url('/images/image.jpg');
  background-position:right;
  color:#fff!important;
  padding:20px;
  height:190px;
  position:relative;
  top:-6px;

}

@media screen and (max-width: 400px) {
  .divStyle {
      background-image:none;
      background-color:red;
      background-position:right;
      color:#fff!important;
      height:140px;
      position:relative;
      top:-6px;
    }
}


text:
Q: getdata() Script time out only when time-triggered I'm importing a range from another spreadsheet and pasting it in the current spreadsheet with this script:
function getdata() {
var values = SpreadsheetApp.openById('XXXXXX').
getSheetByName('SheetB').getRange('A4:AZ484').getValues();
var destsheet = SpreadsheetApp.getActive().getSheetByName('Sheet1');
var destrange = destsheet.getRange('B520:BA1000');
destrange.setValues(values);
}

When firing the script manually the execution lasts around 20 seconds and has no problems at all:
[19-09-06 23:34:48:847 PDT] Starting execution
[19-09-06 23:34:48:999 PDT] SpreadsheetApp.openById([XXXXXX]) [0.145 seconds]
[19-09-06 23:34:49:000 PDT] Spreadsheet.getSheetByName([SheetB]) [0 seconds]
[19-09-06 23:34:49:000 PDT] Sheet.getRange([A4:AZ484]) [0 seconds]
[19-09-06 23:35:07:353 PDT] Range.getValues() [18.352 seconds]
[19-09-06 23:35:07:361 PDT] SpreadsheetApp.getActive() [0 seconds]
[19-09-06 23:35:07:510 PDT] Spreadsheet.getSheetByName([Sheet1]) [0.148 seconds]
[19-09-06 23:35:07:511 PDT] Sheet.getRange([B520:BA1000]) [0 seconds]
[19-09-06 23:35:09:907 PDT] Range.setValues([[[Tue Jan 01 00:00:00 GMT+01:00 2019, 235.1840336134454, 9.0, 41.525999999999996, 10.0, 21.0, 13.0, 13.0, 8.0, 59.43, 0.0, 0.0, 0.0, 0.0, 166.36, 0.0, 269.14, 8.0, 33.6425, 246.7, 1.0909606809890555,...) [2.374 seconds]
[19-09-06 23:35:10:571 PDT] Execution succeeded [21.055 seconds total runtime]

However, when being time-driven triggered (this Script should run automatically once per day) the execution time goes up to 374.518 secs and gets timed out.
Edited-----> I've been splitting the script and logging it:
function getdata() {
var ss = SpreadsheetApp.openById('XXXXX');console.log('s1');
  var sh =ss.getSheetByName('SheetB');console.log('s2');
  var si = sh.getRange('A4:AZ484');console.log('s3');
  var sj = si.getValues(); console.log('step1')
  var destsheet = SpreadsheetApp.getActive().getSheetByName('Sheet1'); console.log('step2')
  var destrange = destsheet.getRange('B520:BA1000'); console.log('step3')
  destrange.setValues(sj); console.log('step4')
}

Apparently it gets stuck in "var sj = si.getValues(); console.log('step1')".
The whole range is aroung 25.000 cells, which I think it shouldn't be too much.
Anyone has an idea how could this be happening?
Thank you very much for help!

A: TL;DR The fastest approach to this issue is at UPDATE II.
ORIGINAL ANSWER: getValues & setValues
We tried to reproduce this error by creating a spreadsheet six times larger than yours (150,000 cells in total). Then we run a function to copy it to a blank spreadsheet using your approach. After many runs, we got an average of 43 seconds to complete. This is the exact function we used to replicate your operation:
function copySheet(){
  var ss1 = SpreadsheetApp.openById('{ORIGINAL SPREADSHEET}').getSheetByName('Sheet1');
  var ss2 = SpreadsheetApp.openById('{COPY SPREADSHEET}').getSheetByName('Sheet1');
  var originalData = ss1.getRange(1, 1, 75000, 2).getValues();
  var targetRange = ss2.getRange(1, 1, 75000, 2).setValues(originalData);
}

And this is an example of a real execution transcript:
[19-09-09 04:09:27:021 PDT] Starting execution
[19-09-09 04:09:27:122 PDT] SpreadsheetApp.openById([{ORIGINAL SPREADSHEET}]) [0.093 seconds]
[19-09-09 04:09:27:123 PDT] Spreadsheet.getSheetByName([Sheet1]) [0 seconds]
[19-09-09 04:09:27:211 PDT] SpreadsheetApp.openById([{COPY SPREADSHEET}]) [0.086 seconds]
[19-09-09 04:09:27:211 PDT] Spreadsheet.getSheetByName([Sheet1]) [0 seconds]
[19-09-09 04:09:27:212 PDT] Sheet.getRange([1, 1, 75000, 2]) [0 seconds]
[19-09-09 04:09:50:166 PDT] Range.getValues() [22.953 seconds]
[19-09-09 04:09:50:396 PDT] Sheet.getRange([1, 1, 75000, 2]) [0.001 seconds]
[19-09-09 04:10:06:199 PDT] Range.setValues() [15.59 seconds]
[19-09-09 04:10:07:128 PDT] Execution succeeded [39.172 seconds total runtime]

When we run this function using a trigger we got similar time values. With all this information we can deduce that the size of the range is not an issue. Since your function stop working in the getValues() line, and as you said it is a spreadsheet with a lot of information and linked to several sources, we recommend to repeat this operation in a replicated spreadsheet with zero links to workaround the problem. Alternatively, you could provide us with an anonymized spreadsheet to test it. We hope that this is useful for you. Please, don't hesitate to offer us more information for further help.
UPDATE I: copyTo, getValues & setValues
To copy just the data itself (nor the links nor the formulas) we can use the method copyTo with the following parameters. Unfortunately, that method can only be used to copy data inside the same spreadsheet. As a workaround, the following code will create a new sheet inside the original spreadsheet, will later copy just the data to that new sheet and after that will copy that sheet to the destination spreadsheet. Finally, the intermediate sheet will be deleted.
function copySheet2() {
  var ss1 = SpreadsheetApp.openById('{ORIGINAL SPREADSHEET}');
  var copySheet = ss1.insertSheet('Clone');
  var ss2 = SpreadsheetApp.openById('{COPY SPREADSHEET}').getSheetByName('Sheet1');
  var originalData = ss1.getSheetByName('Sheet1').getRange(1, 1, 75000, 2);
  var destinationRange = ss1.getSheetByName('Clone').getRange(1, 1, 75000, 2);
  originalData.copyTo(destinationRange, {
    contentsOnly: "true"
  });
  var cloneData = ss1.getSheetByName('Clone').getRange(1, 1, 75000, 2).getValues();
  var destinationSpreadsheet = ss2.getRange(1, 1, 75000, 2).setValues(cloneData);
  ss1.deleteSheet(ss1.getSheetByName('Clone'));
}

As we can see on the new execution transcript, with this approach we can vastly reduce the execution time.
[19-09-11 10:11:50:333 CEST] Starting execution
[19-09-11 10:11:50:391 CEST] SpreadsheetApp.openById([{ORIGINAL SPREADSHEET}]) [0.052 seconds]
[19-09-11 10:11:52:132 CEST] Spreadsheet.insertSheet([Clone]) [1.741 seconds]
[19-09-11 10:11:54:012 CEST] SpreadsheetApp.openById([{COPY SPREADSHEET}]) [1.879 seconds]
[19-09-11 10:11:54:012 CEST] Spreadsheet.getSheetByName([Sheet1]) [0 seconds]
[19-09-11 10:11:57:376 CEST] Spreadsheet.getSheetByName([Sheet1]) [3.364 seconds]
[19-09-11 10:11:57:377 CEST] Sheet.getRange([1, 1, 75000, 2]) [0 seconds]
[19-09-11 10:11:57:377 CEST] Spreadsheet.getSheetByName([Clone]) [0 seconds]
[19-09-11 10:11:57:378 CEST] Sheet.getRange([1, 1, 75000, 2]) [0 seconds]
[19-09-11 10:11:57:378 CEST] Range.copyTo([Range, {contentsOnly=true}]) [0 seconds]
[19-09-11 10:11:57:379 CEST] Spreadsheet.getSheetByName([Clone]) [0 seconds]
[19-09-11 10:11:57:379 CEST] Sheet.getRange([1, 1, 75000, 2]) [0 seconds]
[19-09-11 10:12:04:314 CEST] Range.getValues() [6.934 seconds]
[19-09-11 10:12:04:445 CEST] Sheet.getRange([1, 1, 75000, 2]) [0 seconds]
[19-09-11 10:12:16:389 CEST] Range.setValues() [11.798 seconds]
[19-09-11 10:12:16:390 CEST] Spreadsheet.getSheetByName([Clone]) [0 seconds]
[19-09-11 10:12:16:950 CEST] Spreadsheet.deleteSheet([Sheet]) [0.56 seconds]
[19-09-11 10:12:18:021 CEST] Execution succeeded [26.613 seconds total runtime]

We hope that this new procedure is useful for you, but do not hesitate to ask for more help if you need it.
UPDATE II: copyTo
To improve the previous code, I implemented the method copyTo due to its higher performance. This new code will start duplicating the range and deleting the formulas in the same spreadsheet (as the first update does). It will later copy the data from that clone sheet to the destination spreadsheet. Finally, it will copy the values from the imported clone sheet to the main sheet. I added this last functionality because I assume that you will want to move the data around in the destination spreadsheet.
function copySheet3() {
  var ss1 = SpreadsheetApp.openById('{ORIGINAL SPREADSHEET}');
  var ss2 = SpreadsheetApp.openById('{COPY SPREADSHEET}');
  ss1.insertSheet('Clone');
  var cloneSheet = ss1.getSheetByName('Clone');
  var dataRange = ss1.getSheetByName('Sheet1').getRange(1, 1, 75000, 2);
  var destinationRange = ss1.getSheetByName('Clone').getRange(1, 1, 75000, 2);
  dataRange.copyTo(destinationRange, {
    contentsOnly: "true"
  });
  cloneSheet.copyTo(ss2);
  ss1.deleteSheet(cloneSheet);
  var cloneSheet = ss2.getSheetByName(
  'Copy of Clone'); // Clone on the destination
  var tempRange = cloneSheet.getRange(1, 1, 75000, 2);
  var finalRange = ss2.getSheetByName('Sheet1').getRange(1, 1, 75000, 2);
  tempRange.copyTo(finalRange, {
    contentsOnly: "true"
  });
  ss2.deleteSheet(cloneSheet);
}

As we all can see on the execution transcript, this approach minimizes the elapsed time even more than previous options:
[19-09-16 10:24:04:036 CEST] Starting execution
[19-09-16 10:24:04:113 CEST] SpreadsheetApp.openById([{ORIGINAL SPREADSHEET}]) [0.071 seconds]
[19-09-16 10:24:04:444 CEST] SpreadsheetApp.openById([{COPY SPREADSHEET}]) [0.33 seconds]
[19-09-16 10:24:06:150 CEST] Spreadsheet.insertSheet([Clone]) [1.705 seconds]
[19-09-16 10:24:06:525 CEST] Spreadsheet.getSheetByName([Clone]) [0.374 seconds]
[19-09-16 10:24:06:525 CEST] Spreadsheet.getSheetByName([Sheet1]) [0 seconds]
[19-09-16 10:24:06:526 CEST] Sheet.getRange([1, 1, 75000, 2]) [0 seconds]
[19-09-16 10:24:06:527 CEST] Spreadsheet.getSheetByName([Clone]) [0 seconds]
[19-09-16 10:24:06:528 CEST] Sheet.getRange([1, 1, 75000, 2]) [0 seconds]
[19-09-16 10:24:06:528 CEST] Range.copyTo([Range, {contentsOnly=true}]) [0 seconds]
[19-09-16 10:24:12:755 CEST] Sheet.copyTo([Spreadsheet]) [6.226 seconds]
[19-09-16 10:24:13:271 CEST] Spreadsheet.deleteSheet([Sheet]) [0.515 seconds]
[19-09-16 10:24:13:272 CEST] Spreadsheet.getSheetByName([Copy of Clone]) [0 seconds]
[19-09-16 10:24:13:273 CEST] Sheet.getRange([1, 1, 75000, 2]) [0 seconds]
[19-09-16 10:24:13:273 CEST] Spreadsheet.getSheetByName([Sheet1]) [0 seconds]
[19-09-16 10:24:13:274 CEST] Sheet.getRange([1, 1, 75000, 2]) [0 seconds]
[19-09-16 10:24:13:275 CEST] Range.copyTo([Range, {contentsOnly=true}]) [0 seconds]
[19-09-16 10:24:15:594 CEST] Spreadsheet.deleteSheet([Sheet]) [2.319 seconds]
[19-09-16 10:24:15:767 CEST] Execution succeeded [11.553 seconds total runtime]

Please, let all of us know if this new code sample helped on your project. Feel free to add more ideas or to share the execution transcript for more development.

A: Update II works really much faster, I've had though several problems with the steps:
 ss1.insertSheet('Clone');

and
 cloneSheet.copyTo(ss2);

Adjusting the script, so the "Clone" sheet in the original Spreadsheet is not deleted lter and hence this has not to be created any more at the beginning, the script is running smooth (execution under 4 seconds).
 function copySheet5() {
  var ss1 = SpreadsheetApp.openById([{ORIGINAL SPREADSHEET}]);
  var ss2 = SpreadsheetApp.openById([{COPY SPREADSHEET}]);
  var cloneSheet = ss1.getSheetByName('Clone');
  var dataRange = ss1.getSheetByName('Sheet1').getRange(4, 1, 481, 52);
  var destinationRange = ss1.getSheetByName('Clone').getRange(1, 1, 481, 52);
  dataRange.copyTo(destinationRange, {
    contentsOnly: "true"
  });
  cloneSheet.copyTo(ss2);
  var cloneSheet = ss2.getSheetByName(
  'Copy of Clone'); // Clone on the destination
  var tempRange = cloneSheet.getRange(1, 1, 481, 52);
  var finalRange = ss2.getSheetByName('Sheet1').getRange(520, 2, 481, 52);
  tempRange.copyTo(finalRange, {
    contentsOnly: "true"
  });
  ss2.deleteSheet(cloneSheet);
}

Thanks a lot for all the help!


text:
Q: Multiple logfactory instances, is it performance safe? I am using NLog with .netcore31 web api hosted in IIS10.
We are following a design by Filip that allows running parallel and independent pipelines within an application for each application area/branch.
I would like to configure individual nlog.config files for each of the independent pipeline so that each of them has its own logging configuration and logging filters/targets etc.
I am using following code to configure separate nlog.config for each branch -
//sample Code - for each branch/pipeline
var webHostBuilder = WebHost.CreateDefaultBuilder()
    .ConfigureLogging((hostingContext, logging) =>
    {
        logging.AddNLog(serviceProvider => new LogFactory(nLogConfigFilePathForBranch))
    })

I have 18 such branches configured in the application.
I have not used UseNLog() method anywhere in the code.
Under load (200 concurrent requests) the response time of the application is very low and application is stalled for first 4-5 mins and then responds at very slow speed. There is one "Select" query on single view (select 1 record from roughly 500 records) in the functionality.
I also see an error in NLog internal log - "Warn Flush completed with errors Exception: System.TimeoutException: Timeout when flushing all targets, after waiting 15 seconds."
I am using following Nuget pckgs -
<PackageReference Include="NLog" Version="4.7.4" />
<PackageReference Include="NLog.Web.AspNetCore" Version="4.9.3" />
<PackageReference Include="NLog.WindowsEventLog" Version="4.7.4" />

NLog.Config typically looks like -
<?xml version="1.0" encoding="utf-8" ?>
<nlog xmlns="http://www.nlog-project.org/schemas/NLog.xsd" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" autoReload="true" internalLogLevel="off" internalLogFile="admin.internalLog.txt">
  <extensions>
    <add assembly="NLog.Web.AspNetCore" />
    <add assembly="NLog.WindowsEventLog" />
    <add assembly="Sirius.Api.Platform.Common" />
  </extensions>
  <!-- the targets to write to -->
  <targets>
    <target xsi:type="EventLog" name="apiEventlog" source="Api.Travel" layout="${api-traceidentifier}|${api-userid}|${logger}|${message} ${exception:format=tostring}" Log="Application" machinename="."/>
    <!-- write to file -->
    <target xsi:type="File" name="Api.Travel" fileName="Logs\Api.Travel\${shortdate}.log" keepFileOpen="true" openFileCacheTimeout="120"
        layout="${longdate}|${api-traceidentifier}|${uppercase:${level}}|${api-userid}|${logger}|${message} ${exception:format=tostring}" />
  </targets>
  <!-- rules to map from logger name to target -->
  <rules>
    <logger name="*" minlevel="Info" writeTo="Api.Travel" />
    <!--Skip non-critical Microsoft logs and so log only own logs-->
    <logger name="Microsoft.*" maxLevel="Info"  writeTo="Api.Travel" />
    <logger name="*" minlevel="Warn" writeTo="apiEventlog" />
  </rules>
</nlog>

api-traceidentifier and api-userid are layout renderer as follows -
[LayoutRenderer("api-traceidentifier")]
[ThreadSafe]
internal class ApiUserLogin_RequestTokenLayoutRenderer : AspNetLayoutRendererBase
{
    protected override void Append(StringBuilder builder, LogEventInfo logEvent)
    {
        var httpContext = HttpContextAccessor?.HttpContext;
        if (httpContext == null)
        {
            Guid traceId = System.Diagnostics.Trace.CorrelationManager.ActivityId;
            var identifier = Convert.ToBase64String(traceId.ToByteArray()).Replace("=", "").Replace("+", "-").Replace("/", "_");
            builder.Append(identifier);
        }
        else
        {
            base.Append(builder, logEvent);
        }
    }
    protected override void DoAppend(StringBuilder builder, LogEventInfo logEvent)
    {
        var httpContext = HttpContextAccessor.HttpContext;
        builder.Append(LookupTraceIdentifier(httpContext));
    }
    private string LookupTraceIdentifier(HttpContext httpContext)
    {
        var traceId = Guid.Empty;
        if (Guid.TryParse(httpContext.TraceIdentifier, out traceId))
        {
            return Convert.ToBase64String(traceId.ToByteArray()).Replace("=", "").Replace("+", "-").Replace("/", "_");
        }
        return httpContext.TraceIdentifier;
    }

}

I would like to know if this approach is correct, if its performance safe. If not, will anyone pls be able to suggest any different approach.


text:
Q: What statistical test should I use? - Limited information Say I have a list of patients who have a disease A. I also know the prevalence of disease B in the general population, but I do NOT know the prevalence of disease A in the general population, and I don't have any other data on patients with disease B. I would like to perform a statistical test to find out whether disease A is associated with disease B. Is there a test I can perform with this limited information?

A: Assuming you know how many of your patients have disease B and you know the over all prevalence of B in the population then you can use the binomial distribution. Suppose, to make matters concrete, you have seen 100 people with A of whom 30 have B and you know the overall prevalence of B is 0.1. The you need to calculate the probability of seeing 30 or more positives (B) when you sample 100 times from a binomial distribution with $p=0.1$. Your favourite statistical software should let you do this as it is very tedious by hand.


text:
Q: About the square of orthogonal matrices If $Q^2$ is an orthogonal matrix, is $Q$ an orthogonal matrix? If not, what is the reason or could you please give me a counterexample?

A: Consider the matrix
$$Q=\begin{pmatrix}1&1\\-2&-1\end{pmatrix}$$
Clearly, $Q$ is not orthogonal, but
$$Q^2=\begin{pmatrix}-1&0\\0&-1\end{pmatrix}$$
is orthogonal.


text:
Q: Vault Transit signature: validate offline I have configured Vault Transit secrets engine with encryption key of type RSA-2048.
After signing some input data I have got a some signature and would like to verify it locally using public key and not interacting with Vault server.
Secrets engine: Transit
Encryption key type: RSA-2048 (public and private keys are available)
Sign parameters:

*

*Hash algorithm: sha2-256

*Signature algorithm: pss

Vault sign input: Base64("aaa") = "YWFh"
Vault sign output: vault:v1:fjgCO0r…==
In order to verify generated signature (for investigation purposes) I use web site https://8gwifi.org/RSAFunctionality?rsasignverifyfunctions=rsasignverifyfunctions&keysize=2048 that allows verify signature.
I provide there:

*

*public key

*input text

*generated signature( without prefix "vault:v1:")

and choose RSA Signature Algorithms = SHA256withRSA.
I have got an error Signature Verification Failed.
Could you explain what the structure of Vault generated signature and how it could be verified offline?


text:
Q: How to stop repo tool verifying SSL certificates? I'm building an elderly Yocto project.  repo (https://gerrit.googlesource.com/git-repo) is used to pull all the sources from their respective repositories & keep on top of changes.  Recently, repo has started checking CA certs for the https locations of these sources & refusing to download them as the host machine doesn't have them in its CA store (its an elderly host, to match the elderly Yocto project).  Under the hood, repo is using curl to download the sources, which handily provides a -k or --insecure option to bypass SSL certificate validation.
Is there a way to instruct the repo init command to do the same?  Or is my only option to keep visiting the sites, downloading the certs, adding them to the host cert store on a case by case basis?  (This, whilst protecting me from MITM attacks is impractical in this case).
I've tried export PYTHONHTTPSVERIFY=0 in my script that calls repo, but that doesn't help.
The errors from bitbake look like this: 17:18:25  fatal: unable to access 'https://git.openembedded.org/meta-openembedded/': server certificate verification failed. CAfile: /etc/ssl/certs/ca-certificates.crt CRLfile: none


text:
Q: Bot Framework v4.2 - Gacefully Recover From OnTurnError Exception I've been reading around the docs and looking at code samples for hints and inspiration and so far I've turned up nothing.
If we catch a global exception occuring in our bots we enter the OnTurnError handler:
// Catches any errors that occur during a conversation turn and logs them.
options.OnTurnError = async (context, exception) =>
{
    logger.LogError($"Exception caught : {exception}");
    await context.SendActivityAsync("Sorry, it looks like something went wrong.");
};

I haven't found anything in the docs or in any discussions where anyone is subsequently recovering from an error and restarting the conversation. I have a solution working but I'm wondering if I'm missing a more "best practice" method.  I'm just doing this at the moment:
options.OnTurnError = async (context, exception) =>
{
    logger.LogError($"Exception caught : {exception}");
    await context.SendActivityAsync("Sorry, it looks like something went wrong.");

    await _conversationState.DeleteAsync(context);

    await MyBot.SendIntroCardAsync(context, CancellationToken.None);
};

Without some kind of recovery like this we are leaving users stranded in dead conversations. Is there a better solution I'm not finding?

A: "Wiping" Conversation State and starting over is certainly one way to handle it, albeit a bit heavy handed. Calling DeleteAsync is the right way to do that though. Perhaps consider that you don't want to wipe all conversation state and maybe just wipe the DialogState instead? You would do that by just calling IStatePropertyAccessor<DialogState>::DeleteAsync instead. All depends on what you're maintaining in state and where though.
Now, where I see a problem is in trying to trigger your bot from the OnTurnError handler to sort of instantly restart the conversation when this happens. It looks like you're calling a static method (SendIntroCardAsync), which I suppose works, but it's created some very tight coupling that makes me uncomfortable.
Part of me wants to suggest that, if your MyBot really wants to be so involved in this level of exception handling, then maybe put an actual try/catch into the OnTurnAsync of the bot itself that basically keeps the handling of the activity square in its domain of responsibility and able to cleanly contain and trigger the SendIntroCardAsync. Then, in that case, the OnTurnError likely would never be hit unless the bot failed to handle the exception correctly. I would still keep everything in that handler logic except the call to SendIntroCardAsync, but now you know that's only ever going to be triggered in the scenarios where the bot fails to handle the exception correctly (which should be ultra-rare) or a piece of upstream middleware throws an exception. I don't really love this either though because it puts a responsibility into the bot that it could otherwise be agnostic of.
I think, given that, the final approach I would probably go with would be to build a specific piece of middleware that I would install at the "top" of the pipeline that does top level exception handling and, instead of knowing what exactly to call once it's done that handling, it actually just re-executes the entire pipeline again some configurable number of times. That way your downstream middleware and bot remain "dumb" from a top level exception handling perspective, yet you can still choose what to do (in your case wipe some state) by configuring a callback with this piece of middleware when you register it and, ultimately, your bot will see the replay of the turn once the exception has been handled as a fresh request. This middleware could even add something to the ITurnContext::TurnState bag that lets downstream logic detect that it's in a replay state and behave slightly differently. For example, imagine your bot being able to do this:
public async Task OnTurnAsync(ITurnContext turnContext, CancellationToken cancellationToken = default(CancellationToken))
{
   if(turnContext.IsReplayingTurnBecauseOfException())
   {
       ... send sorry msg and restart dialogs from wherever you want ...
   }
}

Where the IsReplayingTurnBecauseOfException (name up for debate) is an extension method for ITurnContext that would be provided along with this new piece of middleware to abstract code from reading TurnState details directly. Something like:
public static bool IsReplayingTurnBecauseOfException(this ITurnContext turnContext) =>
    turnContext.TurnState.ContainsKey("MySuperAwesomeExceptionHandlingMiddleware.IsReplayingBecauseOfException");

A: I'm using the Python version of the SDK and what worked for me was the on_turn method: Olace a try-except and after except to clear conversation:
async def on_turn(self, turn_context: TurnContext):
    try:
        await super().on_turn(turn_context)

        if self.state_profile_accessor.get(turn_context, CustomState) is not None:
            state_profile = await self.state_profile_accessor.get(turn_context, CustomState)

    except Exception as e:
        await self.conversation_state.clear_state(turn_context)
        await self.profile_state.clear_state(turn_context)
        # await self.profile_state.delete(turn_context)
        # await self.conversation_state.profile_state.delete(turn_context)
        time.sleep(2)
        message = MessageFactory.attachment("resetting")
        await turn_context.send_activity(message)
        await self.conversation_state.save_changes(turn_context)
        await self.profile_state.save_changes(turn_context)

Anyway I'm using a my own Custom State, but the .clear_state & .save_changes restarts it ok for my use-case. Hope this helps.


text:
Q: PostgreSQL data from last day evening to morning I have a table with this structure and data

Id
Data
Date
Time

1
sample1
2022-11-10
21:10:00

2
sample2
2022-11-10
23:50:00

3
sample3
2022-11-11
01:20:00

4
sample4
2022-11-11
05:30:00

5
sample5
2022-11-11
20:59:00

6
sample6
2022-11-11
23:01:00

7
sample7
2022-11-12
01:01:00

8
sample8
2022-11-12
04:01:00

.............................................
and so on
I want the structure in this way

date
Start Date
End Date

2022-11-11
21:10:00
05:30:00

2022-11-12
20:59:00
04:01:00

The time is not fixed, so hard to figure out. One logic is to get the data after 7 pm to 8 am but not sure. Any suggestions will be highly appreciated

A: database structure
create table work (id serial, data text, ev_date date, ev_time time);
insert into work(data, ev_date, ev_time) values
('sample1', '2022-11-10',   '21:10:00'),
('sample2', '2022-11-10',   '23:50:00'),
('sample3', '2022-11-11',   '01:20:00'),
('sample4', '2022-11-11',   '05:30:00'),
('sample5', '2022-11-11',   '20:59:00'),
('sample6', '2022-11-11',   '23:01:00'),
('sample7', '2022-11-12',   '01:01:00'),
('sample8', '2022-11-12',   '04:01:00');

query
the algorithm is as follows:

*

*we group by date

*we determine the interval -5 hours and + 8 hours

*we look for the first time values depending on the order (-5 hours - the first larger value, +8 hours - the first smaller value)

*removing the nulls

with s as (select ev_date from work group by ev_date),
     p as (select s.ev_date,
     (select work.ev_time from work
        where (s.ev_date - interval '5 hour')::date = work.ev_date
                and ((s.ev_date - interval '5 hour')::time < work.ev_time)
        order by work.ev_date,work.ev_time limit 1) start_time,
     (select work.ev_time from work
        where (s.ev_date + interval '8 hour')::date = work.ev_date
                and ((s.ev_date + interval '8 hour')::time > work.ev_time)
        order by work.ev_date,work.ev_time desc limit 1) end_time
     from s)
     select p.ev_date,p.start_time,p.end_time from p where p.start_time is not null and p.end_time is not null order by p.ev_date;

result
  ev_date   | start_time | end_time
------------+------------+----------
 2022-11-11 | 21:10:00   | 05:30:00
 2022-11-12 | 20:59:00   | 04:01:00


text:
Q: Can I use ReadProcessMemory to read the memory of a thread I'm trying to read the memory of a thread in a process for a string, and I was wondering if it's possible to use ReadProcessMemory() to read the memory of the thread.
I'm fairly new to the Win32 API so forgive my noobish-nes.

A: According to the Doc: About Processes and Threads
A thread is the entity within a process that can be scheduled for execution. All threads of a process share its virtual address space and system resources.
And in my opinion, you could search the memory of a process for a specific string instead of search the memory of a thread. If so, you could use ReadProcessMemory function to realize it.(The entire area to be read must be accessible, and if it is not accessible, the function fails.)
I suggest you could refer to the thread:How would I search the memory of a process for a specific string?


text:
Q: How to create a search bar and list (created with StreamBuilder and Listview from FireStore) scroll together? I'm relatively new to flutter/dart, and I'm trying to get the formatting on one of my pages working. I would like to have a search bar at the top followed by a list (filled with information from Firestore), and I want to have them scroll together rather than just the list.
Here's a section of my code so far:
  return Column (children: <Widget>[
    TextField(
        controller: _controller,
        onSubmitted: (String value) async {
          await showDialog<void>(
            context: context,
            builder: (BuildContext context) {
              return AlertDialog(
                title: const Text('Thanks!'),
                content: Text('You typed "$value".'),
                actions: <Widget>[
                  FlatButton(
                    onPressed: () {
                      Navigator.pop(context);
                    },
                    child: const Text('OK'),
                  ),
                ],
              );
            },
          );
        }),
    Expanded(child: buildLearnCards(context))
  ]);
}

Widget buildLearnCards(BuildContext context) {
  return StreamBuilder(

How should I go about this?

A: I will attempt to give a broad description of how to implement this as it requires a bit of infrastructure and knowledge of State Management. I would recommend using provider to manage state. In the constructor of your provider/model, retrieve the list of documents from Firestore and store it in a List. Then use this tutorial to filter your documents based off the search text field. Every time the filterSearchResults method is called, call notifyListeners() at the end of your function. Then in your list of documents in your widget use a Consumer as mentioned in this tutorial to retrieve the list of documents from your provider and display in a ListView however you want. Hope it helps, and ask any questions if you are coming across issues.


text:
Q: Dust.js templates outputting  I have a dust template that is using a partial to render fields in a form:
{#Person}
{>"partial/field" field="FirstName" /}
{>"partial/field" field="MiddleName" /}
{>"partial/field" field="LastName" /}
{/Person}

This is resulting in HTML that looks mostly correct, except there's strange spacing in between each field's output.  When I inspect the markup using Chrome's developer tools, I see a mysterious HTML non-breaking space entity being output as  but I didn't put it there.

A: The solution turned out to be that I had to change the encoding for the partial template file from UTF-8 to Codepage 1252.  Since I use Visual Studio, this was pretty easy: use File > Advanced Save Options...
It appears that entity  is used as the UTF byte order marker and was being output into the resulting HTML.  Hope this helps someone else struggling with this!


text:
Q: Multiple ImageButton objects where each launches a different website Suppose one of my screens has multiple ImageButton objects and each one should launch a unique website when clicked. For example, if the ImageButtons featured pictures of various restaurant logos (Burger King, Wendys, etc) when the ImageButton featuring the Wendys logo was clicked "wendys.com" would open. If the id of each ImageButton was something like
android:id="@+id/wendys"

is there any way that my launchWebsite() method in java could look something along the lines of
public void launchWebsite(View view) {
    Intent openURL = new Intent(android.content.Intent.ACTION_VIEW);
    openURL.setData(Uri.parse("https://www." + [insert id here] + ".com"));
    startActivity(openURL);

}

Thanks so much in advance, I am relatively new to Android Studios

A: You would need to add a onClickListener for each ImageView and modify your method a little bit:
Change the parameter to pass a String (Do you need the view being passed? If yes, keep it there)
ImageButton ib_wendys = findViewById(R.id.ib_wendys);
        iv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                launchWebsite("wendys") //I would even consider to pass the whole URL since it could be different than .com
            }
        });

Method:
public void launchWebsite(String url) {
    Intent openURL = new Intent(android.content.Intent.ACTION_VIEW);
    openURL.setData(Uri.parse("https://www." + url + ".com"));
    startActivity(openURL);

}


text:
Q: Password authentication failing for Postgresql I'm creating a Rails app and using a Postgresql database with it. I've created a few tables and a user, core, which is the owner of each of the tables.
postgres=# create user core with password 'n7zD5FG5';
CREATE ROLE
postgres=# create database core_apps_prod with owner core;
CREATE DATABASE
postgres=# create database core_apps_dev with owner core;
CREATE DATABASE
postgres=# create database core_apps_test with owner core;
CREATE DATABASE

And my database.yml file:
development:
  adapter: postgresql
  database: core_apps_dev
  username: core
  password: n7zD5FG5
  host: localhost

However, when I run rake db:migrate, I get the error
rake aborted!
FATAL:  password authentication failed for user "core"

I also cannot connect to psql manually: psql -U core -W -d core_apps_dev - I get the same error.
How can I allow core to connect to Postgresql on localhost?
The output of SELECT * FROM pg_roles where rolname='core'; is:
 rolname | rolsuper | rolinherit | rolcreaterole | rolcreatedb | rolcatupdate | rolcanlogin | rolreplication | rolconnlimit | rolpassword | rolvaliduntil | rolconfig |  oid
---------+----------+------------+---------------+-------------+--------------+-------------+----------------+--------------+-------------+---------------+-----------+-------
 core    | f        | t          | f             | f           | f            | t           | f              |           -1 | ********    |               |           | 16392

A: You need to add privileges to the role when you create it. To allow logging in and using rake db:create use the following:
create role core with login createdb password 'n7zD5FG5';

To fix your problem, try altering the role to allow login:
alter role core with login;

And if that doesn't work, see if making the login valid forever works:
alter role core valid until 'infinity';

More about roles: http://www.postgresql.org/docs/8.2/static/sql-createrole.html
Edit:
I also had to do this when I installed postgres:
$ psql postgres -c 'CREATE EXTENSION "adminpack";'

A: The issue turned out to be an issue with the port. The Postgresql Activerecord adapter defaults to port 5432, while the port in my configuration was port 5433. My database.yml now looks like this:
development:
  adapter: postgresql
  database: core_apps_dev
  username: core
  password: n7zD5FG5
  host: localhost
  port: 5433

A: The newly created user probably is lacking database privileges. There are many different privileges you can give to a user.
Assuming that you have admin account access to psql, go into psql and run
GRANT ALL PRIVILEGES ON DATABASE core_apps_dev to core;

A: Can you please try
alter role core with password "n7zD5FG5";


text:
Q: In-app billing. How to store information that user has paid? There was a similar subject here
Okay. We can find out about user's purchase using RESTORE_TRANSACTIONS request to Google Play.
But. It is written in documentation that
" You should use the RESTORE_TRANSACTIONS request type only when your application is installed for the first time on a device or when your application has been removed from a device and reinstalled."
Why not after every start?
It looks comfortable and possible to query Google Play every time when the app starts.
Otherewise
1) I should store information about payment on my WEB server
2) Or I should save this info to sdcard. The record should be secure, including
device ID, so that copy on another device will not work
So. Which way is better?
Thanks.

A: I would suggest:
3) Use the in-app Shared-Preferences Class or SQLite Database
(Check this page: http://developer.android.com/guide/topics/data/data-storage.html)
Encryption is always good, but this way the data is so to say attached to your application and can usually not be accessed by other apps.


text:
Q: Ring Homomorphism Confusion (correspondence theorem) I get part b. I have some difficulties with part a.
I know that ideals of $C[t]$ are generated by the lowest degree monic polynomial so if we take the inverse map of $p(t)$, we would get our ideal by the correspondence theorem(provided below). I don't get why the inverse map is equal to $p(x)$ and not $p(x,y)$?

A: Let $J$ be the ideal of $\mathbb C[t]$ generated by the polynomial $p(t)$.  Let $I$ be the inverse image of $J$ under the ring homomorphism $\varphi: \mathbb C[x,y] \rightarrow \mathbb C[t]$.  The claim is that $I = I_1$, where $I_1 = \langle y - x^2, p(x)\rangle$.
This follows from the correspondence theorem: both $I$ and $I_1$ are ideals of $\mathbb C[x,y]$ which contain the kernel of $\varphi$, and we have $\varphi(I) = \varphi(I_1) = J$.  Since $\mathfrak a \mapsto \varphi(\mathfrak a)$ is a bijection from the set of ideals of $\mathbb C[x,y]$ which contain the kernel of $\varphi$ onto the set of ideals of $\mathbb C[t]$,  you can conclude that $I = I_1$.


text:
Q: Confirmation when installing with pip globally Sometimes when working with Python projects one can forget to activate a virtual environment.
Is there a way to get an explicit confirmation when installing Python modules with pip to the global scope instead of a virtual environment?

A: You can try to wrap pip install, e.g.:
import pip

def install(package):
    pip.main(['install', package])

# Example
if __name__ == '__main__':
    if not hasattr(sys, 'real_prefix'):
        # replace this with your confirmation callback
        print('Warning! installing in global scope!')
    install('argh')

Sources:
Installing python module within code
Python: Determine if running inside virtualenv

A: You could use:
$ pip config set install.require-virtualenv true

but this results in a rather inconvenient error when trying to install without a virtual environment:
ERROR: Could not find an activated virtualenv (required).

I have opened a PR implementing a more user-friendly option (at least in my opinion) to enable a warning instead of an error that also has a prompt to ask whether you'd like to continue or not. If that gets merged then you'll be able to do the following:
$ pip config set install.global-install-warning true
$ pip install -r requirements.txt
WARNING: Could not find an activated virtualenv.
Proceed (y/N)?


text:
Q: Available Fonts on iOS I am trying to make a UILabel in Swift -- the label will display a simplified Chinese character.   I am trying to use the Kaiti SC font that comes with the Mac, it is available in the Font Book and in all of the programs on the Mac, but when I list out the fonts using the following code, it does not show up.
    let fontFamilyNames = UIFont.familyNames()

    for familyName in fontFamilyNames {

        print("Font Family Name = [\(familyName)]")
        let names = UIFont.fontNamesForFamilyName(familyName)
        print("Font Names = [\(names)]")
    }

The code for my UILabel is as follows:
   let characterLabel:UILabel! = UILabel(frame: CGRectMake(600,140,300,300));

   characterLabel.font = UIFont(name:"Kaiti SC" , size:250.0);

   characterLabel.text = "说";

I would have thought all of the fonts on the Mac would be available in my Swift program.   (The code, of course, does work with other fonts like "Baskerville", the Chinese characters simply don't look good in those fonts.)  Any ideas?

A: And here Swift 5 Version:
let fontFamilyNames = UIFont.familyNames

for familyName in fontFamilyNames {
    print("Font Family Name = [\(familyName)]")
    let names = UIFont.fontNames(forFamilyName: familyName)
    print("Font Names = [\(names)]")
}

A: The font Kaiti SC is not available on iOS, for a full list of available font check http://iosfonts.com/
Although the font is available on OS X does not mean that it is available or fully available on iOS.

A: This seems to be the answer to my question.
If you go to https://support.apple.com/en-ap/HT202771, you will see what fonts are available in iOS.  In addition, it says "Apps can download the following fonts if necessary:" and these include a number of Asian and other fonts.  They do not tell you how to access those fonts.  Apparently, those fonts are on the Mac, and must be specifically downloaded to iOS.
This site shows you how to do that:  http://www.perfectline.co/blog/2010/05/uiappfonts-custom-fonts-with-the-iphoneipad-3-2-sdk/
The two tricks I found necessary: (1) you need to add a new key in info.plist and (2) you must write a function to list out the font families, so you know the actual font name you need to use in your program.   This site has such a function: http://giordanoscalzo.tumblr.com/post/95900320382/print-all-ios-fonts-in-swift


text:
Q: Does break point trap always mean program was run from the debugger? I'm analyzing a core file which says:
Program terminated with signal 5, Trace/breakpoint trap

From this line can I be sure this was due to program hitting a breakpoint under GDB?
Is there any scenario the above error is possible when it is NOT run under the debugger?

A: No, the program need not have run under a debugger for this to happen.
Try running a program and then using kill -n 5 myProgram (or equivalently kill -s SIGTRAP). It will send a SIGTRAP signal to the program in question, which will most likely cause it to terminate. If it produced a core dump in the process then it would have the message you show.
Or, as mentioned in the comments, the program could have raised that signal itself.


text:
Q: Set-returning functions are not allowed in CASE in postgreSQL I am trying to run this query was able to till some time ago. I don't know what went wrong and I started getting this error now?
Your database returned: ERROR: set-returning functions are not allowed in CASE Hint: You might be able to move the set-returning function into a LATERAL FROM item.
My query:
SELECT distinct
(CASE
WHEN {PERIOD} = 'Previous Quarter' AND pto.pto_start_date < (date_trunc('quarter', now() - INTERVAL '1 month') + INTERVAL '1 month')::date AND pto.pto_end_date >= (date_trunc('quarter', now() - INTERVAL '1 month') + INTERVAL '1 month')::date
THEN generate_series(pto.pto_start_date, pto.pto_end_date, '2 day'::interval)
WHEN {PERIOD} = 'Current Quarter' AND pto.pto_start_date < (date_trunc('quarter', now() - INTERVAL '1 month') + INTERVAL '1 month')::date AND pto.pto_end_date >= (date_trunc('quarter', now() - INTERVAL '1 month') + INTERVAL '1 month')::date
THEN generate_series(pto.pto_start_date, pto.pto_end_date, '1 day'::interval)
ELSE
generate_series(pto.pto_start_date, pto.pto_end_date, '1 day'::interval)
END) AS dt
FROM cust_pto pto

Start dates and end Dates:

What has gone wrong?

A: Why you're getting the error now: you upgraded to postgres 10. Set returning functions are no longer allowed.
What to do: there is more than one way to accomplish what you're trying to do. For the sake of keeping it as close as possible to your original query, all you have to do is put your CASE statement inside generate_series:
SELECT distinct generate_series(
        pto.pto_start_date,
        pto.pto_end_date,
        CASE
        WHEN {PERIOD} = 'Previous Quarter' AND pto.pto_start_date < (date_trunc('quarter', now() - INTERVAL '1 month') + INTERVAL '1 month')::date AND pto.pto_end_date >= (date_trunc('quarter', now() - INTERVAL '1 month') + INTERVAL '1 month')::date THEN
            '2 day'::interval
        ELSE
            '1 day'::interval
        END
) AS dt
FROM cust_pto pto