text:
Q: Why "mailto:" is considered to be a not spam friendly way of sending email? I am creating the front-end of a site. There is a place where the user can send an e-mail to the site owner, which I have implemented via an anchor tag with href="mailto:...". Now the customer says that we need a way other than mailto, which he says is spam-friendly.  He also tells me that there are tons of JavaScript codes that I can use. Who can tell me what the problem is? What is the customer talking about? :) How can I solve this problem that I don't even understand?
EDIT: After all when I understand what my customer wants I understand also that I need a JavaScript email address obfuscator!!! Thanks to all!

A: If you put an e-mail address on a website, spammers can use automated scripts to find it. From that time on, it will be easy for them to send spam to the e-mail address.
If you use a form and let a server side script send the mail, the spammer can only abuse that form. You can protect the form using all kinds of methods, amongst which are captchas.
Also, if you do put the e-mail address on the site, but you're using Javascript to do so, the script that detects e-mail addresses now has to be much more complex, because it need to be able to execute or at least parse the javascript code.

A: because a bot could scrape the html of a site and the email address is exposed to said process - thus it is compromised in terms of being on a spam list.
edit: Think Captcha or similar "humanity required" cognitive barriers that are so well established - this was to prevent the spaming / scraping of mailto links. GL !

A: the problem with mailto: is that web scrapers can be used to "harvest" into a "spam mailing list". these are common in e-mail marketers (email advertising). also, search engines like Google will also pick them up, making your email a public item, easilty searchable, easily spammable.
common methods employed today to prevent spamming thru email is a contact page & following/friending in social sites (since social sites have the ability to block users, spammers won't waste time making accounts and keep friending/following you).

A: Google has an option that you may be able to use.  They have reCAPTCHA Mailhide which hides emails from spam bots.  It presents a link to a reCAPTCHA page that must be answered before revealing the address.  Their reCAPTCHA API contains the code that you may be able to use on your site.

A: The easiest way to prevent having an email address being added to a spam list is to not give it to the user until they give up theirs.
Make a contact form that submits to a simple script that emails the form contents to your customer (there are a million tutorials on Google). You may still get spam if a bot fills in the form, but that can be prevented with a suitable Captcha.
When your customer replies to an email, only then will the other side know his email address.

A: I would create a dedicated contactform page with a captcha.
That way you don't even have to expose the email address on the page.
Also you don't have to rely on people having mail software installed on their computers.

A: Mailto has a few problems that are stated above but you can easily fix the spam, one.
There are sites that can encode your link with javascript for you:
http://hivelogic.com/enkoder/
http://www.mailtoencoder.com/
This way you can use mailto without worrying about spam! Its worked for me so far.


text:
Q: mongoDB update collection documents I have an update request and that request should update the existing data in my database like the flowing example
existing data => [{_id:"abnc214124",name:"mustafa",age:12,etc...}, {_id:"abnc21412432",name:"mustafa1",age:32,etc...}, {_id:"abnc214124123",name:"mustafa3",age:52,etc...} etc... ]
new Data => [{_id:"abnc214124",name:"mustafaxxx",age:12,etc...}, {_id:"abnc21412432",name:"mustafa1",age:35,etc...}, {_id:"abnc214124123",name:"mustafa3",age:20,etc...} etc... ]
the updated fields :
in the first document name
second age
third age
what is the best way to update the existing data without affect the old fields (not modified fields)
BTW
I tried to loop through documents and check the fields then update them but this will cause long response time and to solve this I used multithread on NodeJS and now I need better solution

A: To Update the multiple documents of a collection. you can use updateMany()
This is the example of updateMany()

db.collection.updateMany(
   <filter>,
   <update>,
   {
      multi: true
   }
)

In Above example:
filter parameter specifies which documents to update
update parameter specifies the update to be performed

redpajama_set_name: RedPajamaStackExchange


text:
Q: Swipe until element visible in Android Espresso I have a long vertical screen with data entry form. I need swipeUp (scroll down) this screen until one of form's field is displayed on screen.
I try use swipeUp() and scrollTo() ViewActions on the elements located higher on the screen, but it didn't help me, that these elements hiding from screen after swiping.

A: The idiomatic approach today would be to use RepeatActionUntilViewState. For example, the following would swipe up on an element with ID largeElementId up to 10 times until a view with text "Target text" is visible to the user:
onView(withId(R.id.largeElementId)).perform(repeatedlyUntil(swipeUp(),
        hasDescendant(withText("Target text")),
        10));

A: It should be something like this:
boolean found = false;
int i = 0;
while (!found && i < MAX_SWIPES) {
    onView(withId(R.id.largeElementId)).perform(swipeUp());
    SystemClock.sleep(500);

    try {
        uiElementToSearch.check(matches(isCompletelyDisplayed()));
        found = true;
    } catch (Exception e) {
        // The search continues
    }
    i++;
}

if (!found) {
    Assert.fail("The element has not been found.");
}


text:
Q: Copying HTML Tables from Outlook to Excel Have been trying to get Excel VBA to export HTML tables - keep getting a runtime error.
Something similar does work when run in Outlook VBA using: For Each Item In Application.ActiveExplorer.Selection
What I want to do is to copy the HTML tables and convert them to Excel tables
From here I will be able to work on the data to extract and convert to an ongoing spreadsheet record
Dim OutlookMail As Outlook.MailItem
Dim myInbox As Outlook.MAPIFolder
Dim myitems As Outlook.Items
Dim x As Long
Dim lRow As Long
Dim lCol As Long
Dim wdDoc As Object
Dim Item As MailItem
Dim r As Object
Dim myInspector As Outlook.Inspector

Sub getOrderEmailData()

    ' *************This section cycles through email accounts until it finds "testname@icloud.com" and selects the mailitems in this account inbox ********
    Set myAccounts = outlookapp.GetNamespace("MAPI").Stores

    For i = 1 To myAccounts.Count
        If myAccounts.Item(i).DisplayName = "testname@icloud.com" Then
            Set myInbox = myAccounts.Item(i).GetDefaultFolder(olFolderInbox)
            Debug.Print myInbox
            Exit For
        End If
    Next
    If myInbox Is Nothing Then Exit Sub ' avoid error if no account is chosen

    Set myitems = myInbox.Items 'select the Inbox

    ' show some feedback if no email is found
    If myitems.Count = 0 Then
        MsgBox "Nothing found. Try another account."
        Exit Sub
    End If
    Count = 0

'*************** This section should copy however many tables are found in the HTML email on Outlook to Excel ***********************

   For Each Item In myInbox.Items
       'On Error Resume Next
        Set myInspector = Item.GetInspector
        Set wdDoc = myInspector.WordEditor  <<<<-------- Here is where the program fails - "Run time error - The operation failed"

            Debug.Print Item.Subject
            If Item.Subject = "Alert from MadeUp Solutions" Then

                deleteSheet ("test")

                    'to get all tables
                    Debug.Print wdDoc.Tables.Count
                    For x = 1 To wdDoc.Tables.Count
                        'Select table range
                        Set r = wdDoc.Tables(x)
                        'Copy and paste next table
                        r.Range.Copy
                        Worksheets("Test").Cells(lRow + 1, 1).Select
                        Worksheets("Test").Paste
                        On Error Resume Next
                        'Find row extent of data in each sheet
                        lRow = Worksheets("Test").Cells.Find(What:="*", After:=Range("A1"), LookAt:=xlPart, LookIn:=xlValues, SearchOrder:=xlByRows, SearchDirection:=xlPrevious, MatchCase:=False).Row
                    Next x

            End If
        Next

A: Try to call the Display method before getting the Word editor to initialize it:
For Each Item In myInbox.Items
    'On Error Resume Next
    Item.Display
    ' ...
    Set myInspector = Item.GetInspector
    Set wdDoc = myInspector.WordEditor
    ' ...
    Item.Close olSave
Next

It also makes sense to run the code for getting the Word editor instance in the Inspector's Activate event to be sure the editor is fully initialized when you try to get its instance.

A: If GetInspector and Word editor do not work for you, the only option is to read the MailItem.HTMLBody property and load it into an instance of the HTMLDocument object, which you can then use to extract HTML tables.


text:
Q: gcm canonical id should be updated or not I am working on an android project which uses gcm. I came to know that if we uninstall the appfrom device and reinstalled most of the time the device gets new registration id.Then if we do not delete the old one from application server and update, The messages will be sending to both ids and in the response it will be showing canonical id is present.My question is, at this point message will be successfully send to that device or not?

A: When you receive a canonical registration ID in the response from Google, the message was accepted by the GCM server and the GCM server would attempt to deliver it to the device. Whether it is actually sent to the device depends on whether the device is available (i.e. connected to the internet).
So if your server sends a GCM message to both the old ID and the new ID, the device will probably get two messages.

Canonical IDs
On the server side, as long as the application is behaving well,
  everything should work normally. However, if a bug in the application
  triggers multiple registrations for the same device, it can be hard to
  reconcile state and you might end up with duplicate messages.
GCM provides a facility called "canonical registration IDs" to easily
  recover from these situations. A canonical registration ID is defined
  to be the ID of the last registration requested by your application.
  This is the ID that the server should use when sending messages to the
  device.
If later on you try to send a message using a different registration
  ID, GCM will process the request as usual, but it will include the
  canonical registration ID in the registration_id field of the
  response. Make sure to replace the registration ID stored in your
  server with this canonical ID, as eventually the ID you're using will
  stop working.

(Source)
You can overcome this problem by assigning a unique identifier to each instance of your application. If you store that identifier in the device's external storage, it won't be deleted when the app is uninstalled. Then you can recover it when the app is installed again. If you send this identifier to your server along with the registration ID, you can check if your server has an old registration ID for this identifier, and delete it.

A: @Eran We have two option either to remove older registration ids or update with Key and position of canonical id. I prefer to update... You can view working code of mine i have answered here Steps to Update Canonical Ids


text:
Q: Find a certain word in a string using R I'm trying to use the billboard tibble in R to find all the songs titles that contain the word "Love" in them using string basics but I'm struggling.
The end result should look like this:
 [1]"I'm Outta Love"          "My First Love"
 [3] "My Love Goes On And ..." "He Loves U Not"
 [5] "Love Is Blind"           "I Will Love Again"
 [7] "Feels Like Love"         "Let's Make Love"
 [9] "My Love Is Your Love"    "It Must Be Love"
 [11] "He Can't Love U"         "I Just Wanna Love U ..."
 [13] "U Don't Love Me"         "Don't Say You Love M..."
 [15] "Love's The Only Hous..." "Because You Love Me"
 [17] "Love Sets You Free"      "I Knew I Loved You"
 [19] "I Think I'm In Love ..." "Live, Laugh, Love"
 [21] "The Chain Of Love"

A: data("billboard")

# as suggested by @Cath which is of course the way to go
grep("Love", billboard$track, value = TRUE)

# original answer
billboard$track[grepl("Love", billboard$track)]

#  [1] "I'm Outta Love"          "My First Love"           "My Love Goes On And ..." "He Loves U Not"          "Love Is Blind"
#  [6] "I Will Love Again"       "Feels Like Love"         "Let's Make Love"         "My Love Is Your Love"    "It Must Be Love"
# [11] "He Can't Love U"         "I Just Wanna Love U ..." "U Don't Love Me"         "Don't Say You Love M..." "Love's The Only Hous..."
# [16] "Because You Love Me"     "Love Sets You Free"      "I Knew I Loved You"      "I Think I'm In Love ..." "Live, Laugh, Love"
# [21] "The Chain Of Love"


text:
Q: gradle withJavadocJar() and withSourcesJar() for android library Is there a way to leverage the new functions withSourcesJar() and withJavadocJar() for Android library projects? Currently when I try to use it I get:
> SourceSet with name 'main' not found.

A: With the latest Gradle version 6.0.1, there seems to be no way to use these new methods in Android library projects. Here's why I believe that's the case:

*

*The two methods withJavadocJar() and withSourcesJar() on the java extension have the default main source set hardcoded, see here and here.

*There are two methods with the same names (withJavadocJar() and withSourcesJar()) which can be used in feature variant declarations. However, it seems that Android Gradle builds don't use feature variants, i.e., these methods can't be used either.

A: The documentation states, that these come from the JavaPluginExtension - but not from Android DSL. So they can only be used in conjunction with apply plugin: "java" or apply plugin: "java-library", but not with apply plugin: "com.android.application", apply plugin: "com.android.library" and alike. The name of these tasks also suggest that it's common Java (*.jar) and not Android (*.aar). On Android, this would only make sense for a *.jar library, which uses pure Java features, but no Android features at all (which is limited in functionality).
In short, apply plugin: "java-library" would permit accessing these.

A: With Gradle 7.2 I "recreated" withJavadocJar and withSourcesJar using Gradle Kotlin DSL:
val sourceFiles = android.sourceSets.getByName("main").java.getSourceFiles()

tasks.register<Javadoc>("withJavadoc") {
    isFailOnError = false
    dependsOn(tasks.named("compileDebugSources"), tasks.named("compileReleaseSources"))

    // add Android runtime classpath
    android.bootClasspath.forEach { classpath += project.fileTree(it) }

    // add classpath for all dependencies
    android.libraryVariants.forEach { variant ->
        variant.javaCompileProvider.get().classpath.files.forEach { file ->
            classpath += project.fileTree(file)
        }
    }

    source = sourceFiles
}

tasks.register<Jar>("withJavadocJar") {
    archiveClassifier.set("javadoc")
    dependsOn(tasks.named("withJavadoc"))
    val destination = tasks.named<Javadoc>("withJavadoc").get().destinationDir
    from(destination)
}

tasks.register<Jar>("withSourcesJar") {
    archiveClassifier.set("sources")
    from(sourceFiles)
}

Put this into your gradle.build.kts file and then run ./gradlew withJavadocJar and ./gradlew withSourcesJar (or use the tasks to create artifacts for publishing).
android.sourceSets.getByName("main").java.getSourceFiles() is the Android specific part to retrieve the "main" source files.


text:
Q: Get data from database for graph Android I have setup a SQLite database in my android application. I used a tutorial from google and my database works (I can put data in it and read it out in an other form). Now, I want to get the column price and put it in a graph. I can draw the graph already with hard coded values. I'm trying:
Cursor item0 = _dbHelper.fetcAllBoughtItems();
startManagingCursor(item0);
String xaxis[]=new String[4];
        xaxis[0]= item0.getString(item0.getColumnIndexOrThrow(databaseManager.KEY_BOUGHT_ITEM));
        xaxis[1]="2007";
        xaxis[2]="2008";
        xaxis[3]="2009";

I get the follow error (I know it's telling me what's wrong, but I can't get it fixed)
04-27 10:03:21.382: ERROR/AndroidRuntime(6920): java.lang.RuntimeException: Unable to start activity ComponentInfo{Adforce.files/Adforce.files.summarySpendBudget}: android.database.CursorIndexOutOfBoundsException: Index -1 requested, with a size of 5

Can someone help me please?
Regards
Edit:
fetchAllBoughtItems() code is:
public Cursor fetchAllBoughtItems(){ //function to fetch all bought items
    return mDb.query(DATABASE_TABLE_ItemB, new String[]{KEY_ROWID_ItemB, KEY_BOUGHT_ITEM, KEY_PRICE_ItemB }, null, null, null, null, null);
    }

A: fetcAllBoughtItems() returns Cursor without column named databaseManager.KEY_BOUGHT_ITEM
fix fetcAllBoughtItems()
EDIT:
add item0.moveToFirst() before item0.getString(... and check if will return true


text:
Q: React why 'clearTimeout' not work on useeffect return callback I have a question about using setTimeout, clearTimeout on React useEffect Hook.
    useEffect(() => {
        let timer = setTimeout(() => {
            setRemainingSecond(remainingSecond - 1);
        }, 1000);
        return (() => {
            clearTimeout(timer);
        });
    }, [remainingSecond]);

This is my react code with countdown component.
I understand why i should clear timerId everytime the component unmounts due to the memory leak and other sync problem.
But clearTimeout is meant to be used to cancel setTimeout callback function right?
and since useEffect return callback function will be called before component mounts, shouldn't timeout callback function be canceled and nothing happens?

A: the useEffect return callback will run each time the dependency array changes OR the before the component unmounts (NOT mounts).
In this instance, your timer will continue to go down by 1 every second, but if your component unmounted for some reason, it won't try and call setRemainingSecond once the 1000ms is up, preventing the infamous error:

Can only update a mounted or mounting component. This usually means you called setState() on an unmounted component. This is a no-op. Please check the code for the undefined component.


text:
Q: Prove $[0,1]$ isn't a differential variety or manifold.
Prove $[0,1]$ isn't a differential variety or manifold with the usual topology in $[0,1]$.

Well my idea is using the definition of differential structure we can see that $[0,1]$ doesn't have a differential structure so it can't be a manifold.
In my opinion the point that make that $[0,1]$ isn't a manifold is that if we take charts like $(a,b)$ with $0 < a < b < 1$ or $[0,a)$ or $(a,1]$ and a the identity as the function of the charts $(U_i,Id)$ $\forall i \in I$ it provoques that the image of $[0,a)$ or $(a,1]$ isn't an open set in $\mathbb{R}$ with the usual topology.
I don't know if I am in a correct way or not.

A: The differentiable structure is not necessary here. The point is that the unit interval $[0,1]$ with its usual topology is not locally homeomorphic to an open interval.
To prove this, you must prove that no charts exists at the boundary points, but you had the idea right. A connected open neighborhood in $[0,1]$ of either boundary point is homeomorphic to a half-open half-closed interval. Since you can always find a connected subneighborhood, we can restrict to this case. Hence if we prove a half-open half-closed interval is not homeomorphic to an open interval, we will be done.
This can be done with a connectedness argument: removing any point from an open interval will disconnect it, but removing the present boundary point from a half-open half-closed interval leaves it connected. Hence these spaces cannot be homeomorphic.
It's worth remarking that if you really want to prove the usual topology on the unit interval is not a topological manifold, you must check this for arbitrary open subsets of Euclidean space and not just open intervals. It's a significant theorem that Euclidean spaces of different dimension are not homeomorphic.
You can still use connectedness arguments to differentiate between half-open half-closed intervals and opens subsets of $\mathbb R^n$ for $n\geq 2$ however: removing two points disconnects the former but not the latter.


text:
Q: SharePoint 2013 Term Store Navigation does not show drop down links after branding I've setup the global navigation in my Sharepoint 2013 site using Managed Navigation and the Term Store Management Tool. Most of my top menu items have sub menu items that would normally appear as a drop down when hovering over the top menu item.
My issue is that the drop down menu does not appear to work after I apply branding to my 2013 site. With no branding the drop down menus work just fine.
I created an HTML page, used the Design Manager setup my branding and also used the menu snippet and applied it to my HTML page. I can see all of my top level items which are being driven by the Term Store but no sub menu drop downs.
Can anyone please provide some help.
Thanks.

A: I was having the same issue.
I went into seattle.html and copied the topnav code from their

        <link rel="stylesheet" type="text/css" href="/_layouts/15/1033/styles/menu-21.css" />

Default Publishing Site

-->

Replace the snippet with this code

A: When you created your snippet, there is a preview screen. That should show you the result of your snippet, BEFORE you copy and paste that snippet into your site.
Those snippets are configurable for number of levels to show. you may want to check that the snippet is configured the number of levels you want.\
The following is from the snippet guidance for Top Navigation snippet in SharePoint 2013:

Top Navigation
About this Component
The navigation snippets provide common navigation links and menu items
  on a site page.
The contents of the navigation menu are defined in Navigation
  Settings. There, you can choose between navigation content defined by
  site structure or navigation content defined by site metadata and
  keywords.
You can change how the menu looks and functions (including the number
  of flyout levels via the StaticDisplayLevels property).


text:
Q: jQuery AJAX Request 302 Redirect - What callbacks are available? I'm working with an older system that is using jQuery 1.2.6. I am sending an AJAX Request via the jQuery.ajax function. The URL that it is hitting is sending a 302 HTTP Redirect response and eventually ends up with a 200 HTTP OK response. I have registered both a success and a complete callback, however neither of them are called.
My question is: Are there any callbacks that can/will be called after a redirect occurs?
jQuery.ajax({
    type: "GET",
    url: url,
    data: null,
    dataType: "json",
    async: false,
    success: function(data, textStatus) {
        alert("SUCCESS CALLED: " + textStatus);
    },
    complete: function(xhr, status) {
        alert("COMPLETE CALLED");
    }
});

NOTE: The response is HTML, not JSON, however changing the dataType to html alters the request. It sends an OPTIONS request instead of a GET request, and it also no longer redirects. I need these redirects to occur.

A: As per the comments:

Changing the dataType to html alters the request. It sends an OPTIONS request instead of a GET request, and it also no longer redirects.

This will happen when you send a crossdomain request. I.e., the url does not point to the same domain as where this script is been served from. This namely violates the Same Origin Policy. Not having access to the server code also confirms that it runs on a different domain. The HTTP OPTIONS request sent by jQuery should let the server return a response with an Allow header with a list of request methods which are allowed to be used on the particular URL so that jQuery could then continue accordingly. This is apparently not happening.
If the server is really completely out your control, you'd need to create a proxy on your server which connects the desired URL and streams its response back. Then alter the jQuery url to point to the proxy URL instead. It's unclear what programming language you're using, but your question history suggests that you're familiar with Java, in that case you can use a simple servlet with java.net.URLConnection or Apache HttpComponents Client for this.

A: Use jquery ajax option
dataType: 'jsonp'
to perform the redirect for cross-domain requests.
(Was tested in FF/Chrome browsers)
But this resolution is useful only if you are not handle the response or if the cross-domain-url supports jsonp approach.


text:
Q: What is the alternative to toArray() if there is a limit put equal to 1? state.db
      .collection(`${collection}_TRENDING`)
      .find(paramsForFind)
      .sort({ timeStamp: -1 })
      .limit(1)
      .toArray();

I don't want to convert to array since it's only one record that this command will return. If I don't use toArray then it throws a cursor object. I just want the data that is returned from the query which backend consumes and throws it to the frontend.
How is it possible? One naive way would be to iterate over the cursor and exit after reading the first and only document. I would prefer a better-engineered way than a for loop.
The module used is:
const MongoClient = require("mongodb").MongoClient;


text:
Q: Delphi, Dependency Injection and Memory Management Dependency Injection is certainly one of the most important concepts when trying to write testable code. But while Java and C# have garbage collection, Delphi has not and normally, object disposal is managed using the ownership-principle (the one who creates the object destroys it). This is nicely supported by the try..finally construct
Obj := TObject.Create;
try
  ...
finally
  Obj.Free;
end;

Now what if one uses dependency injection:
constructor TFileLister.Create(FileSystem: TFileSystem);

Who should now be responsible for destroying the FileSystem object? Does the ownership-principle still work here?
I know that interfaces are a solution to this problem (thanks to the fact that they are reference-counted). But what if there are no interfaces (say in some legacy code)? What other approaches or best practices are there to handle memory management when using dependency injection?

A: You have to come up with an owner for the FileSystem object. This can be either the entity that creates the TFileLister instances, or you could pass ownership to the file lister, documenting that it will free the file system that was passed to the constructor.
The right approach depends on course on your particular application. For example, if other objects would also use the same file system object, it shouldn't be owned by one of these such as the file lister, but by the object that ties it all together. You could even make the file system object global if it only makes sense to have one of it.
In short, you'll have to do a little more thinking than in Java but that's not necessarily a bad thing.

A: It's almost always preferable to regard the entity that create an object also to be its owner (i.e. responsible for destroying it).
To understand why I say this, consider the alternative. Suppose that object A creates object B. At some point later it passes B to object C which becomes the owner.
In the period between creating B and handing it over to C, A is responsible for destruction in case of exceptions, or perhaps the selection of a branch that bypasses C. On the other hand, once it has handed off B, A must not attempt to destroy C.
All this can be handled with sufficient care. One approach is that taken by the VCL with TComponent.Owner.
However, if you can find a way to stick to the two standard patterns of ownership then do so.
What are the two standard patterns?

*

*Create in a constructor and assign to a field; destroy in the matching destructor.

*Create and destroy inside a single method, with protection provided by try / finally.

I would strongly recommend that you try to shape your code so that all resource acquisition uses one of these two options.
How can you do so in your example? The option that leaps out at me is to use a factory to create your FileSystem object. This allows TFileLister to manage the lifetime of the FileSystem object, but gives you the flexibility of injecting different behaviour into TFileLister.

A: I disagree with the notion that an object must be destroyed by the one that created it. Many times this is the natural choice but its certainly not the only way of managing memory. A better way to look at it is that an object's lifetime should end when it is no longer needed.
So what options do you have?
Use Interface reference counting
In many cases it is trivial to extract an interface from an existing class so don't shelve this idea just because your working with legacy code.
Use an IoC container that supports lifetime management.
There are a number of IoC containers for Delphi and more are popping up all the time. Spring for Delphi is one that I know of that supports lifetime management. Note: most of these containers target Delphi 2010 or newer so it may be difficult to find one for legacy code.
Use a garbage collector.
The Boehm GC memory manager is the only one I'm aware.
All three of these can be combined with poor man's dependency injection to get the testing benefits while making minimal changes to your legacy code. For those unfamiliar with the term you use constructor chaining to instantiate a default dependency.
constructor TMyClass.Create;
begin
  Create(TMyDependency.Create);
//Create(IoCContaineror.Resolve(TMyDependency));
end;

constructor TMyClass.Create(AMyDependency: TMyDependency)
begin
  FMyDependency := AMyDependency;
end;

Your production code continues to use the default constructor with the real object while your tests can inject a fake/mock/stub to sense what the class being exercised is playing nicely. Once your test coverage is high enough you can remove the default constructor.


text:
Q: Why OleFileIO_PL only works with .doc file types and not .docx Python? right so I'm working on a Python script (Python 2.7) that will extract the metadata from OLE files. I am using OleFileIO_PL and it work perfectly file with OLE files 97 - 2003, but any later then that it just says that it is not an OLE2 file type.
Any way I can modify my code to support both .doc and .docx ? Same with .ppt and .pptx etc.
Thank you in advance
Source Code:
#!/usr/bin/env python
# -*- coding: utf-8 -*-

import OleFileIO_PL
import StringIO
import optparse
import sys
import os

def printMetadata(fileName):
   data = open(fileName, 'rb').read()
   f = StringIO.StringIO(data)
   OLEFile = OleFileIO_PL.OleFileIO(f)
   meta = OLEFile.get_metadata()
   print('Author:', meta.author)
   print('Title:', meta.title)
   print('Creation date:', meta.create_time)
   meta.dump()
   OLEFile.close()

def main():
  parser = optparse.OptionParser('usage = -F + Name of the OLE file with the extention For example: python Ms Office Metadata Extraction Script.py -F myfile.docx ')
  parser.add_option('-F', dest='fileName', type='string',\
     help='specify OLE (MS Office) file name')
  (options, args) = parser.parse_args()
  fileName = options.fileName
  if fileName == None:
     print parser.usage
     exit(0)
  else:
     printMetadata(fileName)

if __name__ == '__main__':
  main()

A: To answer your question, this is because the newer MS Office 2007+ files (docx, xlsx, xlsb, pptx, etc) have a completely different structure from the legacy MS Office 97-2003 formats.
It is mainly a collection of XML files within a Zip archive. So with a little bit of work, you can extract everything you need using zipfile and ElementTree from the standard library.
If openxmllib does not work for you, you may try other solutions:

*

*officedissector: https://www.officedissector.com/

*python-opc: https://pypi.python.org/pypi/python-opc

*openpack: https://pypi.python.org/pypi/openpack

*paradocx: https://pypi.python.org/pypi/paradocx
BTW, OleFileIO_PL has been renamed to olefile, and the new project page is https://github.com/decalage2/olefile


text:
Q: List to List conversion in Java 11 using Streams I have a list of Integer and would like to convert into a list of Long (or any other type) by using Streams. I tried multiple options but all failed. How do I do that?
List<Integer> arr = new ArrayList<Integer>();
    arr.add(1);
    arr.add(3);
    arr.add(5);
    arr.add(7);
    arr.add(9);

A: List<Long> longList =  arr.stream().map(Long::valueOf).collect(Collectors.toList());

A: Use:
List<Long> longList = arr.stream()
    .map(Long::valueOf) //or map to any other type/objects with "e -> new..."
    .collect(Collectors.toList());

A: List<Integer> arr = new ArrayList<>();
...

List<Long> longs = arr.stream()    // Stream<Integer>
    .mapToLong(Integer::longValue) // LongStream
    .boxed()                       // Stream<Long>
    .collect(Collectors.toList());

List<Long> longs = arr.stream()            // Stream<Integer>
    .map(n -> Long.valueOf(n.longValue())) // Stream<Long>
    .collect(Collectors.toList());

The latter uses Integer.longValue(), though Integer.intValue() would have done also.
Relying on Integer to int unboxing and then Long.valueOf widening int to long, is too convoluted. Not sure whether there is a speed/memory difference. Should not.
Alternatively with a different data structure for arr:
IntStream arr = IntStream.of(1, 3, 5, 7, 9);
List<Long> longs = arr.asLongStream() // LongStream
    .boxed()                          // Stream<Long>
    .collect(Collectors.toList());

Basically you have to map an Integer to a Long.


text:
Q: Eye of Cthulhu in Terraria Xbox 360 edition I was playing Terraria and I summoned the Eye of Cthulhu and got killed. I was wondering, can I manually respawn it again and/or will it respawn again by its self?

A: Yes. Well, both. If you don't defeat the eye, it'll just respawn eventually.  You can always spawn him manually whether or not you have beaten him.


text:
Q: Datos de horas para un Spinner Tengo un Spinner y como datos estas horas:
final String[] horasInicio = new String[] {
            "09:00",
            "09:30",
            "10:00",
            "10:30",
            "11:00",
            "11:30",
            "12:00",
            "12:30",
            "13:00",
            "13:30",
            "14:00",
            "14:30",
            "15:00",
            "15:30",
            "16:00",
            "16:30",
            "17:00",
            "17:30",
            "18:00",
            "18:30",
            "19:00",
            "19:30",
            "20:00",
            "20:30"
    };

Cómo puedo hacer para que si son, por ejemplo, las 11:49, se genere otro array o un ArrayList que tenga los datos del spinner que serían 12:00, 12:30, 13:00, 13:30... así hasta las 20:30. Si son las 13:12, pues generar una lista con los datos 13:30, 14:00, 14:30... hasta las 20:30. son las horas de inicio de reservas, por eso si son las 11:49, lo lógico, es que la primera hora de reserva sea las 12:00 y como se puede reservar de media hora en media hora, vaya 12:00, 12:30...20:30.

A: Yo lo haria de la siguiente manera, antes de guardar las horas en string las tendria en int
final int[] horasInicio = new int[] { 900, 930, 1000, 1030, 1100, 1130, 1200, 1230, 1300, 1330, 1400, 1430, 1500, 1530, 1600, 1630, 1700, 1730, 1800, 1830, 1900, 1930, 2000, 2030 };

List<Integer> horasReserva = new ArrayList<>();

int hora = 1149;

//obtener una lista con las reservas posibles
for (int i=0;i < horasInicio.length;++i) {
    if (hora < horasInicio[i])  horasReserva.add(horasInicio[i]);
}

//mostrar las reservas
for (int i=0;i < horasReserva.size();++i) {
    System.out.println(horasReserva.get(i));
}

Solo queda la parte de convertir 11:49 a int y de int a formato 00:00
Otra manera más consistente seria convertir las horas a total de minutos.


text:
Q: Facebook The Open Graph protocol post link to wall not showing image I'm using the (The Open Graph protocol[Source]). I've searched the most of the stackoverflow, but i seems, that there aren't any answers to my question.
My <meta> code is:
<meta property="og:title" content="Testing" />
<meta property="og:description"
  content="This is the desciption testing 123" />
<meta property="og:image" content="http://www.byui.edu/images/agriculture-life-sciences/flower.jpg" />

When i copy paste a link(http://mywebsite.com/testing.php) into facebook, on my wall, it pulls out the og:title and og:description perfectly everytime, even when i make a new PHP-file document example: testing1.php. But it dosen't show the image on the post, when i refresh the facebook 3-6 times, copy pasting the link, to the status input, it will somehow be shown, but how can it be that i need to refresh it 3-6 times, before facebook cache the image, and before the image will be shown? Is there are work around on this problem or something i've been missing? I'm using a HTTP url.
Thanks!

A: Facebook does indeed cache its images, and this can sometimes cause problems (such as you are experiencing). The best way I know how to "force" clean Facebook's cache is by running your website through their debugger tool. It used to be called "lint" when I was working with it, but I think this should have the same functionality.
Whether it works or not, I'd recommend you use it. It's a handy utility either way!


text:
Q: Why am I getting ValueError when trying to render PNG? I have some SVGs that I would like to save as PNGs with Python. I am using svglib to handle this process. Whenever I try to renderPM.drawToFile(logo, path, fmt) it returns the following error:
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "C:\Users\Myself\Desktop\programming\project-folders\svg-to-png\venv\lib\site-packages\reportlab\graphics\renderPM.py", line 683, in drawToFile
    c.saveToFile(fn,fmt)
  File "C:\Users\Myself\Desktop\programming\project-folders\svg-to-png\venv\lib\site-packages\reportlab\graphics\renderPM.py", line 321, in saveToFile
    im = self.toPIL()
  File "C:\Users\Myself\Desktop\programming\project-folders\svg-to-png\venv\lib\site-packages\reportlab\graphics\renderPM.py", line 317, in toPIL
    (getattr(im,'frombytes',None) or getattr(im,'fromstring'))(self._gs.pixBuf)
  File "C:\Users\Myself\Desktop\programming\project-folders\svg-to-png\venv\lib\site-packages\PIL\Image.py", line 827, in frombytes
    d.setimage(self.im)
ValueError: tile cannot extend outside image

Here is the code I entered in the python shell to get these results (see documentation):
>>> from svglib.svglib import svg2rlg
>>> from reportlab.graphics import renderPM
>>> logo = svg2rlg(r'C:\Users\Myself\Desktop\testenv\test.svg')
>>> renderPM.drawToFile(logo, r'C:\Users\Myself\Desktop\testenv\test.png', fmt='PNG')

Here is the SVG that I am trying to export as PNG (using a very simple SVG for testing):
<!DOCTYPE html>
<html>
  <body>
    <svg xmlns="http://www.w3.org/2000/svg" height="500" width="500">
      <polygon points="200,10 250,190 160,210" style="fill:lime;stroke:purple;stroke-width:1" />
    </svg>
  </body>
</html>

I have looked at many similar problems to try to find an answer, but I am not having any luck.

A: As mentioned by @Robert Longson, the HTML file was giving me the value error. I changed the document to include the proper format, which fixed my issue:
<?xml version="1.0" standalone="no"?>
<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd">
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 400 400">


text:
Q: Django 404 Regular Expression I'm trying to access the detail view, but it doesn't seem to be mapping properly.  Is there something I'm missing?  When I try to access the localhost:8000/polls/1 view I get a 404 saying the the url pattern doesn't match any of those url patterns given below.  Is there something wrong with my regular expression?
Here are the url patterns in the 404:
^polls/ ^$
^polls/ ^polls/(?P<poll_id>\d+)/$
^polls/ ^polls/(?P<poll_id>\d+)/results/$
^polls/ ^polls/(?P<poll_id>\d+)/vote/$
^admin/

The current URL, polls/1/vote/, didn't match any of these.
Here is urls.py:
from django.conf.urls import patterns, include, url

urlpatterns = patterns('polls.views',
    url (r'^$', 'index'),
    url (r'^polls/(?P<poll_id>\d+)/$', 'detail'),
    url (r'^polls/(?P<poll_id>\d+)/results/$', 'results'),
    url (r'^polls/(?P<poll_id>\d+)/vote/$', 'vote'),
    )

Here is my views.py:
from django.template import RequestContext
from django.http import HttpResponseRedirect, HttpResponse
from django.core.urlresolvers import reverse
from django.shortcuts import render_to_response, get_object_or_404
from polls.models import Choice,Poll

def index(request):
latest_poll_list = Poll.objects.all().order_by('-pub_date')[:5]
return render_to_response('polls/index.html', {'latest_poll_list': latest_poll_list})

def detail(request, poll_id):
p = get_object_or_404(Poll, pk=poll_id)
return render_to_response('polls/detail.html', {'poll': p},
                                  context_instance=RequestContext(request))

def results(request, poll_id):
p = get_object_or_404(Poll, pk=poll_id)
return render_to_response('polls/results.html', {'poll':p})

def vote(request, poll_id):
p = get_object_or_404(Poll, pk=poll_id)
try:
    selected_choice = p.choice_set.get(pk=request.POST['choice'])
except (KeyError, Choice.DoesNotExist):
    #Redisplay poll voting form
    return render_to_response('polls/detail.html', {
        'poll': p,
        'error_message': "You didn't select a choice.",
    }, context_instance=RequestContext(request))
else:
    selected_choice.votes += 1
    selected_choice.save()
return HttpResponseRedirect(reverse('polls.views.results', args=(p.id,)))

A: I guess you are including your app urls in project urls file which is why in the error urls you can see polls written twice. I would suggest you to remove 'polls' word from your app urls
and try again..
    url (r'^$', 'index'),
    url (r'^(?P<poll_id>\d+)/$', 'detail'),
    url (r'^(?P<poll_id>\d+)/results/$', 'results'),
    url (r'^(?P<poll_id>\d+)/vote/$', 'vote'),


text:
Q: Page and Post return 404 with custom taxonomy I have registered a custom taxonomy on "post" named "cat_modules" with this args:
'rewrite' => array(
        'hierarchical' => true,
        'slug' => '/',
        'with_front' => false
    )

I used 'hierarchical' => true to have the url structure like 'category/subcateogry' and I used 'slug' => '/' to remove the "cat_modules" from the slug.
These work well on the archive pages but all posts and pages return a 404 error.
If I remove 'slug' => '/' from the args everything work well.
P.S In this web site is installed WPML.

A: OK, so you've used / as you taxonomy slug. It means that URL for your term is:
http://example.com/my-sample-taxonomy-term/

And for pages it will be:
http://example.com/my-sample-page/

As you can see, there is no way to guess, what type of post should WP search for.
WordPress processes the URLs looping through registered Rewrite Rules and matching given URL against regular expression assigned to current rule.
That means that in your case WP will take first rule that will match correctly and try to display that type of object. And because there are two different objects registering rules that are in conflict, then you'll get 404 errors for some of them.


text:
Q: Get Average, Max, Min , Last added value and Time I have a Parameters Log table like this:

Log ID
Temperature
Humidity
country
Date

1
40
10
USA
2021-09-04 10:00:51.737

2
20
20
USA
2021-09-04 11:09:51.737

3
30
30
USA
2021-09-04 12:09:51.737

The above table stores Temperature, Humidity likewise different parameters for the different countries at different times. I want an average of This parameter, max, min, last added value, and Last added Time for a specific day.
For example:

Parameters
Country
Average
Min
Max
Last value
Last updated time

Temperature
USA
30
20
40
30
2021-09-04 12:09:51.737

Humidity
USA
20
10
30
30
2021-09-04 12:09:51.737

This is what I did for Temperature :
;WITH CTE AS
(
    SELECT
        AVG(Temperature) AVG_Temp,
        MIN(Temperature) MIN_Temp,
        MAX(Temperature) Max_Temp,
        Country
    FROM
        Parameters_Log
    GROUP BY
        Country
    WHERE
        Country = 'USA'
        AND CAST([date] AS date) = '2021-09-04'
)

First I am getting avg, Min, and Max for temperature for a country as above
SELECT TOP 1
    c.Country,
    c.AVG_Temp,
    c.MIN_Temp,
    c.Max_Temp,
    [log].date,
    [log].Temperature
FROM
    Parameters_Log [log]
INNER JOIN
    cte c ON c.country = [log].country
          AND
WHERE
    [log].Country = 'USA'
    AND cast([log].[date] AS date) = '2021-09-04'
ORDER BY
    [log].[date] DESC

Then I am using order by date desc to get the last added Temperature value and time. Finally, I am Taking Top 1 and store in a temporary table then the same procedure following for Humidity.
Can anyone guide me on what will be the performance-wise best approach?

A: You can unpivot the values using apply. Then use row_number() and aggregation for the summary:
select country, parameter,
       avg(val), min(val), max(val),
       max(case when seqnum = 1 then val end) as last_val,
       max(date)
from (select pl.country, pl.date, v.*,
             row_number() over (partition by pl.country, v.parameter order by pl.date desc) as seqnum
      from parameters_log pl cross apply
           (values ('Temperature', pl.temperature), ('Humidity', pl.humidity)
           ) v(parameter, val)
     ) pl
group by country, parameter;

If you want a specific day, add a where clause to the subquery, such as:
where pl.date >= '2021-09-04' and pl.date < '2021-09-05'

Here is a db<>fiddle.

A: Please try this. last value is picked based on max logid. apply cross join for whole result set into 2 copies.
-- SQL SERVER
SELECT CASE WHEN id = 1 THEN 'Temperature' ELSE 'Humidity' END Parameters
     , pl.country
     , CASE WHEN id = 1 THEN avg_temp ELSE avg_hum END Average
     , CASE WHEN id = 1 THEN min_temp ELSE min_hum END "Min"
     , CASE WHEN id = 1 THEN max_temp ELSE max_hum END "Max"
     , CASE WHEN id = 1 THEN pl.temparature ELSE pl.humidity END last_value
     , t.last_date "Last updated time"
FROM Parameters_Log pl
INNER JOIN (SELECT country
                 , MIN(temparature) min_temp
                 , MAX(temparature) max_temp
                 , AVG(temparature) avg_temp
                 , MIN(humidity) min_hum
                 , MAX(humidity) max_hum
                 , AVG(humidity) avg_hum
                 , MAX(logid) max_id
                 , MAX(tdate) last_date
            FROM Parameters_Log
            WHERE CAST(tdate AS date) = '2021-09-04'
            GROUP BY country) t
       ON pl.logid = t.max_id
CROSS JOIN (SELECT 1 id UNION SELECT 2 id) c

Please check from url https://dbfiddle.uk/?rdbms=sqlserver_2017&fiddle=48e671202de62aeff8ea737ba4d1ba5a
If desired output depends on max_date then ON condition will
ON pl.tdate = t.last_date

If desired output depends on max log_id then ON condition will
 ON pl.logid = t.max_id


text:
Q: Expected execution time vs actual execution time in python I have two different functions for solving the knapsack problem.
The difference in these functions is that the v2 function uses less space over v1. From my time complexity analysis, the v2 function should not be faster than v1.
However, after running my test cases several times, I found that v2 is significantly faster than v1, and I cannot understand why.
I am using Python Unittest.
Here is the test times:
v1 execution time:

Ran 1 test in 35.985s

v2 execution time:

Ran 1 test in 25.294s

Here is my v1 functions:
def knapsack_bottom_up_v1(self):
    N = len(self.values)
    C = self.capacity

    # table
    dp = [[0 for rc in range(C+1)] for i in range(N)]

    # filling out the table
    for i in range(0, N):
        i_weight = self.weights[i]
        i_val = self.values[i]
        for rc in range(1, C+1):
            # edge case
            if i == 0:
                if i_weight > rc:
                    dp[i][rc] = 0
                else:
                    dp[i][rc] = i_val
            # recurrence relation
            if i_weight > rc:
                dp[i][rc] = dp[i-1][rc]
            else:
                dp[i][rc] = max(dp[i-1][rc], dp[i-1][rc-i_weight] + i_val)
    return dp[N-1][C]

Here is my v2 function:
def knapsack_bottom_up_v2(self):
    N = len(self.values)
    C = self.capacity

    # prev_dp == dp[i-1]
    prev_dp = [0]*(C+1)
    # dp == dp[i]
    dp = [0]*(C+1)

    # filling out the table
    for i in range(0, N):
        i_weight = self.weights[i]
        i_val = self.values[i]
        for rc in range(1, C+1):
            # recurrence relation
            if i_weight > rc:
                dp[rc] = prev_dp[rc]
            else:
                dp[rc] = max(prev_dp[rc], prev_dp[rc-i_weight] + i_val)
        prev_dp, dp = dp, prev_dp
        for i in range(len(dp)):
            dp[i] = 0

    return prev_dp[C]

Here is also the test case I'm using:
values = [825594,1677009,1676628,1523970,943972,97426,69666,1296457,1679693,\
              1902996,1844992,1049289,1252836,1319836,953277,2067538,675367,853655,\
              1826027,65731,901489,577243,466257,369261]
weights = [382745,799601,909247,729069,467902,44328,34610,698150,823460,903959,\
               853665,551830,610856,670702,488960,951111,323046,446298,931161,31385,\
               496951,264724,224916,169684]
capacity = 6404180
solution = [1,1,0,1,1,1,0,0,0,1,1,0,1,0,0,1,0,0,0,0,0,1,1,1]

Can anyone help me understand why the execution time of v2 is faster than v1? I think it should be about the same, if not, v2 should be slightly slower than v1.
Thanks!

A: The time difference mainly comes from two or three more indexes in each internal loop.
I did a test on my machine and did two additional indexes in each internal loop. The difference was about 9 seconds:
>>> lst = [0]
>>> timeit("""for i in range(C):
...     prev = lst[0]
...     for j in range(N):
...         prev
...         prev
... """, globals=globals(), number=1)
3.6931853000132833
>>> timeit("""for i in range(C):
...     for j in range(N):
...         lst[0]
...         lst[0]
... """, globals=globals(), number=1)
12.408428700000513


text:
Q: Генератор корректного предложения из списка слов Следующая задача:
Необходимо в функцию передать список слов и одно слово, на выходе необходимо корректное предложение с этим словом и любыми словами из списка, например:
list1 = ["в", "на", "к", "погода", "улица", "солнце"]
str1 = "хорошая"
gen_pr(list1, str1)

Вывод:
"На улице хорошая погода" (или иное со словом "хорошая")
Нужен совет, как лучше это реализовать.
Можно реализовать с помощью цепей Маркова, генерируя и проверяя каждое предложение на list1 и str1.
Можно ли это ещё как либо реализовать?


text:
Q: Replace slashes with dots in javascript regex I have a date and I want to replace all the slashes with dots. This is what I have but it's not working:
var TheDate = "3 / 29 / 2017";
TheDate = TheDate.replace(/'/'/g,'.');
alert(TheDate);

What's not right? There's a jsFiddle here to test.

A: Your expression should be /\//g

var d = "3 / 29 / 2017";
d = d.replace(/\//g,'.');
document.body.append(d);

A: Replace /'/'/g with /[/]/g

*

*/ - start of the regex

*[/] match characters inside square brackets

*/g end of the regex
Regex resources:

*

*http://regexr.com/

*https://regexone.com/

A: Try this TheDate.replace(/\//g, '.')

A: var TheDate = "3 / 29 / 2017";
TheDate = TheDate.replace(/\//g,'.');
alert(TheDate);

You need to escape the / character. You do it by prepending it with a \.


text:
Q: How to format an output? (In Java) Write a program that accepts names and formats them as follows: If the input is:
John Anthony Brown
Then the output must be:
Brown, John A.
Here is what I have
    int mn;
    String input3;
    int fn;
    int ln;
    String firstName;
    String lastName;
    String middleName;
    Scanner scnr = new Scanner(System.in);
    String input = scnr.nextLine();
    fn = input.indexOf(" ");
    firstName = input.substring(0, fn);
    middleName = input.substring(fn+1, input.length());
    mn = middleName.indexOf(" ");
    lastName = input.substring(mn+1, input.length());

    System.out.println(lastName + ", " + mn + " " + firstName + ".");
}

I keep trying different things and get weird outputs such as "ry A Lee, 1 Mary." for the input "Marry A Lee"
This topic was never covered in my class and I am very confused.

A: Because this is homework, I'll give code fragments:
Firstly, use split() to break up the text into words:
String[] names = input.split(" ");

Then build up your result:
String result = names[2] + ", " + names[0] + ", " + names[1].charAt(0) + ".";

There are more elegant ways of doing it, but this way is arguably the easiest to understand.
You could get fancier by catering for varying numbers of names.

A: Try something like this:
String[] items = input.split(" ");

//if there are three item in items, then it is the pattern you mentioned
if (items.length == 3) {
    System.out.println(items[2] + "," + items[0] + items[1].charAt(0) + ".");
}


text:
Q: AADB2C AuthenticationTicket is null in AuthorizationCodeReceived Net Framework with AADB2C. The login process works until the AuthorizationCodeReceived event is fired. When I debug the code I can see that the AuthenticationTicket is null. I have followed and looked at plenty of solutions but cant find any solutions for this. All help is appreciated. My code is as follows:
app.UseOpenIdConnectAuthentication(
                new OpenIdConnectAuthenticationOptions
                {
                    MetadataAddress = string.Format(CultureInfo.InvariantCulture, _azureAdInstance, _azureAdTenant, _azureAdB2CPolicy),
                    ClientId = _azureAdClientId,
                    Scope = "openid profile offline_access",
                    ResponseType = "code",
                    PostLogoutRedirectUri = _azureAdPostLogoutRedirectUri,
                    RedirectUri = "https://dev.sigvaris.com",

                    // To only allow users from a single organizations, set ValidateIssuer to true and 'tenant' setting in web.config to the tenant name
                    // To allow users from only a list of specific organizations, set ValidateIssuer to true and use ValidIssuers parameter
                    TokenValidationParameters = new TokenValidationParameters()
                    {
                        //ValidateIssuer = true, // This is a simplification
                        //RoleClaimType = ClaimTypes.Role,
                        NameClaimType = "name",
                    },

                    Notifications = new OpenIdConnectAuthenticationNotifications
                    {

                        AuthenticationFailed = context =>
                        {
                            context.HandleResponse();
                            context.Response.Write(context.Exception.Message);
                            return Task.FromResult(0);
                        },
                        RedirectToIdentityProvider = context =>
                        {
                            // Here you can change the return uri based on multisite
                            HandleMultiSiteReturnUrl(context);

                            // To avoid a redirect loop to the federation server send 403
                            // when user is authenticated but does not have access
                            if (context.OwinContext.Response.StatusCode == 401 &&
                                context.OwinContext.Authentication.User.Identity.IsAuthenticated)
                            {
                                context.OwinContext.Response.StatusCode = 403;
                                context.HandleResponse();
                            }
                            //XHR requests cannot handle redirects to a login screen, return 401
                            if (context.OwinContext.Response.StatusCode == 401 && IsXhrRequest(context.OwinContext.Request))
                            {
                                context.HandleResponse();
                            }
                            return Task.FromResult(0);
                        },
                        AuthorizationCodeReceived = async notification =>
                        {
                            **notification.AuthenticationTicket is null here**
                            var httpClient = _httpClientFactory.CreateClient(HttpClientNames.Owin);
                        }
                }
            );

A: You might be missing some bit of code, check this code file regarding  the code you provided for UseOpenIdConnectAuthentication.
Also, null value comes due to session based cookie/cache issues, to clear that please check this Reference:  ASP.NET_SessionId + OWIN Cookies do not send to browser
app.UseCookieAuthentication(new CookieAuthenticationOptions
        {
            CookieManager = new SystemWebCookieManager()
        });


text:
Q: Url.Link always returns null used within asp..net web api I want to create some hyperlinks for my DTO`s returned from a REST Api.
The variable url is always null and I do not know why?!
Why is the url not created, what am I still missing?
The name of the route is GetStatusFeedback that's correct and I also use Action and Controller as route parameters + the leadId param!
public class ValuesController : ApiController
{
    [Route("")]
    [HttpGet]
    public IHttpActionResult Get()
    {
        var leadsFromDataBase = new List<Lead> { new Lead { Id = 1 }, new Lead { Id = 2 } };
        var leadDtos = new List<LeadDto>();
        foreach (var lead in leadsFromDataBase)
        {
            var leadDto = new LeadDto();
            string url = Url.Link("GetStatusFeedback", new { LeadId = lead.Id, Action = "Accept", Controller = "values"});
            leadDto.AcceptLink = new Link { Url = url, Verb = "Get" };

            leadDtos.Add(leadDto);
        }
        return Ok(leadDtos);
    }

    [Route("leads/{id:int}/statusfeedback", Name = "GetStatusFeedback")]
    [HttpPost]
    public void Accept(int leadId)
    {

    }

A: route parameters need to match the expected parameter in the route template
string url = Url.Link("GetStatusFeedback", new { id = lead.Id });

should match based on the "leads/{id:int}/statusfeedback" route template
also route template placeholders need to match parameter name in the action
[Route("leads/{id:int}/statusfeedback", Name = "GetStatusFeedback")]
[HttpPost]
public void Accept(int id) {

}

Finally you should use proper route names that help describe the route.

A: It took me a while to get what I needed from the accepted answer (and my mistake differed from the OP), here is a simplified version based on Nkosi's answer and OP's comment:
public class ValuesController : ApiController
{
  [HttpGet]
  public IHttpActionResult Get()
  {
    string url = Url.Link("GetStatusFeedback", new { Id = 1, Action = "Accept", Controller = "values"});
    /*or*/ url = Url.Link(nameof(Accept), new { Id = 1,      Action = "Accept", Controller = "values"});
    //not  url = Url.Link(nameof(Accept), new { LeadId = 1,  Action = "Accept", Controller = "values"});

    return Ok(url);
  }

// Controller we want to get the URL of:
[HttpPost("leads/{id:int}/statusfeedback", Name = "GetStatusFeedback")]
public void Accept(int id) //param name matches the line above {id} (in OP it mismatched)
{

}


text:
Q: Programmatically clicking the Quora "more" button I'm trying to use watir to programmatically click the "more" button at the bottom of a page like http://www.quora.com/Startups/best_questions. I currently have code that looks like:
    require 'watir-webdriver'
    b = Watir::Browser.new
    b.goto 'quora.com/'+ ARGV[2] + '/best_questions'

    show_more = b.button(:id => "more_button")
    show_more.click

But I'm having some trouble finding the id of the button in DOM. I'm actually not even sure that this is the correct approach.

A: From chrome or firefox (with firebug) right click on the button and go to inspect element.
In the inspector panel you can see that it's actually a div and it looks like this:

More

so you would do:
b.div(:text => 'More').click

or
b.div(:class => 'pager_next').click


text:
Q: Independent events A and B have the same probability p. Find {A U B} Unless I'm reading the question wrong P{A $\cup$ B} = P(A) +P(B) - P(A $\cap$ B).
Since they have the same probabiliity then P(A) = 0.50, P(B) = 0.50 and P(A $\cap$ B) = 0.25, thus P{A $\cup$ B}= 1-.025=0.75?

A: We assume $P(A)=P(B)=p.$
If $A$ and $B$ are independent, then
$$P(A \cap B)=P(A) \cdot P(B)$$
and
$$
P(A \cup B)=P(A)+P(B)-P(A \cap B)
$$ reads
$$
P(A \cup B)=p+p-p \cdot p=2p-p^2.
$$


text:
Q: How to use speech to text in WP7 mango Application using inbuilt Mango voice feature programmatically can we call inbuilt Windows phone mango voice feature programmatically as in we use Launcher and Choosers.
Is there a way I can use this feature for my Translator application where my application recognises the voices spoken in different languages and convert them to text in that particular language.
Do we have this feature in BING Translator service? if yes then how to use them?
also how to use the INbuilt voice command of my WP mango to build my application?

A:
can we call inbuilt Windows phone mango voice feature progamatically as in we use Launcher and Choosers.

No. There is no speech API for Windows Phone as of right now. See Microsoft TellMe for a upcoming API.

Is there a way i can use this feature for my Translator application where my applictaion recogonises the voices spoken in different languages and convert them to text in that particular language.

No

also how to use the INbuilt voice command of my WP mango to build my application?

You can't.

A: Not sure if you have found an answer for this, but Wade Wegner from the azure team has a translating and OCR app built using the Bing translation services.  I have not tried it, but this seems like something you could use.


text:
Q: Generating a download link/export file (csv or excell) i need some advice, i need to be able to generate a download link, and in this download link i can export some table data store in my database(questions ans answers ). I need to be able to get the data from the controller, and then return the generate link.
But there is a thing about it. For example these links will be sent to the client(cronjob), every day ex(ex: data from "2017-06-06 00:00:00" to "2017-06-06 24:59:59". Can someone tell me a good toll/repo that can make me achieve what im trying to do?
My example route downlo: ex: domain.com/download/uniquehaskkey/dateRangeMaybe.."


text:
Q: Using an Angularjs Promise on a objectID I am trying to build a dynamic SVG chart.  Each object in the chart has an ID.  All works well, the labels and and other objects draw fine, but Firfox's  console logfile is full of the following errors:
Error: [$interpolate:interr] http://errors.angularjs.org/1.4.2/$interpolate/interr?p0=%7B%7B(getText1Wid…eError%3A%20Cannot%20read%20property%20'getComputedTextLength'%20of%20null

This error refers to the following code:
   $scope.getText1Width = function (item) {
        if (typeof document.getElementById('text1-' + item) != 'undefined') {
            return document.getElementById('text1-' + item).getComputedTextLength()};    // Error Here
        return null;
    };

There are other functions that are similar and generate the same class of error:
$scope.getRecAbsLoc,
$scope.getTransData,
$scope.resizeSVG

What I would like to do is us a Promise to delay the evaluation of this code until the object referenced by the ID is rendered.
The theory is that for each 'item' in a list defined on $scope, a box, text and connecting lines are created.
Here is the template for the SVG:

        <button class="btn-xs btn-primary"
                ng-click="popDrawing('sm')">
            Enlarge
        </button>

            <svg id="svg-head" xmlns="http://www.w3.org/2000/svg">
                <defs>
                    <marker id="markerCircle" markerWidth="8" markerHeight="8" refx="5" refy="5">
                        <circle cx="5" cy="5" r="2" style="stroke: none; fill: inherit;"/>
                    </marker>

                    <marker id="markerArrowStart" markerWidth="5" markerHeight="5" refx="0" refy="2.5" orient="auto">
                        <path d="M2.5,0 v5 l-2.5,-2.5 Z " style="fill: inherit; "/>
                    </marker>
                    <marker id="markerArrowEnd" markerWidth="5" markerHeight="5" refx="2.5" refy="2.5" orient="auto">
                        <path d="M0,0 v5 l2.5,-2.5 Z " style="fill: inherit; "/>
                    </marker>
                </defs>

                <g
                        ng-attr-transform="translate({{nD.rxOffset*$index+1}},{{2+$index*(nD.height+nD.ryOffset)}})"
                        ng-repeat="item in $parent.productVersionsTested |orderBy: '-plRank'"
                        ng-attr-id="trans-{{item.pvNum}}"
                        text-anchor="middle"
                        class="my-box"

                        >
                    <rect
                            ng-attr-height={{nD.height}}
                            ng-attr-width={{(getText1Width(item.pvNum)+(nD.hPad*2))}}
                            ng-attr-id="rect-{{item.pvNum}}"
                            class="my-box"
                            >
                        {{resizeSVG('rect-'+item.pvNum)}}
                    </rect>
                    <text
                            ng-attr-x={{((getText1Width(item.pvNum)+(nD.hPad*2))/2)}}
                            ng-attr-y={{(nD.height/2)-5}}
                            ng-attr-id="text1-{{item.pvNum}}"
                            class="my-text"
                            >
                        <tspan>{{item.plName}}</tspan>
                    </text>
                    <text
                            ng-attr-x={{((getText1Width(item.pvNum)+(nD.hPad*2))/2)}}
                            ng-attr-y={{(nD.height/2)+10}}
                            ng-attr-id="text2-{{item.pvNum}}"
                            class="my-text"
                            >
                        <tspan>{{item.pvVerString}}</tspan>
                    </text>
                    <g ng-repeat="line in item.plMatchList">
                        <path
                                ng-attr-d="{{buildPath($parent.$index,$index,line)}}"
                                ng-attr-style="{{buildStyle($parent.$index,$index,line)}}"
                                />
                    </g>
                </g>
            </svg>

As always, thank you in advance for your help with this.


text:
Q: Multiple EditText by clicking: how to make the keyboard stay? My layout
In my layout, there are multiple EditTexts, when I click on the one of EditTexts, the keyboard pop up, that is ok.
Problem
Then, I click on another EditText, I would like the keyboard stays, rather than disappear and appear again.


text:
Q: MongoDb - Aggregation: How to $filter array documents with $elemMatch on a subdocument array? I'm trying use $filter on an aggregation. I need to filter an array called 'extras' that  intersect at least one of his 'seasons' with the giving 'dates'.
Here an example:
var from = new Date(2016, 0, 1);
var to = new Date(2016, 0, 5)

var projection = {
    name: 1,
    units: 1,
    capacity: 1,
    availabilitySeasons: { // This works
      $filter: {
        input: '$availabilitySeasons',
        as: 'avSeason',
        cond: {
          $and: [{
            $lte: ['$$avSeason.from', to]
          }, {
            $gte: ['$$avSeason.to', from]
          }]
        }
      }
    },
    rate: 1,
    features: 1,
    extras: {
      $filter: { // $elemMatch is no valid
        input: '$extras',
        as: 'extra',
        cond: {
          $elemMatch: ['$$extra.seasons', {
            from: {
              $lte: from
            },
            to: {
              $gte: to
            }
          }]
        }
      }
    }
  };

It's possible to use $filter in this case? Do I have to rush through a $unwind/$group hell?

A: Yes, you can do it.
As for the following example, use a condition with $lte and $gte inside a $and condition.
$project: {
       items: {
           $filter: {
              input: "$items",
              as: "item",
              cond: {
                 $and: [
                    $lt: [ "$$item.price", 100 ],
                    $gt: [ "$$item.price", 50 ]
                 ] }
            }
       }
 }


text:
Q: Check if record does NOT exist in Rails (from array of ids)? I can do this to check if a record(s) exists (say id "1" exists, but "2" and "3" don't):
Model.exists?(:id => [1, 2, 3]) #=> true

How do I do the opposite, so:
Model.not_exists?(:id => [1, 2, 3]) #=> true

A: Use empty?, this is what you want.  It uses count(*) vs select 1 as one.
> Rocketeer.where(:id => [1, 2, 3]).empty?
   (0.6ms)  SELECT COUNT(*) FROM "rocketeers" WHERE "rocketeers"."id" IN (1, 2, 3)
=> false

> Rocketeer.where(:id => [1, 2, 3]).any?
   (0.5ms)  SELECT COUNT(*) FROM "rocketeers" WHERE "rocketeers"."id" IN (1, 2, 3)
=> true

> Rocketeer.where(:id => [1, 2, 3]).exists?
  Rocketeer Exists (0.5ms)  SELECT  1 AS one FROM "rocketeers" WHERE "rocketeers"."id" IN (1, 2, 3) LIMIT 1
=> true

A: just add a ! operator
!Model.exists?(:id => [1, 2, 3]) #=> true

A: Edit: Please don't use this method. Even if it works it's not optimal since it loads all records instead of only testing their existence. This is a better way of doing it.

If you only need search records through ID you can try this
class Model
  def self.not_exists?(ids)
    self.find(ids)
    false
  rescue
    true
  end
end

If any of the IDs does not exist the find method will raise a ActiveRecord::RecordNotFound exception that we simply catch and return true.

A: class Model
  def self.does_not_exist?(ids)
    Model.where(id: ids).count < ids.size
  end
end

Explanation: If (and only if) all the instances you're looking for exist, Model.where(id: ids).count is equal to ids.size.
However if there are one or more instances missing, the count will be lower, meaning that there's a record that does not exist.

A: A more Ruby-esque way of doing it would be to use unless with exists?. This way, you don't have to use !. I imagine your use case is something like this:
def my_method
    return unless Model.exists?(:id => [1, 2, 3])

    # do something
end

You can replace 1, 2, 3 with a variable (call it id or something) and even remove the array altogether if you'd like: .exists?(id: id)

A: Another simple way is to use the where method with an array of id's.
# If the count of the query is equal to the count of all of the id's then the statement will return false.
# Else it will return true if not all ids exists in the database.
Model.where(id: [1, 2, 3]).count < [1,2,3].count

A: To ensure all ids exist, not just one the following works without have to rescue
ids = [1,2,3]
Model.where(id: ids).count != ids.length

The exists? method will return true if any of the ids match. The above will ensure all ids exist.


text:
Q: getting XML Catalog to work with wsimport. JAX-WS RI 2.1.6 in JDK 6 I have not had problems with xjc or tools like oxygen and eclipse xml plugin with my catalogs, but can't seem to find a flavor that works with the wsimport command.
Using the namespace for resolution  the following entries work for xjc but not wsimport.

<public publicId="http://schemas.ticomgeo.com/2010/geonet/common/ServiceMessageTypes/v0"  uri="./MessageTypes/ServiceMessageTypes.xsd"/>

Here are the commands I issued

xjc /data/catalog.work/wsdefs/HSTypes/HealthAndStatusV1.xsd  -catalog /data/catalog.work/wsdefs/catalog3.xml
wsimport -verbose /data/catalog.work/wsdefs/HealthAndStatusServiceV1.wsdl -catalog /data/catalog.work/wsdefs/catalog5.xml

The error I get in the wsimport shows it is not mapping the schema location. It  only looks for it relative to the catalog or wsdl  home directory ( they are the same ).

[ERROR] /data/catalog.work/wsdefs/ServiceMessageTypes.xsd (No such file or directory)

Here is the import statment in the wsdl
    <xs:schema>
        <xs:import
           namespace="http://schemas.ticomgeo.com/2010/geonet/common/ServiceMessageTypes/v0"
            schemaLocation="ServiceMessageTypes.xsd"/>
    </xs:schema>

Using the following entry in the catalog file again processing works with xjc

<systemSuffix  systemIdSuffix="ServiceMessageTypes.xsd"  uri="./MessageTypes/ServiceMessageTypes.xsd"/>

However using wsimport I get errors similar to the following on every element. The first error line number refers the line numoer of the start of the element following endpointStatusEnumType and the second error line number refers to the start of the EndpointStatusEnumType element Note that it is resolving the file location to get to the schema.

[ERROR] 'EndpointStatusEnumType' is already defined
   line 38 of file:/data/catalog.work/wsdefs/MessageTypes/ServiceMessageTypes.xsd
[ERROR] (related to above error) the first definition appears here
   line 23 of file:/data/catalog.work/wsdefs/MessageTypes/ServiceMessageTypes.xsd
23  <xs:simpleType name="EndpointStatusEnumType">

             The current status of a web service's endpoint.>
   </xs:annotation>
   <xs:restriction base="xs:string">
     <xs:enumeration value="NORMAL"/>
      <xs:enumeration value="COMMS_ERROR"/>
        <xs:enumeration value="DISABLED"/>
    </xs:restriction>
</xs:simpleType>

<!-- Complex Types -->
<!-- -->

38    <xs:complexType name="HeaderType">"

Besides working with xjc both formats also work with the OXYGEN and Eclipse XML editors and validators.
I assume that wsimport calls the same code as xjc so I am guessing there is something broken in how I import the schemas into the wsdl file, but its a pretty straight forward  or a bug in the version of wsimport I am using.
wsimport -version
JAX-WS RI 2.1.6 in JDK 6
xjc version "JAXB 2.1.10 in JDK 6"
JavaTM Architecture for XML Binding(JAXB) Reference Implementation, (build JAXB 2.1.10 in JDK 6)
Anyone have suggestions on how to get catalogs to work with wsimport?


text:
Q: Get thumbnail from Woocommerce Tag I am using this plugin
https://woocommerce.com/products/custom-product-tag-image/
To add images to my tags.
I'd like to display a list of tags with images. I've tried so many approaches but nothing yet.
Here's my code which outputs a list of tags but no images.
 <?php $taxonomyName = "product_tag";
$terms = get_terms(array('taxonomy' => 'product_tag', 'hide_empty' => false)); ?>
<?php foreach ( $terms as $term ) { ?>

 <?php
            $thumb_id = get_woocommerce_term_meta( $term->term_id, 'thumbnail_id', true );
            $term_img = wp_get_attachment_url(  $thumb_id );
        ?>
        <img src="<?php echo $term_img; ?>" />
<a href="<?php echo get_term_link( $term->term_id, 'product_tag' ); ?> " rel="tag"><?php echo $term->name; ?>

<?php } ?>

Suggestions?

A: You can use WC get_woocommerce_term_meta() and WP wp_get_attachment_url(). check below code.
<?php foreach ( $terms as $term ) { ?>

        <?php
            $thumb_id = get_woocommerce_term_meta( $term->term_id, 'thumbnail_id', true );
            $term_img = wp_get_attachment_url(  $thumb_id );
        ?>
        <a href="<?php echo $term_img; ?> " rel="tag"><?php echo $term->name; ?>

<?php } ?>

A: The code below is what worked for me as woocommerce_get_term_meta is deprecated and thumbnail_id doesn't exist anymore:
 <?php $taxonomyName = "product_tag";
$terms = get_terms(array('taxonomy' => 'product_tag', 'hide_empty' => false)); ?>
<?php foreach ( $terms as $term ) { ?>

 <?php
            $term_image_id = get_term_meta( $term->term_id, 'product_search_image_id', true );
            $term_image = wp_get_attachment_url( $term_image_id );
        ?>
        <img src="<?php echo $term_image; ?>" />
<a href="<?php echo get_term_link( $term->term_id, 'product_tag' ); ?> " rel="tag"><?php echo $term->name; ?>

<?php } ?>


text:
Q: How to make something Scale from a fixed point OK so I want to scale something in JoglGL using Java.
My code will scale something but I want it to be from my fixed point, which is my origin.. I read in the documentation that if I choose a fixed point to leave the same it should work, but each time I do it scales and moves from the center point ...Any ideas ?
public void scale(double sx, double sy)
    {
      vertices[0][0]=vertices[0][0]*sx;
      vertices[0][1]=vertices[0][1]*sy;
      vertices[1][0]=vertices[1][0]*sx;
      vertices[1][1]=vertices[1][1]*sy;
      vertices[2][0]=vertices[2][0]*sx;
      vertices[2][1]=vertices[2][1]*sy;
      vertices[3][0]=vertices[3][0]*sx;
      vertices[3][1]=vertices[3][1]*sy;

}

A: In the code snippet above, the scaling factor sx or sy is applied to all the vertices i.e. elements of the vertices[][] array. Skip the scaling factor to vertices[0][0], and your problem should be resolved. :)


text:
Q: How to change MUI_INSTFILESPAGE_FINISHHEADER_SUBTEXT if exists two MUI_PAGE_INSTFILES I have managed to customize the message shown in the title / subtitle after installation:
!define APP_NAME 'Test15'

name ${APP_NAME}
outfile '${APP_NAME}.exe'
showinstdetails show
InstallDir '$PROGRAMFILES\${APP_NAME}'

!include 'mui.nsh'

Var CompletedText
CompletedText $CompletedText

Var MUI_HeaderText
Var MUI_HeaderSubText
!define MUI_INSTFILESPAGE_FINISHHEADER_TEXT "$MUI_HeaderText"
!define MUI_INSTFILESPAGE_FINISHHEADER_SUBTEXT "$MUI_HeaderSubText"

!insertmacro MUI_PAGE_INSTFILES

!insertmacro MUI_LANGUAGE "English"

Section "One"
    MessageBox MB_OK "Section One"
SectionEnd

Section -"Post"
  ;MessageBox MB_OK "Section Post"
  StrCpy $CompletedText "My custom text"
  StrCpy $MUI_HeaderText "My custom header text"
  StrCpy $MUI_HeaderSubText "My custom header subText"
  ;MessageBox MB_OK "OUTING Section Post"
SectionEnd

My problem is that when I need to add a second part installation (it is a new mandatory requirement), and then not get modify / customize messages title / subtitle shown at the end:
!define APP_NAME 'Test15'

name ${APP_NAME}
outfile '${APP_NAME}.exe'
showinstdetails show
InstallDir '$PROGRAMFILES\${APP_NAME}'

!include 'mui.nsh'

Var CompletedText
CompletedText $CompletedText

Var MUI_HeaderText
Var MUI_HeaderSubText
!define MUI_INSTFILESPAGE_FINISHHEADER_TEXT "$MUI_HeaderText"
!define MUI_INSTFILESPAGE_FINISHHEADER_SUBTEXT "$MUI_HeaderSubText"

!insertmacro MUI_PAGE_INSTFILES

;This my second part instalation!!
!insertmacro MUI_PAGE_INSTFILES

!insertmacro MUI_LANGUAGE "English"

Section "One"
   MessageBox MB_OK "Section One"
SectionEnd

Section -"Post"
  ;MessageBox MB_OK "Section Post"
  StrCpy $CompletedText "My custom text"
  StrCpy $MUI_HeaderText "My custom header text"
  StrCpy $MUI_HeaderSubText "My custom header subText"
  ;MessageBox MB_OK "OUTING Section Post"
SectionEnd

Now, the same message is always displayed at the end for Title/Subtitle: "Installation Complete" // "Setup was completed successfully.". Nevertheless, the 'completed' text value is modified successfully ("My custom text").
Please, can anyone help me?
Thanks in advance!

A: If you read the MUI documentation carefully you will find this in the "Page settings" section:

Page settings apply to a single page and should be set before inserting a page macro. The same settings can be used for installer and uninstaller pages. You have to repeat the setting if you want it to apply to multiple pages.

Only the defines listed under "Interface settings" are global.
!include MUI.nsh
!define MUI_PAGE_HEADER_TEXT "Install page #1"
!define MUI_PAGE_HEADER_SUBTEXT "Foo foo foo"
!define MUI_INSTFILESPAGE_FINISHHEADER_TEXT "Did part 1"
!define MUI_INSTFILESPAGE_FINISHHEADER_SUBTEXT "..."
!insertmacro MUI_PAGE_INSTFILES
!define MUI_PAGE_HEADER_TEXT "Install page #2"
!define MUI_PAGE_HEADER_SUBTEXT "Bar bar bar!"
!define MUI_INSTFILESPAGE_FINISHHEADER_TEXT "All done"
!define MUI_INSTFILESPAGE_FINISHHEADER_SUBTEXT "ZZZzzz.."
!insertmacro MUI_PAGE_INSTFILES
!insertmacro MUI_LANGUAGE "English"


text:
Q: Laravel 8.66: Incompatible Authenticate() methods (App vs. Middleware) I managed to mess with my Laravel Authenticate method in
..\app\Http\Middleware\Authenticate.php
If I try to reindex Algolia with the command
php artisan scout:import

I get the error:
 ErrorException

Declaration of App\Http\Middleware\Authenticate::authenticate(array $guards) should be compatibl
are\Authenticate::authenticate($request, array $guards)

at D:\laragon\www\myproject\app\Http\Middleware\Authenticate.php:56
   52▕      *
   53▕      * @throws \Illuminate\Auth\AuthenticationException
   54▕      */
   55▕
➜  56▕     protected function authenticate(array $guards)
   57▕     {
   58▕
   59▕       if (empty($guards)) {
   60▕             return $this->auth->authenticate();

1   D:\laragon\www\myproject\app\Http\Middleware\Authenticate.php:10
    Illuminate\Foundation\Bootstrap\HandleExceptions::handleError("Declaration of App\Http\Middl
te(array $guards) should be compatible with Illuminate\Auth\Middleware\Authenticate::authenticat
D:\laragon\www\myproject\app\Http\Middleware\Authenticate.php", [Object(Algolia\ScoutExtended\C
, Object(Symfony\Component\Finder\Finder), Object(Symfony\Component\Finder\SplFileInfo)])

2   D:\laragon\www\myproject\vendor\algolia\scout-extended\src\Helpers\SearchableFinder.php:113
    require_once("D:\laragon\www\myproject\app\Http\Middleware\Authenticate.php")

my ..\app\Http\Middleware\Authenticate.php method is this:
protected function authenticate(array $guards)
{

  if (empty($guards)) {
        return $this->auth->authenticate();
    }

    foreach ($guards as $guard) {
        if ($this->auth->guard($guard)->check()) {
            return $this->auth->shouldUse($guard);
        }else{
            return null;
        }
    }

    throw new AuthenticationException('Unauthenticated.', $guards);
}

and the method in ..\vendor\laravel\framework\src\Illuminate\Auth\Middleware\Authenticate.php is this:
protected function authenticate($request, array $guards)
{
    if (empty($guards)) {
        $guards = [null];
    }

    foreach ($guards as $guard) {
        if ($this->auth->guard($guard)->check()) {
            return $this->auth->shouldUse($guard);
        }
    }

    $this->unauthenticated($request, $guards);
}

What can I do to make these two compatible again? Since they are not the same, I tried to overwrite one authenticate method with the other method, but that didn't work at all.
How can I go about solving this issue? Should I go find the factory version of these files and copy over the authenticate methods?

A: You can't mix and match function parameters like that. Just add Request $request as the first parameter of your function, and it will auto-inject the request dependency and become compatible.

A: Thanks to @kjoedion and @lagbox I managed to get it working:
The trick was to make the signature of the methods matching, without using "Request" in the /vendor/../Authenticate (so $request only):
..\app\Http\Middleware\Authenticate.php
protected function authenticate($request, array $guards)
{

  if (empty($guards)) {
        return $this->authenticate($request, $guards);
    }

    foreach ($guards as $guard) {
        if ($this->auth->guard($guard)->check()) {
            return $this->auth->shouldUse($guard);
        }else{
            return null;
        }
    }

    throw new AuthenticationException('Unauthenticated.', $guards);
}

in ..\vendor\laravel\framework\src\Illuminate\Auth\Middleware\Authenticate.php:
protected function authenticate($request, array $guards)
{
    if (empty($guards)) {
        $guards = [null];
    }

    foreach ($guards as $guard) {
        if ($this->auth->guard($guard)->check()) {
            return $this->auth->shouldUse($guard);
        }
    }

    $this->unauthenticated($request, $guards);
}


text:
Q: dropdownlist remain selected value unchanged when refresh the page I have a dropdown list like below:
<asp:DropDownList ID="DropDownList1" cssclass="ddStyle" runat="server" DataSourceID="SqlDataSource2" DataTextField="company" DataValueField="SECid" Width="100%" AppendDataBoundItems="true" AutoPostBack="True" EnableViewState="true" ViewStateMode="Enabled">
    <asp:ListItem Text="--Select One--" Value="" />
</asp:DropDownList>
<asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server" ControlToValidate="DropDownList1"></asp:RequiredFieldValidator>
<asp:SqlDataSource ID="SqlDataSource2" runat="server" ConnectionString="<%$ ConnectionStrings:ConnectionString %>" SelectCommand="select distinct secid, company from .... order by company"></asp:SqlDataSource>

The VB behind is
Protected Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button1.Click

    Dim Selection As String = Nothing

    If Not DropDownList.SelectedValue Is Nothing Then Selection = DropDownList.SelectedValue
    Session("Selected") = Selection

End Sub

I want to achieve that when I refresh the page after I made selection to the dropdwonlist, the dropdownlist won't return to "--select one--", rather, keep its last selected item. I wonder what's the solution for it?
Thanks for advice!

A: Here is an example of what LakshmiNarayana ment:
ASPX:
<asp:DropDownList ID="DropDownList1" runat="server">
    <asp:ListItem Text="-- Select One --"></asp:ListItem>
    <asp:ListItem Text="Apple"></asp:ListItem>
    <asp:ListItem Text="Orange"></asp:ListItem>
</asp:DropDownList>

<asp:Button ID="Button1" runat="server" Text="Submit" OnClick="Button1_Click" />

VB Code-Behind:
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
    If Not IsPostBack Then
        If Not Session("Selected") Is Nothing Then
            DropDownList1.SelectedValue = Session("Selected").ToString
        End If
    End If
End Sub

Protected Sub Button1_Click(ByVal sender As Object, ByVal e As EventArgs) Handles Button1.Click
    Dim Selection As String = Nothing

    If Not DropDownList1.SelectedValue Is Nothing Then
        Selection = DropDownList1.SelectedValue
        Session("Selected") = Selection
    End If
End Sub

A: One approach could be to check if Session("Selected")  value contains a value, and bind it to the list box in page_load, in a !isPostback block.
Checkout this forum for other approaches of achieving this.


text:
Q: react-native-image-crop-picker doesn't get recognized by my react-native app Hello Stack Overflow Community,
The problem:
I've been trying to install and apply the npm package "react-native-image-crop-picker" to my react-native app. I am building the react-native app on windows for android. The problem is that the npm package doesn't get recognized by my react-native app and provides "null".
Exception on my mobile device
What I've already tried:

*

*I already checked my android sdk and gradle version and they should be as required

*I re-installed the "npm package" (npm i)and the "react-native-image-crop-picker" (npm i react-native-image-crop-picker)

Thank you!

A: Try this and this may work for you:
close your metro bundler then:
cd ./android && gradlew clean && cd .. && react-native run-android


text:
Q: IndexError: list index out of range, Django def homepage(request):
    if request.user.is_authenticated():
        # get authenticated rfuser
        rfuser = RFUser.objects.filter(user=request.user)[0]
        print rfuser
        # show info of current user
        project_list = rfuser.project_set.all().order_by('project_name')
#       project_list = RFUser.objects.filter(user=request.user).order_by('project_name')
        context_dict = {'projects': project_list}
        return render(request, 'homepage.html', context_dict)
    else:
        return render(request, 'homepage.html')

I get the following error:
Internal Server Error: /
Traceback (most recent call last):
  File "C:\Python27\lib\site-packages\django\core\handlers\exception.py", line 39, in inner
    response = get_response(request)
  File "C:\Python27\lib\site-packages\django\core\handlers\base.py", line 249, in _legacy_get_response
    response = self._get_response(request)
  File "C:\Python27\lib\site-packages\django\core\handlers\base.py", line 187, in _get_response
    response = self.process_exception_by_middleware(e, request)
  File "C:\Python27\lib\site-packages\django\core\handlers\base.py", line 185, in _get_response
    response = wrapped_callback(request, *callback_args, **callback_kwargs)
  File "E:\rfui_web\myaccoutsite\views.py", line 13, in homepage
    rfuser = RFUser.objects.filter(user=request.user)[0]
  File "C:\Python27\lib\site-packages\django\db\models\query.py", line 295, in __getitem__
    return list(qs)[0]
IndexError: list index out of range

list index out of range But can not find why the reason is,Do not know if the index is not due to the array of the relevant value

A: This is because your query is returning an empty queryset. And thus returning IndexError: list index out of range
.If you want o know whether the query gives back something or not first check using:
if RFUser.objects.filter(user=request.user).exists():
     // then do things which you need


text:
Q: Cohomological definition of the Chow ring Let $X$ be a smooth projective variety over a field $k$. One can define the Chow ring $A^\bullet(X)$ to be the free group generated by irreducible subvarieties, modulo rational equivalence. Multiplication comes from intersection. The problem is, verifying that everything is well-defined is quite a pain. My question is

Is there a definition of $A^\bullet(X)$ that is purely cohomological?

In other words, is it possible to give a definition of $A^\bullet(X)$ that works for any ringed space? Probably the fact that this definition is equivalent to the usual one will be a theorem of some substance.
Note: I am not claiming that the usual definition of the Chow ring is "bad" in any way. I just think it would be nice to know if there was a "high-level" approach.

A: Another result I just ran across. In Hulsbergen's book Conjectures in arithmetic algebraic geometry he mentions the following theorem "of Grothendieck."
For a general ringed space, let
$$
  K_0(X)^{(n)} = \{x\in K_0(X)_{\mathbf Q}:\psi^r(x) = r^n x\text{ for all }r\geqslant 1\}
$$
where $\psi^r$ is the $r$-th Adams operation. The theorem states:

If $X$ is a smooth variety over a field $k$, then $\operatorname{A}^n(X)_{\mathbf Q}\simeq K_0(X)^{(n)}$.

Unfortunately, besides the obvious inference that this result is somewhere in SGA 6, no specific reference is given.

A: The Bloch formula (proved by Quillen, special cases by Bloch) holds for any regular scheme $X$ of finite type over a field: the group of algebraic cycles of codimension $i$ modulo rational equivalence is isomorphic to the cohomology group $H^i(X,\mathcal{K}_i)$ where $\mathcal{K_i}$ is the sheaf associated to the presheaf that sends each open subset $U$ to $K_i(U)$, where $K_i$ is the $K$-theory functor in the sense of Quillen. One can use this to define the intersection product.
Note: $K_i$ is the functor on schemes that sends $X$ to the abelian group $K_i(X)$ where $K_i$ is defined as $K_i$ of the exact category $P(X)$ of vector bundles on $X$. If $f:X\to Y$ is a morphism of schemes the inverse image functor $f^*:P(Y)\to P(X)$ is an exact functor inducing a morphism of $K$-groups $K_i(Y)\to K_i(X)$. In particular, if $U\subseteq X$ is an open subscheme then this provides the restriction, whence $U\mapsto K_i(U)$ is really a presheaf, so there is an associated sheafification.
Of course, defining $K_i(\mathcal{A})$ for an exact category $A$ requires some machinery, but the definition in Quillen's paper assumes only a basic knowledge of category theory and a bit of homological algebra. If the homotopy theory of categories is a bit fast there try Weibel's K-Book (available on his website), Ch. 4, Section 3.
The  Quillen's paper "Higher Algebraic K-Theory I", Theorem 5.19 for the original proof. An excellent introduction is Gillet's paper "K-Theory and Intersection Theory" which is in the great "Handbook of K-Theory".


text:
Q: How to delete emails from cpanel using php fopen I have my domains in one hosting account and emails in another. I need to delete emails using php code. Using fopen, how can I delete emails from one hosting account whose domains are in another.

A: I think fopen function can open a file to read or write but can't delete, but may be discussion in this thread could give you any suggestion.

A: @fopen("http://".$cpuser.":".$cppass."@".$domain.":2082/frontend/x3/mail/realdelpop.html?domain=".$domain."&email=".$email, "r") OR
    die("Error.");


text:
Q: Android SnackBar not shown before Activity recreate In my android app I have a button, which changes the language.
After clicking the button, the activity is recreated to apply the language changes.
I need to show a message to user via SnackBar, that the language has changed.
Till now I used a Toast and it worked fine, but from Android 11, the custom Toast views are deprecated and SnackBars are recommended.
However SnackBar doesn't persist, so it is not shown, because the activity is recreated immediately.
    public void ClickLang(View view)
{
    String lng = readLang();
    String tx;String newlng;

    ImageView language = findViewById(R.id.lang);
    if (lng.equals("sk")) {
        language.setImageResource(R.drawable.sk);
        newlng = "en"; tx="English language";
    }
    else {
        language.setImageResource(R.drawable.en);
        newlng = "sk"; tx="Slovenský jazyk";

   }

    showMsgSnack(tx);
    saveLang(newlng);

}

public void showMsgSnack(String msg) {
    View parentLayout = findViewById(android.R.id.content);
    Snackbar snackbar = Snackbar.make(parentLayout, msg, Snackbar.LENGTH_SHORT);
    snackbar.show();
}

private void saveLang(String lng) {
    SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
    sharedPreferences.edit().putString("hrad_lang", lng).apply();

    super.recreate();
}

If I remove  super.recreate();, the SnackBar shows up, but the lang is not changing, so I need it there.
Is there a solution, how to show that SnackBar before recreate?

A: Thanks to @Manuel Mato, the onSaveInstanceState seems working:
 protected void onSaveInstanceState( @NonNull Bundle texto) {
        super.onSaveInstanceState(texto);
        String lng = readLang();
        texto.putString("showlng", lng);
    }

and in onCreate:
 @Override
    protected void onCreate(Bundle texto) {
        super.onCreate(texto);
        if (texto != null){String tx;
            String tt = texto.getString("showlng");
            assert tt != null;
            if (tt.equals("sk")) { tx = "Slovenský jazyk";} else { tx = "English language";}
            showMsgSnack(tx);
        }

A: Its better to use the restore state method and rate positive the previous answer, thanks


text:
Q: called controller page of shopping_admin into ecommerce codeigniter application i have created one codeigniter application named as ecommerce. In this application i have created another codeigniter application called as shopping_admin into the application folder of ecommerce. so how can i called controller page of shopping_admin? how to configure shopping_admin?

A: What do you want?
Why you did not make single application and use the ACL (user Access Control List) between admin and user.
But if you still insist make 2 application on one directory, maybe you can use CURL.
Example here
sory for my bad english


text:
Q: /usr/local/bin/mitmproxy: No such script I'm trying to have mitmproxy do the tls_passthrough but I get the /usr/local/bin/mitmproxy: No such script
I'm running the command sudo mitmproxy --set stream_large_bodies=1 --set block_global=false --showhost -s tls_passthrough.py
System Information
sudo mitmproxy --version
Mitmproxy: 4.0.4
Python: 3.6.8
OpenSSL: OpenSSL 1.1.1 11 Sep 2018
Platform: Linux-4.15.0-58-generic-x86_64-with-Ubuntu-18.04-bionic

A: I have encounter same problem.
solution: makesure your xxx.py in mitmdump -s xxx.py path is correct
reason: the script in No such script means the script file = normally is xxx.py
you here: makesure the current path of running this your mitmproxy  -s tls_passthrough.py can find the file tls_passthrough.py
you can check it by:
pwd
ls -l

make sure can find tls_passthrough.py file.

A: If you typo: N.B. ERROR [missing leading "-" from "--set"]
mitmproxy -set upstream_bind_address=docs.mitmproxy.org -s tls_passthrough.py

will produce the, (slightly misleading error):
/usr/local/bin/mitmdump: No such script

when there is nothing wrong with the script.

A: You can find your the path with this.
which mitmproxy

and you can move that to /usr/local/bin/

A: I guess mitmdump doesn't support relative paths. I got the full path of the script, e.g. /workspace/example/scripts/add_cargo_auth_header.py:
mitmdump -s /workspace/example/scripts/add_cargo_auth_header.py

That worked for me.


text:
Q: C# SQL Server Relative Path I'd like my program to reference a relative path to the .mdf file so it can run on a new machine without modifying the connection string.
Environment:

*

*Microsoft Visual Studio Community 2019, Version 16.11.8

*Windows Forms

The connection string is pulled from the dbstring class:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Sharpening_Teeth
{
    public class dbString
    {
        // modifyTemplate pulls in the connection string from this class
        public static string getConnectionString()
        {
            return "Data Source=(LocalDB)\\MSSQLLocalDB;AttachDbFilename=C:\\Users\\vamel\\OneDrive\\Desktop\\test\\Sharpening Teeth\\Sharpening Teeth\\templateDB.mdf";
        }

        public static string getReadQuery()
        {
            return "SELECT template_id, template_name, message_content FROM dbo.message_template";
        }
    }
}

I'm just getting back into programming and I'm stuck. Hopefully someone can point me in the right direction here.  Thank you.
Threads reviewed

*

*Connection string with relative path to the database file

*How to set a relative path to a SQL Server Compact database?

*SQL Express connection string: mdf file location relative to application location

*connection string with relative path to database not working?

*How to set a relative path to a SQL Server Compact database?

*C# Visual Studio: |DataDirectory| keyword in connection string conflicts mdf files
EDIT
I found a solution on reddit.
https://www.reddit.com/r/csharp/comments/k0xaqb/local_db_sql_connection_string_without_using_the/