text:
Q: How to serialize XML with explicitly defined namespaces that matches inherited ancestor's namespace? TLDR version
I am serializing objects into XML to match a schema provided by a third party. Their validator requires one of the child objects to have a namespace explicitly declared which matches it's ancestor's namespace . The data is complex enough that I don't want to roll my own serializer for this purpose. How can I force the XMLSerializer class to explicitly render a namespace even though it is technically redundant?
Full version
I am running into an issue where the CoreItemsMkt namespace is not rendered by the XMLSerializer. I believe that this is because both the attribute and the namespaces exactly match the ancestor's namespace that it is inheriting from, therefore the serializer omits it - however, the site validator that this file gets submitted to requires it.
For example:
<?xml version="1.0" encoding="utf-8"?>
<FSAMarketsFeed xmlns="http://www.fsa.gov.uk/XMLSchema/FSAMarketsFeed-v1-2">
 <FSAFeedHeader xmlns="http://www.fsa.gov.uk/XMLSchema/FSAFeedCommon-v1-2">
  [...contents omitted, this item appears once...]
 </FSAFeedHeader>
 <FSAMarketsFeedMsg>
   <CoreItemsMkt xmlns="http://www.fsa.gov.uk/XMLSchema/FSAMarketsFeed-v1-2"> <!--//This namespace is the issue//-->
    [...contents omitted, this item appears multiple times...]
   </CoreItemsMkt?
 </FSAMarketsFeedMsg>
 <FSAMarketsFeedMsg>
   <CoreItemsMkt xmlns="http://www.fsa.gov.uk/XMLSchema/FSAMarketsFeed-v1-2"> <!--//This namespace is the issue//-->
    [...contents omitted, this item appears multiple times...]
   </CoreItemsMkt?
 </FSAMarketsFeedMsg>

I'm serializing with a method like this:
        var path = GetFilePath();

        var ns = new XmlSerializerNamespaces();
        ns.Add("", "http://www.fsa.gov.uk/XMLSchema/FSAMarketsFeed-v1-2");

        var ser = new XmlSerializer(typeof(FSAMarketsFeed));
        var settings = new XmlWriterSettings
        { Encoding = Encoding.UTF8, Indent = true, IndentChars = "\t", NamespaceHandling = NamespaceHandling.Default };
        using (var writer = XmlWriter.Create(path, settings))
        {
            ser.Serialize(writer, GetDataToSerialize(), ns);
        }

My root class is defined as:
[XmlType(AnonymousType = true)]
[XmlRoot(Namespace = "http://www.fsa.gov.uk/XMLSchema/FSAMarketsFeed-v1-2", IsNullable = false)]
public class FSAMarketsFeed
{
    public FSAMarketsFeed()
    {
        FSAMarketsFeedMsg = new FSAMarketsFeedMsg[0];
    }

    [XmlElement("FSAFeedHeader", IsNullable = true, Namespace = "http://www.fsa.gov.uk/XMLSchema/FSAFeedCommon-v1-2")]
    public FSAFeedHeader FeedHeader { get; set; }

    [XmlElement("FSAMarketsFeedMsg")]
    public FSAMarketsFeedMsg[] FSAMarketsFeedMsg { get; set; }
}

The working feed header class:
[XmlType(AnonymousType = true)]
public class FSAFeedHeader
{
    [XmlElement("FeedTargetSchemaVersion", IsNullable = true)]
    public string FeedTargetSchemaVersion { get; set; }

    [XmlElement("Submitter", IsNullable = true)]
    public Submitter Submit { get; set; }

    [XmlElement("ReportDetails", IsNullable = true)]
    public ReportDetails ReportDetail { get; set; }
}

The parent Feed Message Class:
[XmlType(AnonymousType = true)]
public class FSAMarketsFeedMsg
{
    [XmlElement("CoreItemsMkt", IsNullable = true, Namespace = "http://www.fsa.gov.uk/XMLSchema/FSAMarketsFeed-v1-2")]
    public CoreItemsMkt CoreMarket { get; set; }

    [XmlElement("Transaction", IsNullable = true)]
    public Transaction Trans { get; set; }
}

Finally, the CoreItemsMkt class which is failing to render its namespace:
[XmlType(Namespace = "http://www.fsa.gov.uk/XMLSchema/FSAMarketsFeed-v1-2", AnonymousType = true)]
public class CoreItemsMkt
{
    //[... Children omitted ...]]
}

Tried so far:

*

*Using XMmlType(AnonymousType = true) to try to break the inheritance chain

*Explicitly setting xmlns as an XmlAttributeAttribute w/ a hard coded value.

*Setting and removing XmlType(Namespace = "http://www.fsa.gov.uk/XMLSchema/FSAMarketsFeed-v1-2") on CoreItemsMkt

*Adding and removing XmlElement(Namespace = "the value") on the FSAMArketsFeedMsg's property.

*Implementing ISerializable on CoreItmsMkt (Couldn't quite figure out how to get that to work though.)

*Stack overflow searches - I've found 1 similar question that was answered with "This is unsupported, change your output namespace." Unfortunately, that answer doesn't work for me.

So, without hand rendering this, is there any way to force the XmlSerializer class to render those namespace attributes on CoreItmsMkt?

A: Try to use custom XML writer.
public class CustomWriter : XmlTextWriter
{
    public CustomWriter(TextWriter writer) : base(writer) { }
    public CustomWriter(Stream stream, Encoding encoding) : base(stream, encoding) { }
    public CustomWriter(string filename, Encoding encoding) : base(filename, encoding) { }

    public override void WriteStartElement(string prefix, string localName, string ns)
    {
        base.WriteStartElement(prefix, localName, ns);

        if (localName == "CoreItemsMkt")
        {
            base.WriteAttributeString("xmlns",
                "http://www.fsa.gov.uk/XMLSchema/FSAMarketsFeed-v1-2");
            //base.WriteAttributeString("xmlns", ns);
        }
    }
}

The custom writer forcibly adds the required attribute to every element with the CoreItemsMkt name.
Usage
using (var customWriter = new CustomWriter(path, Encoding.UTF8))
{
    customWriter.Formatting = Formatting.Indented;
    customWriter.Indentation = 1;
    customWriter.IndentChar = '\t';

    ser.Serialize(customWriter, GetDataToSerialize(), ns);
}

A: You would like to be able to force XmlSerializer to emit redundant xmlns= attributes when serializing specified nested elements.  Unfortunately, I don't know of any API to make this happen automatically.  You also wrote The data is complex enough that I don't want to roll my own serializer for this purpose so you don't want to have to implement IXmlSerializable on FSAMarketsFeedMsg.  (ISerializable is not used by XmlSerializer so implementing it will not help.)  Thus you're going to want to do something "semi-manual".  There are at least a couple of options for this.
Option 1: Serialize to a temporary XDocument then fix the attributes.
With this solution, you serialize to a temporary XDocument in memory, then add an XAttribute for each desired redundant xmlns=, as follows:
// Generate the temporary XDocument
var ns = Namespaces.GetFSAMarketsFeedNamespace();
var doc = data.SerializeToXDocument(null, ns);
var root = doc.Root;

// Add redundate xmlns= attributes
var name = XName.Get("CoreItemsMkt", Namespaces.FSAMarketsFeed);
var query = doc.Descendants(name); // Could be a more complex query, possibly even an XPath query.

foreach (var element in query)
{
    if (!element.Attributes().Any(a => a.IsNamespaceDeclaration))
    {
        var prefix = element.GetPrefixOfNamespace(element.Name.Namespace);
        if (string.IsNullOrEmpty(prefix))
            element.Add(new XAttribute("xmlns", element.Name.NamespaceName));
        else
            element.Add(new XAttribute(XNamespace.Xmlns + prefix, element.Name.NamespaceName));
    }
}

// Write the XDocument to disk.

Using the static extension classes:
public static class Namespaces
{
    public const string FSAMarketsFeed = @"http://www.fsa.gov.uk/XMLSchema/FSAMarketsFeed-v1-2";
    public const string FSAFeedCommon = @"http://www.fsa.gov.uk/XMLSchema/FSAFeedCommon-v1-2";

    public static XmlSerializerNamespaces GetFSAMarketsFeedNamespace()
    {
        var ns = new XmlSerializerNamespaces();
        ns.Add("", Namespaces.FSAMarketsFeed);
        return ns;
    }
}

public static class XObjectExtensions
{
    public static T Deserialize<T>(this XContainer element, XmlSerializer serializer)
    {
        using (var reader = element.CreateReader())
        {
            serializer = serializer ?? new XmlSerializer(typeof(T));
            object result = serializer.Deserialize(reader);
            if (result is T)
                return (T)result;
        }
        return default(T);
    }

    public static XDocument SerializeToXDocument<T>(this T obj, XmlSerializer serializer, XmlSerializerNamespaces ns)
    {
        var doc = new XDocument();
        using (var writer = doc.CreateWriter())
        {
            serializer = serializer ?? new XmlSerializer(obj.GetType());
            serializer.Serialize(writer, obj, ns);
        }
        return doc;
    }

    public static XElement SerializeToXElement<T>(this T obj, XmlSerializer serializer, XmlSerializerNamespaces ns)
    {
        var doc = obj.SerializeToXDocument(serializer, ns);
        var element = doc.Root;
        if (element != null)
            element.Remove();
        return element;
    }
}

Which produces the XML:

<FSAMarketsFeed xmlns="http://www.fsa.gov.uk/XMLSchema/FSAMarketsFeed-v1-2">
  <FSAFeedHeader xmlns="http://www.fsa.gov.uk/XMLSchema/FSAFeedCommon-v1-2">
    <FeedTargetSchemaVersion>value of FeedTargetSchemaVersion</FeedTargetSchemaVersion>
  </FSAFeedHeader>
  <FSAMarketsFeedMsg>
    <CoreItemsMkt xmlns="http://www.fsa.gov.uk/XMLSchema/FSAMarketsFeed-v1-2" />
  </FSAMarketsFeedMsg>
</FSAMarketsFeed>

Option 2: Do a nested serialization of CoreMarket using [XmlAnyElement] on its containing type.
Using an [XmlAnyElement] property, a type can serialize and deserialize any arbitrary child element.  You can use this functionality to do a nested serialization of CoreMarket with the necessary namespace declarations included.
To do this, modify FSAMarketsFeedMsg as follows:
[XmlType(AnonymousType = true)]
public class FSAMarketsFeedMsg
{
    [XmlIgnore]
    public CoreItemsMkt CoreMarket { get; set; }

    [XmlAnyElement(Name = "CoreItemsMkt", Namespace = Namespaces.FSAMarketsFeed)]
    [Browsable(false), EditorBrowsable(EditorBrowsableState.Never), DebuggerBrowsable(DebuggerBrowsableState.Never)]
    public XElement CoreMarketXml
    {
        get
        {
            return (CoreMarket == null ? null : XObjectExtensions.SerializeToXElement(CoreMarket,
                XmlSerializerFactory.Create(typeof(CoreItemsMkt), "CoreItemsMkt", Namespaces.FSAMarketsFeed),
                Namespaces.GetFSAMarketsFeedNamespace()));
        }
        set
        {
            CoreMarket = (value == null ? null : XObjectExtensions.Deserialize<CoreItemsMkt>(value,
                XmlSerializerFactory.Create(typeof(CoreItemsMkt), "CoreItemsMkt", Namespaces.FSAMarketsFeed)));
        }
    }

    // Remainder of properties are left unchanged.
}

In addition to the static extension classes from Option 1, you will need the following to avoid a substantial memory leak:
public static class XmlSerializerFactory
{
    static readonly Dictionary<Tuple<Type, string, string>, XmlSerializer> table;
    static readonly object padlock;

    static XmlSerializerFactory()
    {
        table = new Dictionary<Tuple<Type, string, string>, XmlSerializer>();
        padlock = new object();
    }

    public static XmlSerializer Create(Type serializedType, string rootName, string rootNamespace)
    {
        if (serializedType == null)
            throw new ArgumentNullException();
        if (rootName == null && rootNamespace == null)
            return new XmlSerializer(serializedType);
        lock (padlock)
        {
            var key = Tuple.Create(serializedType, rootName, rootNamespace);
            XmlSerializer serializer;
            if (!table.TryGetValue(key, out serializer))
            {
                var attr = (string.IsNullOrEmpty(rootName) ? new XmlRootAttribute() { Namespace = rootNamespace } : new XmlRootAttribute(rootName) { Namespace = rootNamespace });
                serializer = table[key] = new XmlSerializer(serializedType, attr);
            }
            return serializer;
        }
    }
}

Note that the [XmlAnyElement] property will be called for all unknown elements, so if your XML for some reason has unexpected elements, you may get an exception thrown from XObjectExtensions.Deserialize because the root element name is wrong.  You may want to catch and ignore exceptions from this method if that is a possibility.
Serialize to disk as you are currently doing.  The redundant xmlns= attributes will be present as in Option 1.


text:
Q: App crashes when rotating Samsung phone Has anyone else expereience that the app crashes if the phone is rotated?
I'm running Android 4.0.3 on my Samsung Galaxy 2.
The problem does not occur on HTC or Samsung running Android 2.3.3.
Eclipse debug screen is not showing any errors.
My app is developed using PhoneGap.
Log when I rotate phone:
05-25 13:38:09.155: I/GATE(20061): <GATE-M>DEV_ACTION_COMPLETED</GATE-M>
05-25 13:38:09.175: D/DroidGap(20061): Origin to allow: http://127.0.0.1*
05-25 13:38:09.175: I/CordovaLog(20061): Found log level DEBUG
05-25 13:38:09.175: I/CordovaLog(20061): Changing log level to DEBUG(3)
05-25 13:38:09.175: I/CordovaLog(20061): Found preference for classicRender
05-25 13:38:09.175: D/DroidGap(20061): DroidGap.onCreate()
05-25 13:38:09.180: D/DroidGap(20061): DroidGap.loadUrl(file:///android_asset/www/index.html)
05-25 13:38:09.180: D/DroidGap(20061): DroidGap: url=file:///android_asset/www/index.html baseUrl=file:///android_asset/www/
05-25 13:38:09.205: I/webclipboard(20061): clipservice: android.sec.clipboard.ClipboardExManager@4169fae8
05-25 13:38:09.210: D/DroidGap(20061): DroidGap.init()
05-25 13:38:09.260: D/PluginManager(20061): init()
05-25 13:38:09.280: D/WML_SISO(20061): InitPasteboardJni
05-25 13:38:09.280: D/SoftKeyboardDetect(20061): Ignore this event
05-25 13:38:09.730: W/IInputConnectionWrapper(20061): showStatusIcon on inactive InputConnection
05-25 13:38:09.790: I/GATE(20061): <GATE-M>DEV_ACTION_COMPLETED</GATE-M>
05-25 13:38:09.810: I/GATE(20061): <GATE-M>DEV_ACTION_COMPLETED</GATE-M>

A: You need to add screenSize to the android:configChanges attribute of your activity and build against at least android-13 target since this value was introduced in API level 13.

A: Did you tried to add :     android:configChanges="orientation"  in
<activity android:name=".activityName"/>

redpajama_set_name: RedPajamaStackExchange


text:
Q: What's the difference between -objectRegisteredForID: and -existingObjectWithID:error:? What's the difference between getting an managed object with
- (NSManagedObject *)objectRegisteredForID:(NSManagedObjectID *)objectID

and
- (NSManagedObject *)existingObjectWithID:(NSManagedObjectID *)objectID error:(NSError **)error

What are "registered" objects? What's the difference between "registered" objects and "unregistered" objects?

A: Years after the fact:
As Wienke suspects, registered objects are those already in memory for that context. So objectRegisteredForID: will return an object only if somebody else has previously obtained that object.
objectWithID: will return an object if it currently exists in the persistent store.
So the really important distinction is:
objectWithID may go to the persistent store.
Note the corollary: objectWithID may have to perform a fetch. That means locking the store. So:

*

*if the store is already locked by somebody else, objectWithID may block, whereas objectRegisteredForID will never block; and

*supposing you had an array of 30 object IDs and you performed objectWithID for each, you'd potentially do 30 separate trips to the store — it'd be much faster to check whether the objects are already registered and then, if any aren't, use an NSFetchRequest to get the rest. Notice that a self in X query can accept an array or set of object IDs to return actual objects even though that wouldn't technically exactly match the normal Objective-C meaning of 'self'.

Falling back on NSFetchRequest is also generally preferable if you have any relationship paths you're going to need prefetched. So there's potentially quite a lot of performance to be gained.

A:
What are "registered" objects?

Judging from the results I've gotten using these methods, a registered object is one that has been fetched into the MOC. If an object exists in the persistent store but has not been fetched, feeding its objectID to the objectRegisteredForID method will return nil.
How could you even have its objectID if it had not been fetched? Well, I visited this question when implementing a Revert routine. I dumped any unsaved changes by replacing the database with an older copy, cleared the context and then reaccessed it. But I wanted to be able to restore the  user's selection of objects to the cache of a table. So, before doing the reversion, I stashed the objectIDs that the user had selected in an array. Then, after the reversion, I rebuilt the table cache using the stashed objectIDs.
When I called objectRegisteredForID using these stashed objectIDs, it always returned nil. (But if I tested this before getting a fresh context, it would return the corresponding object -- which at that point was a fetched, loaded object. Hence my inference as to the meaning of "registered.")
When I called objectWithID using these stashed objectIDs, everything was fine unless the object had been deleted post the last save, in which case it would no longer exist in the database and the invalid but non-nil return would cause exceptions later.
So I used existingObjectWithID:error. If the object still existed, it would be returned. If it no longer existed, the return would be nil and the error's localizedDescription would be "Attempt to access an object not found in store."

A: To your first question:
objectRegisteredForID: is the quick & easy way to get the object -- it either returns your object or it returns nil letting you know that it could not.  You use this when you either already know why the result might be nil or you don't care.
existingObjectWithID:error: is similar, in that it returns either your object or nil but, in addition, if you pass an error parameter, it will tell you WHY it returned nil.  You may want to do this if you plan to do any sort of error reporting (a log message or alert), or error handling (perhaps you plan to take different actions, depending on which kind of error is returned.
EDIT: In addition (per docs), if there is not a managed object with the given ID already registered in the context, the corresponding object is faulted into the context.
I suggest that you break out the "what are registered objects?" portion of your question to a separate question in order to facilitate both getting a better answer (based on the subject line matching the question) and to help future spelunkers who may come looking for an answer.

A: I was recently confused as to why registeredObject(for objectID: NSManagedObjectID) was returning nil, but there was a simple explanation: the NSManagedObject instances I fetched were not retained: I extracted the information I needed from them and let them be deallocated, which seems to "unregister" them from the managed object context, though they could easily be retrieved using other methods on NSManagedObjectContext. I find the CoreData documentation truly terrible: "registered" is just one of many distinctions that are not clearly explained.


text:
Q: cannot insert value to sqlite DB iOS Well following this tutorial I have some problems in inserting values to my DB although everything seems to be working fine.
This is my code for inserting entries.
-(void)insertOrder:(MyOrderList*)entry
{
    // Create insert statement for the person
    NSString *insertStatement = [NSString stringWithFormat:@"INSERT INTO LIST (URL, CODE, EMAIL, FULL) VALUES (\"%@\", \"%@\", \"%@\",\"%@\")", entry.db_url, entry.db_code, entry.db_email,entry.db_full];
    NSLog(@"SQL INSERTION COMMAND:%@",insertStatement);

    char *error;
    if ( sqlite3_exec(databaseHandle, [insertStatement UTF8String], NULL, NULL, &error) == SQLITE_OK)
    {
            NSLog(@"Order inserted.");
    }
    else
    {
        NSLog(@"Error: %s", error);
    }
}

And I can see "Order Inserted" being printed out.
This is my code for retrieving the list.
-(NSArray*) getList
{
    NSMutableArray *persons = [[NSMutableArray alloc]init];
    NSString *queryStatement = [NSString stringWithFormat:@"SELECT URL,CODE ,MAIL, FULL FROM LIST"];
    sqlite3_stmt *statement;
    NSLog(@"Query:%@",queryStatement);
    if (sqlite3_prepare_v2(databaseHandle, [queryStatement UTF8String], -1, &statement, NULL) == SQLITE_OK)
    {
        // Iterate over all returned rows
        while (sqlite3_step(statement) == SQLITE_ROW) {
            NSLog(@"Url of my List is:%@",[NSString stringWithUTF8String:(char*)sqlite3_column_text(statement, 0)]);

            MyOrderList *person = [[MyOrderList alloc]initWithUrl:[NSString stringWithUTF8String:(char*)sqlite3_column_text(statement, 0)] andCode:[NSString stringWithUTF8String:(char*)sqlite3_column_text(statement, 1)] andEmail:[NSString stringWithUTF8String:(char*)sqlite3_column_text(statement, 2)] andFull:[NSString stringWithUTF8String:(char*)sqlite3_column_text(statement, 3)]];
      [persons addObject:person];

            // Release the person because the array takes ownership
            //[person release];

        }
        sqlite3_finalize(statement);
    }
    //return [persons autorelease];
    return persons;

}

and this is how I use it in my .m file
  DataController *dataController = [[DataController alloc]init];
                [dataController initDatabase];
                //[dataController release];

                 MyOrderList *order  = [[MyOrderList alloc] initWithUrl:url_2 andCode:keycode andEmail:mail andFull:full_2 ];
                [dataController insertOrder:order];
                //data has been added
                NSMutableArray* persons = [dataController getList];

and I see that persons are 0.
From terminal I see this:
Admins-MacBook-Air:~ admin$ sqlite3 Users/admin/Library/Application\ Support/iPhone\ Simulator/5.1/Applications/1A70F53B-133E-46AE-833E-13F205EA96EA/Documents/sqlite.db
SQLite version 3.7.12 2012-04-03 19:43:07
Enter ".help" for instructions
Enter SQL statements terminated with a ";"
sqlite> .schema
Error: unable to open database "Users/admin/Library/Application Support/iPhone Simulator/5.1/Applications/1A70F53B-133E-46AE-833E-13F205EA96EA/Documents/sqlite.db": unable to open database file
Admins-MacBook-Air:~ admin$

it's like my db is not even created.
this is my code for creating the DB.
-(void)initDatabase
{
    // Create a string containing the full path to the sqlite.db inside the documents folder
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths objectAtIndex:0];
    NSString *databasePath = [documentsDirectory stringByAppendingPathComponent:@"sqlite.db"];
    NSLog(@"Path is:%@",databasePath);

    // Check to see if the database file already exists
    bool databaseAlreadyExists = [[NSFileManager defaultManager] fileExistsAtPath:databasePath];

    // Open the database and store the handle as a data member
    if (sqlite3_open([databasePath UTF8String], &databaseHandle) == SQLITE_OK)
    {
        // Create the database if it doesn't yet exists in the file system
        if (!databaseAlreadyExists)
        {
            // Create the PERSON table
            const char *sqlStatement = "CREATE TABLE IF NOT EXISTS LIST (ID INTEGER PRIMARY KEY AUTOINCREMENT, URL TEXT, CODE TEXT, EMAIL TEXT, FULL TEXT)";
            char *error;
            if (sqlite3_exec(databaseHandle, sqlStatement, NULL, NULL, &error) == SQLITE_OK)
            {
                NSLog(@"Database and tables created.");
            }
            else
            {
                NSLog(@"Error: %s", error);
            }
        }
    }
}


text:
Q: False error in XAML parsing I'm getting a persistent non-fatal error when the building my WinRT project
Error 1 Closing tag for element '' was not found.
Of course there is an ending tag in my XAML and the project builds and runs just fine. How can I get VS to just give up on this error?
(Yes, I've tried a clean build)

A: I also got a similar error. Closing and reopening the solution resolved it. I believe this issue was fixed with Visual Studio 2012 Update 2
Have a look at : http://social.msdn.microsoft.com/Forums/windowsapps/en-US/dea9687f-5939-4a15-b197-707eb3f26d3b/false-error-in-xaml-parsing


text:
Q: How to share code between projects in Visual C++ or "unresolved external symbol" for static variables in static lib I have two Projects in my Visual Studio C++ Solution and I want to share some code between them.
So, I looked for it, and found that a lot of people suggested creating static library and linking it with both projects. However, when I do it, I got "unresolved external symbol" error for all static variables. Here how to reproduce the problem:
1) Create empty Visual Studio Solution with empty project named Project1, change it's type to "static library" (lib). Add Foo class:
Foo.h:
#pragma once
class Foo
{
public:
    static int F(int a);
private:
    static int bar;
};

Foo.cpp:
#include "Foo.h"
int Foo::F(int a)
{
    bar = 3;
    return a*bar;
}

2) Create empty project named Project2.
Source.cpp:
#include <iostream>
#include "Foo.h"
int main()
{
    std::cout << Foo::F(2) << std::endl;
    std::cin.get();
    return 0;
}

3) In Properties of Project2, add Project1 folder to "Additional Include Directories"
4) In Common Properties of Project2, click "Add new reference" add Project1 as a new reference. (or you can add Project1.lib it in Linker -> Input -> Additional Dependencies).
Now, when you compile only static library (Project1), it works.
When you compile both or just your executable (Project2), you got
2>Project1.lib(Foo.obj) : error LNK2001: unresolved external symbol "private: static int Foo::bar" (?bar@Foo@@0HA)
2>C:\dev\Project1\Debug\Project2.exe : fatal error LNK1120: 1 unresolved externals

If you remove static variable, it works.
What am I doing wrong? Is there any better way and simple way to share code between projects (rather than just including same .cpp/.h files into both projects)?

A: You have declared bar in Foo but you haven't provided a definition for it. You need to add the following to your code.
int Foo::bar;

If you would like to initialize it with a specific value (say 42) you can do
int Foo::bar = 42;

The reason you only get a linker error for Project1 is because neither the static library nor Project2 actually access Foo::bar so there are no references to it for the linker to resolve.


text:
Q: maxima find root of equation Good morning everyone,
Im trying to get used to using maxima.
Specifically the find root function.
To find the root of this equation:
$0.85 = \frac{16}{(19.62 (\sin x + \frac{5}{12}\cos x)}$
So I have entered the following into maxima:
find_root(0.85 = 16/(19.62*(Sin*x + 5/12*cos*x)),x,1,2);
Have I made any obvious mistakes? I haven't slept much so im really hoping someone will spot a syntax error or something as I think ive become blind by looking at it so much!
EDIT:
I have tried this equation in Maxima and its not doing anything at all, which is why I assume it is incorrect. :)

A: HINT
Transpose and go towards sine of angle sum
$$ \dfrac{ 16 \cdot 12}{(0.85)19.62 (13)}=\frac{12  \sin x + 5 \cos x }{13} $$
with $$ \sin \theta= \dfrac{5}{13} \,$$ etc.


text:
Q: Get "Day" of Selected Date in ngb-datepicker (ng Bootstrap) in Angular Application Demo:
https://stackblitz.com/edit/angular-bife8z-px13fl?file=app%2Fdatepicker-basic.html
I have added Day(Sunday) as static text, i want this to be changed according to date selection form calendar.

A: You can use the calendar to get the day of the week and have a Dictionary which stores the Day names.
weekDays = {
  1: 'Monday',
  2: 'Tuesday',
  3: 'Wednesday',
  4: 'Thursday',
  5: 'Friday',
  6: 'Satarday',
  7: 'Sunday'
}

Selected Date is: {{weekDays[calendar.getWeekday(model)]}}

https://stackblitz.com/edit/angular-bife8z-bftzuu?file=app%2Fdatepicker-basic.html
Infact you can have a variable for day which gets set in the setter of the model variable.
  selectedDay: string = '';
  set model(val) {
    this._model = val;
    this.selectedDay = this.weekDays[this.calendar.getWeekday(this.model)]
  }

  get model() {
    return this._model;
  }

 Selected Date is: {{selectedDay}}

A: Try this:
component html
Selected Date is: {{getDay(model)}}

component ts
  getDay(model){
    let date = new Date(Date.UTC(model.year, model.month - 1, model.day, 0, 0, 0))
    let days = new Array( "Monday", "Tuesday", "Wednesday", "Thursday",  "Friday", "Saturday", "Sunday" );
    let day = days[date.getDay() - 1]
    return day
  }


text:
Q: How can I write a batch file that launch a http request everyday? I want to write a batch file that sends the same http request everyday at a specific time.
I have tried this :
start http://mysite.org
exit

A: Use wget for Windows. It can send any request to given address.
wget http://mysite.org


text:
Q: after editing when update button press ,no data change why i want to make admin panel.my problem is that after editing show data but when edit the data and update no any data changes in database no changes
plz help me and give me correct direction
MY FIRST PHP FILE
 <?php
    $conn=mysqli_connect('localhost','root','','admin');
    $sql="SELECT * FROM admin";
    $result=mysqli_query($conn,$sql);
    while($row=$result->fetch_assoc())
    {
        $id=$row['id'];
        $name=$row['name'];
        $email=$row['email'];
    ?>

            <form action="111.php" method="post">

<?php echo $id ?>	<?php echo $name ?>	<?php echo $email ?>		<input type="hidden" name="id" value="<?php echo $id ?>">
            <input type="submit" name="edit" value="edit">
</form>

    <?php
    }
    ?>

MY SECOND PHP FILE
  <?php
    $conn=mysqli_connect('localhost','root','','admin');
    if(isset($_POST['edit']))
    {
        $id=$_POST['id'];
        $sql="SELECT * FROM admin where id='$id'";
        $result=mysqli_query($conn,$sql);
        while ($row=$result->fetch_assoc())
        {
        $id=$row['id'];
        $name=$row['name'];
        $email=$row['email'];
    ?>
    <form action="2017.php" method="post">
    <input type="hidden" name="id" value="<?php echo $id ?>">
    <input type="text" name="name" value="<?php echo $name ?>">
    <input type="text" name="email" value="<?php echo $email ?>">
    <input type="submit" name="update" value="update">
    </form>

    <?php
    }
    }
    ?>

MY THIRD PHP FILE
<?php
$conn=mysqli_connect('localhost','root','','admin');
if(isset($_POST['update']))
{
    $id=$_POST['id'];
    $name=$_POST['name'];
    $email=$_POST['email'];
    $sql="UPDATE admin SET name='$name' AND email='$email' where id='$id'";
    mysqli_query($conn,$sql);
    echo "successfully update";
}
?>

A: You need to separate fields in UPDATE query with commas not with AND.
Correct:
$sql="UPDATE admin SET name='$name' AND email='$email' where id='$id'";

To:
$sql="UPDATE admin SET name='$name', email='$email' where id='$id'";


text:
Q: OpenCV K-Means (kmeans2) I'm using Opencv's K-means implementation to cluster a large set of 8-dimensional vectors. They cluster fine, but I can't find any way to see the prototypes created by the clustering process. Is this even possible? OpenCV only seems to give access to the cluster indexes (or labels).
If not I guess it'll be time to make my own implementation!

A: I can't say I used OpenCV's implementation of Kmeans, but if you have access to the labels given to each instance, you can simply get the centroids by calculating the average vector of instances belong to each of the clusters.

A: As of (at least) OpenCV 2.0, there is the way to retrieve cluster centers (see the latest argument):
double kmeans( const Mat& samples, int clusterCount, Mat& labels,
  TermCriteria termcrit, int attempts,
  int flags, Mat* centers );

http://opencv.willowgarage.com/documentation/cpp/clustering_and_search_in_multi-dimensional_spaces.html#cv-kmeans


text:
Q: What is a parametrized surface? How is it different from a surface? (Multivariable Calculus) My textbook defines it like this:
Let F be a continuous function from a subset D(F) R2 into Rq. Suppose that D(F) is pathwise connected, and that every point in D(F) is either an interior point of D(F), or on the boundary of the interior of D(F).  Then F is called a parametrized surface in Rq.
I understand what everything in the definition means and understand how to check for all the conditions.  However, I do NOT understand what type of surface is being described.  How do these special qualities of the domain enhance our understanding of the surface?
Can someone explain what a parametrized surface is (intuitively, not formally) and how that relates to this formal definition?
What consequences are their to a surface being a "parametrized surface?"

A: There are three ways I like to think about surfaces: 1) as graphs of functions from $\mathbb{R}^2$ to $\mathbb{R}$, 2) as level sets of functions $\mathbb{R}^3 \rightarrow \mathbb{R}$, and 3) as images of maps $\mathbb{R}^2 \rightarrow \mathbb{R}^3$.  Surfaces of the third type are called parametric.
Here are examples of each:
1) The graph of $z = x^2 + y^2$ is a paraboloid.
2) The sphere is the level set $x^2 + y^2 + z^2 = 1$.  Here the function from $\mathbb{R}^3$ to $\mathbb{R}$ is $F(x,y,z) = x^2 + y^2 + z^2$.  Note that the graph of $F$ is a hypersurface in $\mathbb{R}^4$, but that when we take a level of $F$ (i.e., set it equal to a constant) it becomes a surface in $\mathbb{R}^3$.
3) The torus (surface of a donut) is a parametric surface that can be defined as the image of the map $G:\mathbb{R}^2 \rightarrow \mathbb{R}^3$ given be $G(u,v) = ((2 + cos(v))cos(u), (2 + cos(v))sin(u), sin(v))$.  Here, the input variables $u$ and $v$ are called parameters, and the output coordinates could be specified as three "parametric equations":
x = (2 + cos(v))cos(u)
y = (2 + cos(v))sin(u)
z = sin(v)
As $u$ and $v$ take on different values, the function $G$ traces out the surface in space.
There's more to say here, but that's a start!


text:
Q: Basic question on math notation of max and min When we write $\text{max}\left \{x,y  \right \}$ and $\text{min}\left \{x,y  \right \}$ then what do we actually mean? Does it mean the maximum and minimum of both the things that are inside $\left \{  \right \}$. Say $\epsilon = \text{max}\left \{1,3  \right \}$ then what does it exactly mean in a numeric sense? If $x = 1$ and $y = 3$, then is  $\epsilon = \text{max}\left \{1,3  \right \}$ the biggest number formed from $x$ and $y$?

A: For real $a$ and $b$ (and in general for any $a$ and $b$ belonging to some order), $\max\{a, b\} = a$ if $a \geq b$; otherwise, $\max\{a, b\} = b$.

A: Yes, $\max(1,3)$ means the biggest number from both and $\min(1,3)$ means the smallest number.


text:
Q: Quuiero agregar una referencia desde Reference Manager en Visual Studio 2019, pero no me sale la opción Assemblies Estoy creando un windows form en C#, y necesito agregar la referencia "System.Configuration" pero no me sale la pestaña de "Assemblies". ¿Cómo la agrego?

A: Lo resolví por mí mismo. El problemafue el tipo de Class Library que estaba utilizando, debía ser de tipo "Net.Framework"


text:
Q: Unable to get "Description" into SharePoint 2010 search results XML I'm failing terribly at adding a field to my search results.
The fields (external) name is "description" and is, to my knowledge, not custom made but out of the box.
The Webpart settings already contain the element , the XML output is correct but the  tag is empty. Although the field is filled out on multiple files!
Upon further inspection, the internal name of the column appears to be "RoutingRuleDescription". Adding this to the webpart settings results in "Property doesn't exist or is used in a manner inconsistent with schema settings."
Any ideas?

A: Did you do a full crawl?
In order to get a new property in the search results you need to do the following:

*

*Create a column and fill it at least with one value

*Do a full crawl

*Create a managed property and map the crawled property to it

*Do a full crawl

*Verify the xml results and see if the property is filled.

See http://technet.microsoft.com/en-us/library/ff621097(v=office.14).aspx for more details.


text:
Q: how to dynamically name a form element with javascript I'm scripting an html form inside a PHP. The form is shown as a table. Every row is a 'set' of passed items that will be gathered in a $_POST double array where the first id is the table ROW, and the second identifier is the COLUMNS, actually the variables of the form.
Here is an example.
<?php
echo '<form>
';
for ($i=1;$i<10;$i++){
echo '

       <input type="text" name="data[',$i,'][element1]>
       <input type="text" name="data[',$i,'][element2]>
       <input type="text" name="data[',$i,'][element3]>
       ...
       <input type="text" name="data[',$i,'][elementN]>

';
}
echo '
</form>';
?>

The "gathering" part of the script simply is:
$myFormInformation = $_REQUEST['data'];

and shows the content like this:
data[1][element1] = element 1-1
data[1][element2] = element 1-2
...
data[1][elementN] = element 1-N
..
data[2][element1] = element 2-1
...
data[2][elementN] = element 2-N
... ... ...
data[10][elementN] = element 10-N

I rendered the idea...and it perfectly works. However I don't want to have all teh 10 rows shown for input, but, instead, grant the user to add rows if needed.
I found this javascript snippet to add rows, however the problem is that I don't know how to pass the ROW ID dynamically to allow my $_REQUEST part of code to work. At this moment in fact the $_REQUEST gets only one row.

obviously there is a button with id=addNewRow to launch the javascript.
How can I pass a "counter" from the javascript to the forms element in order to have each new row increase it's name="data[i][elementX]".
I can accept other ways to do the job done, if easier...
thanks!

A: You can loop the td elements and then find the input. Setting the name attribute as you please.
Something like this:
function addRow() {
    var referenceNodes = document.getElementById("flightsTable").getElementsByTagName("tr");
    //-2 because last row is button row
    var referenceNode = referenceNodes[referenceNodes.length - 1];
    var newNode = referenceNode.cloneNode(true);

    // get the next count for the new row.
    var dataCount = referenceNodes.length + 1;

    // loop the cells.
    var cells = newNode.getElementsByTagName("td");
    for (var i = 0; i < cells.length; i++) {
        var cell = cells[i];

        // get the input (assuming only one).
        var input = cell.getElementsByTagName("input")[0];

        // set the name property.
        input.name = "data['" + dataCount + "'][element" + (i + 1) + "]";
    }

    referenceNode.parentNode.insertBefore(newNode, referenceNode.nextSibling);
}

Here is a working example


text:
Q: S3 Notification - Downloadable Link I have a lambda function that requires the URL associated with an S3 object.
I have S3 notifications set-up as described, and have looked over the template for a Record https://docs.aws.amazon.com/AmazonS3/latest/dev/notification-content-structure.html
My question is, is there a way to determine the URL Link for an object? (assumes client has read permissions)
Is it safe to use the pattern:
https://s3.amazonaws.com/{bucket name}/{key}
And/Or is there a better way of obtaining information?

A: It is not safe to use https://s3.amazonaws.com/{bucket}/{key}.
That is only valid for objects in the us-east-1 region -- the original S3 region -- and only for ipv4.  Requests for buckets in other regions will throw an error except in a few limited circumstances.
The standardized formats:
https://{bucket}.s3.{region}.amazonaws.com/{key} # ipv4
https://{bucket}.s3.dualstack.{region}.amazonaws.com/{key} # ipv4/v6

If the bucket has dots in its name, place the bucket name between the hostname and key, ...amazonaws.com/{bucket}/{key}, instead of at the beginning of the hostname.
Some regions also have legacy hostnames that are also valid, such as replacing s3.us-west-2 with s3-us-west-2 in us-west-2, or replacing s3.us-east-1 with s3-external-1 in us-east-1 but all regions now support the consistent formats, above.
https://docs.aws.amazon.com/general/latest/gr/rande.html#s3_region


text:
Q: Sair do git log ou git diff Rodei o comando git log e visualizei todo o conteúdo, até chegar ao final conforme o print:

Porém, não conisgo fazer mais nada nessa janela de terminal. Já tentei escrever exit, digitar Ctrl+C e nada. Como faço para sair desse comando?

A: O que ocorre é que o git carrega um programa less, que permite que o log seja escrolável. Para sair desse programa, basta digitar q. Para objter ajuda, digite h


text:
Q: VBscript error handling - move to a next item in a "For Each" loop I have a loop that processes each file of a folder. In case a file is corrupted and can't be opened, I want to:
- Display the error message to the user
- Stop the execution of the remaining code
- Loop to the next file
The problem is, that if the file cannot be opened at the beginning of the loop, there's still a lot of code that will execute, which will throw other errors. I cannot exit the loop, since this would mean that not all of the files would get processed, and I cannot continue the execution of the code. Please see the part of the code below.
Set fso = CreateObject("Scripting.FileSystemObject")
For each objFile in fso.GetFolder(".").Files
    If lCase(fso.GetExtensionName(objFile)) = srcExtName Then
        Set app = GetNewAppInstance (Program)
        Set fileHandle = GetNewFileHandler(app)

        On Error Resume Next
            Set objOpenFile = fileHandle.Open(objFile.path)
            If err.number <> 0 Then
            next
                MsgBox "The file " & objFile.name & " cannot be opened. Please verify that the file is not corrupted or locked." & vbNewLine & "The file will be skipped."
                Set fileHandle = nothing : app.Quit : Set app = nothing
                <<< How can I jump to the next file from here ? >>>
            End If
        On error goto 0
        strSrcPath = fso.BuildPath(objOpenFile.path, fso.GetBaseName(objOpenFile.name) & "._temp")
        objOpenFile.SaveAs strSrcPath, tmpExtNum
        objOpenFile.Close

        Set objOpenFile = nothing
        Set fileHandle = nothing
        app.Quit : Set app = nothing

        Set app = GetNewAppInstance (Program)
        Set fileHandle = GetNewFileHandler(app)

        Set objOpenFile = fileHandle.Open(strSrcPath)
        strTgtPath = fso.BuildPath(objOpenFile.path, fso.GetBaseName(objOpenFile.name) & "." & srcExtName)
        objOpenFile.SaveAs strTgtPath, srcExtNum
        objOpenFile.Close
        fso.DeleteFile(strSrcPath)

        Set objOpenFile = nothing
        Set fileHandle = nothing
        app.Quit : Set app = nothing
    End If
Next
End Sub

Thanks!

A: Try this:
Set fso = CreateObject("Scripting.FileSystemObject")
For each objFile in fso.GetFolder(".").Files
    If lCase(fso.GetExtensionName(objFile)) = srcExtName Then
        Set app = GetNewAppInstance (Program)
        Set fileHandle = GetNewFileHandler(app)

        On Error Resume Next
        Set objOpenFile = fileHandle.Open(objFile.path)
        If err.number <> 0 Then
            MsgBox "The file " & objFile.name & " cannot be opened. Please verify that the file is not corrupted or locked." & vbNewLine & "The file will be skipped."
            Set fileHandle = nothing : app.Quit : Set app = nothing
        Else
            strSrcPath = fso.BuildPath(objOpenFile.path, fso.GetBaseName(objOpenFile.name) & "._temp")
            objOpenFile.SaveAs strSrcPath, tmpExtNum
            objOpenFile.Close

            Set objOpenFile = nothing
            Set fileHandle = nothing
            app.Quit : Set app = nothing

            Set app = GetNewAppInstance (Program)
            Set fileHandle = GetNewFileHandler(app)

            Set objOpenFile = fileHandle.Open(strSrcPath)
            strTgtPath = fso.BuildPath(objOpenFile.path, fso.GetBaseName(objOpenFile.name) & "." & srcExtName)
            objOpenFile.SaveAs strTgtPath, srcExtNum
            objOpenFile.Close
            fso.DeleteFile(strSrcPath)

            Set objOpenFile = nothing
            Set fileHandle = nothing
            app.Quit : Set app = nothing
        End If
        On error goto 0
    End If
Next

I've moved the "rest" of your code into the else block of your if statement, so it will only execute if you have no error.


text:
Q: Prevent cheating in a timed online quiz My company regularly run competitions on the internet. These consist of simple multiple choice  quizzes, where the fastest person to complete the quiz wins a prize.
Recently we've been having big problem with cheaters (a lot of sub one second entries that would be impossible to complete manually). The time is calculated server side, so the cheater can't be manipulating the times directly. The only feasible way to cheat would be to write a script to automatically fill in and submit the quiz.
We've already implemented the following to try and combat this:

*

*Limit the user to one entry (by checking IP and asking for email address)

*randomly take questions from a pool (unfortunately each quiz has to be translated, so the actual pool size is quite small due to our limited translation resources)

*randomize question and answer order

*randomize quiz element class names and ids

Even with all of the techniques above, we're still getting people who manage to cheat.
As a last resort, we're considering replacing the quiz text with images, and randomizing the image names, but this would be a nightmare for accessibility and could still feasibly be cheated by using image comparison. Hence, we really want to avoid this if at all possible.
So I was wondering if anybody here had any ideas of how to combat this?

A: Maybe load the next Random question with AJAX only after the previous question get answered. I hope this helps.


text:
Q: How to Abort (Stop) a chain of promises, executed in a loop? - JavaScript I have a web application, in which I have two buttons: "start download" and "abort download", that are bind to the methods: start() and stop() accordingly.
1. When the user clicks the "start download" button, the application will loop over an array of data. For each item in the array, it will call the _downloadFile() method that will download one file and return a new Promise(), once that download is complete the next download will start.
2. If during the download flow (that may take a long long time) the user clicked the "abort download" button I would like to stop the download flow.
How can I implement the abort functionality?
Here is what I got so far?
Notice that due to the fact I'm using async/await, the loop will holt until the promise is resolved, and the next iteration will only be executed once the promise is resolved (or rejected).
async function start(dataArray)
{
  for (let i = 0; i < dataArray.length; i++)
  {
    try
    {
      let fileUrl = `http://server-url/${ i }/${ dataArray[i] }.xml`;
      let result = await _downloadFile(fileUrl);
      _saveResult(result);
    }
    catch(e) // promise rejected
    {
      _handleError(e);
    }
  }
}

function stop()
{
  // what goes here?? how do I stop the flow??
}

function _downloadFile(fileUrl)
{
  return new Promise((resolve, reject) =>
  {
    // ...
  });
}

function _saveFile(data)
{
  // ..
}

function _handleError(error)
{
  console.error("Error: " + error);
}

A: Set a flag that the function can check, and throw if it's set. (Well, you're actually converting rejection to resolution in your code, so maybe you don't throw, just return early. [I wouldn't do that, btw.])
let stopped = false; // *** The flag
async function start(dataArray)
{
  stopped = false;                                  // *** Re-init the flag
  for (let i = 0; i < dataArray.length; i++)
  {
    try
    {
      let fileUrl = `http://server-url/${ i }/${ dataArray[i] }.xml`;
      let result = await _downloadFile(fileUrl);
      if (stopped) {                                // *** Check the flag
          return;                                   // *** and return
      }
      _saveResult(result);
    }
    catch(e) // promise rejected
    {
      _handleError(e);
    }
  }
}

function stop()
{
  // *** Set the flag
  stopped = true;
}


text:
Q: R recycling process Please see the snippet below:
x <- c(23,43,54,75,76,6,87,5,43,234,2)
y <- c(1,2,23,43,54,75,76,6,87,1)
z <- x + y

The snippet gives me the warning message.When I try to add x and y as:
#Warning message:
#In x + y : longer object length is not a multiple of shorter object length

However When I add:
x <- c(3,4,5,8)
y <- c(1,3)
z <- x + y
z

No error message is thrown and R recycles it perfectly. Why?

A: First of all, it is important to notice that this is a warning, and not an error. So in either case, no error is thrown and the vectors are added.
Concerning the absence of the warning in your second example, the warning message states the reason quite clearly:

object length is not a multiple of shorter object length

In your second example, the length of x is twice the length of y, so it is a multiple (in contrast to your first example, which yields the warning). Hence, no warning is given in the second example when the vector y is recycled.


text:
Q: How do I pull singe cell RNA sequencing data from GEO database? I am new to R and computational biology. I am trying to look through a published data set to check for gene expression for my own project. I am having trouble finding materials to teach me how to analyze single cell RNA sequencing data on R from the GEO NCBI database.
This is the data that I am trying to access https://www.ncbi.nlm.nih.gov/geo/query/acc.cgi?acc=GSE138651
I would appreciate any directions or suggestions for tutorials.
Thanks!

A: You might want to check out the BioConductor GEOquery package.
Install using
if (!requireNamespace("BiocManager", quietly = TRUE))
    install.packages("BiocManager")

BiocManager::install("GEOquery")

More information on how to use this package and read in data from GEO can be found in the vignette


text:
Q: Query Store "Overall Resource Consumption" details I want to know how much total CPU a database has consumed for a given date span, for all queries.
I can see it in SSMS (under Query Store / Overall Resource Consumption), but how can I query for that programmatically?

A: The Query Store GUI uses this T-SQL:
exec sp_executesql N'WITH DateGenerator AS
(
SELECT CAST(@interval_start_time AS DATETIME) DatePlaceHolder
UNION ALL
SELECT  DATEADD(d, 1, DatePlaceHolder)
FROM    DateGenerator
WHERE   DATEADD(d, 1, DatePlaceHolder) < @interval_end_time
),
UnionAll AS
(
SELECT
    CONVERT(float, SUM(rs.count_executions)) as total_count_executions,
    ROUND(CONVERT(float, SUM(rs.avg_duration*rs.count_executions))*0.001,2) as total_duration,
    ROUND(CONVERT(float, SUM(rs.avg_cpu_time*rs.count_executions))*0.001,2) as total_cpu_time,
    ROUND(CONVERT(float, SUM(rs.avg_logical_io_reads*rs.count_executions))*8,2) as total_logical_io_reads,
    ROUND(CONVERT(float, SUM(rs.avg_logical_io_writes*rs.count_executions))*8,2) as total_logical_io_writes,
    ROUND(CONVERT(float, SUM(rs.avg_physical_io_reads*rs.count_executions))*8,2) as total_physical_io_reads,
    ROUND(CONVERT(float, SUM(rs.avg_clr_time*rs.count_executions))*0.001,2) as total_clr_time,
    ROUND(CONVERT(float, SUM(rs.avg_dop*rs.count_executions))*1,0) as total_dop,
    ROUND(CONVERT(float, SUM(rs.avg_query_max_used_memory*rs.count_executions))*8,2) as total_query_max_used_memory,
    ROUND(CONVERT(float, SUM(rs.avg_rowcount*rs.count_executions))*1,0) as total_rowcount,
    DATEADD(d, ((DATEDIFF(d, 0, rs.last_execution_time))),0 ) as bucket_start,
    DATEADD(d, (1 + (DATEDIFF(d, 0, rs.last_execution_time))), 0) as bucket_end
FROM sys.query_store_runtime_stats rs
WHERE NOT (rs.first_execution_time > @interval_end_time OR rs.last_execution_time < @interval_start_time)
GROUP BY DATEDIFF(d, 0, rs.last_execution_time)
)
SELECT
    total_count_executions,
    total_duration,
    total_cpu_time,
    total_logical_io_reads,
    total_logical_io_writes,
    total_physical_io_reads,
    total_clr_time,
    total_dop,
    total_query_max_used_memory,
    total_rowcount,
    SWITCHOFFSET(bucket_start, DATEPART(tz, @interval_start_time)) , SWITCHOFFSET(bucket_end, DATEPART(tz, @interval_start_time))
FROM
(
SELECT *, ROW_NUMBER() OVER (PARTITION BY bucket_start ORDER BY bucket_start, total_duration DESC) AS RowNumber
FROM UnionAll
) as UnionAllResults
WHERE UnionAllResults.RowNumber = 1
OPTION (MAXRECURSION 0)',N'@interval_start_time datetimeoffset(7),@interval_end_time datetimeoffset(7)',@interval_start_time='2018-02-19 10:41:32.4646188 -06:00',@interval_end_time='2018-03-19 11:41:32.4646188 -05:00'

The results look like:
╔════════════════════════╦════════════════╦════════════════╦════════════════════════╦═════════════════════════╦═════════════════════════╦════════════════╦═══════════╦═════════════════════════════╦════════════════╦════════════════════════════════╦════════════════════════════════╗
║ total_count_executions ║ total_duration ║ total_cpu_time ║ total_logical_io_reads ║ total_logical_io_writes ║ total_physical_io_reads ║ total_clr_time ║ total_dop ║ total_query_max_used_memory ║ total_rowcount ║        (No column name)        ║        (No column name)        ║
╠════════════════════════╬════════════════╬════════════════╬════════════════════════╬═════════════════════════╬═════════════════════════╬════════════════╬═══════════╬═════════════════════════════╬════════════════╬════════════════════════════════╬════════════════════════════════╣
║                      2 ║           3.25 ║           3.25 ║                      0 ║                       0 ║                       0 ║              0 ║         2 ║                           0 ║              1 ║ 2018-03-18 18:00:00.000 -06:00 ║ 2018-03-19 18:00:00.000 -06:00 ║
╚════════════════════════╩════════════════╩════════════════╩════════════════════════╩═════════════════════════╩═════════════════════════╩════════════════╩═══════════╩═════════════════════════════╩════════════════╩════════════════════════════════╩════════════════════════════════╝

I saw that using a T-SQL statement trace against the server while simultaneous opening the GUI for "Overall Resource Consumption" on my local SQL Server 2016 instance.
I re-factored that above query down a bit, to:
DECLARE @interval_start_time datetimeoffset(7);
DECLARE @interval_end_time datetimeoffset(7);
SET @interval_start_time = '2018-02-19 10:41:32.4646188 -06:00';
SET @interval_end_time = '2018-03-19 11:41:32.4646188 -05:00';

SELECT
      total_count_executions = CONVERT(float, SUM(rs.count_executions))
    , total_duration = ROUND(CONVERT(float, SUM(rs.avg_duration*rs.count_executions))*0.001,2)
    , total_cpu_time = ROUND(CONVERT(float, SUM(rs.avg_cpu_time*rs.count_executions))*0.001,2)
    , total_logical_io_reads = ROUND(CONVERT(float, SUM(rs.avg_logical_io_reads*rs.count_executions))*8,2)
    , total_logical_io_writes = ROUND(CONVERT(float, SUM(rs.avg_logical_io_writes*rs.count_executions))*8,2)
    , total_physical_io_reads = ROUND(CONVERT(float, SUM(rs.avg_physical_io_reads*rs.count_executions))*8,2)
    , total_clr_time = ROUND(CONVERT(float, SUM(rs.avg_clr_time*rs.count_executions))*0.001,2)
    , total_dop = ROUND(CONVERT(float, SUM(rs.avg_dop*rs.count_executions))*1,0)
    , total_query_max_used_memory = ROUND(CONVERT(float, SUM(rs.avg_query_max_used_memory*rs.count_executions))*8,2)
    , total_rowcount = ROUND(CONVERT(float, SUM(rs.avg_rowcount*rs.count_executions))*1,0)
    , bucket_start = DATEADD(d, ((DATEDIFF(DAY, 0, rs.last_execution_time))),0 )
    , bucket_end = DATEADD(d, (1 + (DATEDIFF(DAY, 0, rs.last_execution_time))), 0)
FROM sys.query_store_runtime_stats rs
WHERE NOT (rs.first_execution_time > @interval_end_time OR rs.last_execution_time < @interval_start_time)
GROUP BY DATEDIFF(DAY, 0, rs.last_execution_time)
ORDER BY DATEDIFF(DAY, 0, rs.last_execution_time);

That returns a row for each day between the start end end dates provided.


text:
Q: Hyperledger Fabric BYFN - Unable to find directory listed in docker-compose-base.yaml I am looking at docker-compose-base.yaml line 27:
volumes:
    - ../channel-artifacts/genesis.block:/var/hyperledger/orderer/orderer.genesis.block
    - ../crypto-config/ordererOrganizations/example.com/orderers/orderer.example.com/msp:/var/hyperledger/orderer/msp
    - ../crypto-config/ordererOrganizations/example.com/orderers/orderer.example.com/tls/:/var/hyperledger/orderer/tls
    - orderer.example.com:/var/hyperledger/production/orderer

I can find below 3 directories on my filesystem
../channel-artifacts/genesis.block
../crypto-config/ordererOrganizations/example.com/orderers/orderer.example.com/msp
../crypto-config/ordererOrganizations/example.com/orderers/orderer.example.com/tls/

but I cannot find a directory named orderer.example.com. I think this is not meant to be a directory but related to the
container_name: orderer.example.com

in some way. Could anyone explain the meaning of the last mapping:
- orderer.example.com:/var/hyperledger/production/orderer

it does not look like a local <-> docker directory mapping. Then what is it?

A: Before starting the container it's normal that the orderer.example.com folder is not create, since it will be created when the container starts.
Mount the directory /var/hyperledger/production/orderer between the host and the container can be useful if you orderer is run is solo mode.
Indeed, if your container crash (for example your server restart) you can keep track of the blocks that the orderer has build. It's can be used for restart the blockchain network easier (or move the orderer in other server) .

A: TL;DR: The first three
- ../channel-artifacts/genesis.block:/var/hyperledger/orderer/orderer.genesis.block
    - ../crypto-config/ordererOrganizations/example.com/orderers/orderer.example.com/msp:/var/hyperledger/orderer/msp
    - ../crypto-config/ordererOrganizations/example.com/orderers/orderer.example.com/tls/:/var/hyperledger/orderer/tls

are examples of bind mounts. The last one
- orderer.example.com:/var/hyperledger/production/orderer

is a volume. Its confusing because bind mounts can be created using the volume syntax and hence also get referred to as volumes in documentation.

This is not related to
container_name: orderer.example.com

docker-compose-base.yaml is a base file that is used e.g., by docker-compose-e2e-template.yaml. In that file one can see volumes being defined:
volumes:
  orderer.example.com:
  peer0.org1.example.com:
  peer1.org1.example.com:
  peer0.org2.example.com:
  peer1.org2.example.com:

these volumes behave the same way as if one had created them using the docker volume create command. see https://docs.docker.com/engine/reference/commandline/volume_create/ to understand what that command does. It is a way to create persistent storage that 1. does not get deleted when the docker containers stop and exit and, 2. that can be used to share data amongst containers.
To see list of all volumes created by docker on the machine, run:
docker volume ls

To inspect a volume, run (to give an example):
$ docker volume inspect net_orderer.example.com
[
    {
        "CreatedAt": "2018-11-06T22:10:42Z",
        "Driver": "local",
        "Labels": null,
        "Mountpoint": "/var/lib/docker/volumes/net_orderer.example.com/_data",
        "Name": "net_orderer.example.com",
        "Options": null,
        "Scope": "local"
    }
]

re: the original question:

Unable to find directory listed in docker-compose-base.yaml

You will not be able to find this directory. E.g., if you try listing the mountpoint above:
$ ls /var/lib/docker/volumes/net_orderer.example.com/_data
ls: /var/lib/docker/volumes/net_orderer.example.com/_data: No such file or directory

docker volumes are not created as regular directories on the host. The steps to "get" to a volume are quite complex in fact. see https://forums.docker.com/t/host-path-of-volume/12277/9 for details.


text:
Q: Piwik Events API - How to Query Single Action I setup a custom trackEvent using this code:
<a href="#" onclick="javascript:_paq.push(['trackEvent', 'Like', '<?php echo $id ?>']);">Like Me

So "Like" is the category, and "$id" is the action, which will be different depending on which page is being viewed.
This works fine and successfully get the custom event into my Piwik dashboard under the "Like" category. For example, I clicked on this link on 3 different pages so I have 10, 11, and 12 as actions in my dashboard.
To query them, I'm using this URL in a HTTP request:
http://www.MYPIWIKURL.com/?module=API&method=Events.getAction&idSite=1&period=day&date=today&format=JSON&token_auth=MYAUTHTOKEN

This returns an array with all 3 of the actions listed as nested arrays. I'm wondering, however, how I can return only the array with the action I want to view? For example, action 10?
I tried adding "e_a=10", "action_name=10", and "segment=actions==10" to the URL, but they aren't recognized.
Could someone point me in the right direction for querying a single action within a category? Seems like I'm almost there!
Also--I do know that I could loop through the array and get the action I want, but eventually there will be thousands of actions, so that wouldn't be very efficient I don't think.
Thanks for any help!

A: An actually better solution here is to use the API parameter &label=10 which will return the row where the label is 10. This parameter works in all APIs and lets you easily filter and keep only one row. Learn more: http://piwik.org/docs/analytics-api/reference
Using Segments is not recommended because it will trigger archiving of data for this segment, because segment data is not pre-processed. However using the &label= parameter will be very fast.

A: I was using the wrong segment identifier. For anyone who may have this same issue, the segment to use is:
segment=eventAction==10

So the full URL would be:
http://www.MYPIWIKURL.com/?module=API&method=Events.getAction&segment=eventAction==10&idSite=1&period=day&date=today&format=JSON&token_auth=MYAUTHTOKEN


text:
Q: How to use a variable name of reserved words in Python I've encountered a problem when I'm using peewee in python to fetch a column's data named 'class'. But 'class' is a reserved word, when I run the code it always stopped with 'SyntaxError: invalid syntax'.
Here is the code I'm using which works if I do not include the Class.class column.
query = (
    Student.select(
        Student.id,
        Student.name,
        Student.school_id,
        School.name,
        Student.class_id,
        Class.class,
        Class.grade,
    )
    .join(Class, join_type=pw.JOIN.INNER, on=(Class.id == Student.class_id))
    .join(School, join_type=pw.JOIN.INNER, on=(School.id == Student.school_id))
    .where(Student.id == id)
)

And the definition of Class.class which also causes the same error:
class = CharField(max_length=45)

It should give me a query without error. So my question is how do I use the variables of reserved name in python. Thanks!

A: In general, you can use getattr to access names that are reserved keywords; for the class attribute:
query = (
    Student.select(
        Student.id,
        Student.name,
        Student.school_id,
        School.name,
        Student.class_id,
        getattr(Class, 'class'),  # equivalent to `Class.class` (if that were allowed)
        Class.grade,
    )
    .join(Class, join_type=pw.JOIN.INNER, on=(Class.id == Student.class_id))
    .join(School, join_type=pw.JOIN.INNER, on=(School.id == Student.school_id))
    .where(Student.id == id)
)

However, you probably want to rename the attribute in your Peewee table definition to something that's not a reserved word and use column_name='class' to have it still refer to a class attribute in the physical table:
klass = CharField(max_length=45, column_name='class')
# or maybe, if you prefer:
class_ = CharField(max_length=45, column_name='class')

A: You should name the class attribute class_ (or something non reserved) and then use the column_name parameter for a Peewee field to set it to "class."

A: It is not possible to use a reserved word in this way but it is common to add an underscore to avoid a clash such as class_ so your code would use Class.class_ or even Class_.class_


text:
Q: Disable/Enable 3G for ios app In my app I am doing live streaming in which user have a switch to on/off 3G. If user don't want to stream via 3G he could off 3G. My code is:
-(void)InternetCheck {

NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];

Reachability *reachability = [Reachability reachabilityForInternetConnection];
[reachability startNotifier];

NetworkStatus status = [reachability currentReachabilityStatus];

if(status == NotReachable)
{
    NSLog(@"No Internet");
}
else if (status == ReachableViaWiFi)
{
    //WiFi
    [self play];
}
else if (status == ReachableViaWWAN)
{
    //3G
    if([[defaults valueForKey:@"3GPermission"] isEqualToString:@"3GAllowed"])
    {
        [self play];
    }
    else
    {
        NSLog(@"No Internet");
    }
}

}

But if user turn off 3G and if there is no wifi, user could stream. How could i do this. Please help me. Thanks


text:
Q: The structure and meaning of "How far along have you gotten?" I was wondering what the structure and meaning of "How far along have you gotten?" in the following sentences are:

You were looking at variations in climate in the Grant City area,
  right? How far along have you gotten?

I searched the dictionary, but I cannot find an appropriate answer.

A: Apparently a task has been assigned that involves the climate in a particular area.
When someone asks "How far along have you gotten?", they are imagining that the task is like a road. When the task was first assigned, that represents the beginning of the road. The completion of the task is the end of that road. As you do the work to complete the task, you are traveling along that imaginary road.
So the question means, "How far along the (imaginary) road have you traveled?" In other words, "How much work has been completed?"


text:
Q: DBPedia SparQL select Players of Team i'm trying to select any active players of an soccer Team.
for example i have selected the football team for Austria
SELECT * WHERE
{
    ?club a dbo:SoccerClub ;
          dbo:ground ?grounds .
    ?grounds  dbo:location ?country.
    FILTER(?country = <http://dbpedia.org/resource/Austria>)
}

The
result of the query
 seems very well
Now I'm trying to get all active players for one soccer team/club.
for example:http://dbpedia.org/resource/FC_Red_Bull_Salzburg
so I have tried the following query
PREFIX dbpedia: <http://dbpedia.org/property/>
SELECT *
WHERE {
?player dbpedia:currentclub ?teamName.
OPTIONAL {?teamName dbpedia:ground ?ground}.
OPTIONAL {?grounds  dbo:location ?country}.
OPTIONAL {?player dbpedia:cityofbirth ?city}.
OPTIONAL {?player dbpedia:dateOfBirth ?dob}.
Filter(?country = <http://dbpedia.org/resource/Austria>)
Filter(?teamName = <http://dbpedia.org/resource/FC_Red_Bull_Salzburg>)
}

but unfortuality the query returns no results.
I would be grateful for any help.


text:
Q: I am stuck with this mysql inner join query select t1.TITLE,PJT_ID, group_concat(t2.count) as COUNT, group_concat(t2.CREATED_BY) USERS,t2.task_id,group_concat(dc_users.PHOTO)as PHOTO from dc_tasks t1 inner join (SELECT dc_remarks.`CREATED_BY`,dc_sprints.PJT_ID , TSK_ID AS task_id, count( dc_remarks.`CREATED_BY` ) AS count FROM dc_remarks inner join dc_tasks on dc_remarks.`TSK_ID` = dc_tasks.ID inner join dc_sprints on dc_sprints.ID=dc_tasks.SPT_ID WHERE DATE( `CREATED_ON` ) = DATE('2015-05-22') AND dc_sprints.PJT_ID = GROUP BY `CREATED_BY` , `TSK_ID` ORDER BY `TSK_ID`) t2 on t1.ID = t2.task_id inner join dc_users on dc_users.FIRST_NAME = t2.CREATED_BY GROUP BY t2.task_id

A: Your error is here:
dc_sprints.PJT_ID = GROUP BY `CREATED_BY`.

Complete the where condition before grouping results
Your formatted sql looks like this:
select
   t1.TITLE,PJT_ID, group_concat(t2.count) as COUNT,
   group_concat(t2.CREATED_BY)
   USERS,t2.task_id,group_concat(dc_users.PHOTO)as PHOTO
from
   dc_tasks t1
inner join (
       SELECT
           dc_remarks.`CREATED_BY`,dc_sprints.PJT_ID ,
           TSK_ID AS task_id, count( dc_remarks.`CREATED_BY` ) AS count
       FROM
           dc_remarks
       inner join dc_tasks on dc_remarks.`TSK_ID` = dc_tasks.ID
       inner join dc_sprints on dc_sprints.ID=dc_tasks.SPT_ID
       WHERE
            DATE( `CREATED_ON` ) = DATE('2015-05-22') AND
           dc_sprints.PJT_ID =
       GROUP BY `CREATED_BY` , `TSK_ID` ORDER BY `TSK_ID`
  ) t2 on t1.ID = t2.task_id
  inner join dc_users on dc_users.FIRST_NAME = t2.CREATED_BY
  GROUP BY t2.task_id

A: select
   t1.TITLE,PJT_ID, group_concat(t2.count) as COUNT,
   group_concat(t2.CREATED_BY)
   USERS,t2.task_id,group_concat(dc_users.PHOTO)as PHOTO
from
   dc_tasks t1
inner join (
       SELECT
           dc_remarks.`CREATED_BY`,dc_sprints.PJT_ID ,
           TSK_ID AS task_id, count( dc_remarks.`CREATED_BY` ) AS count
       FROM
           dc_remarks
       inner join dc_tasks on dc_remarks.`TSK_ID` = dc_tasks.ID
       inner join dc_sprints on dc_sprints.ID=dc_tasks.SPT_ID
       WHERE
            DATE( `CREATED_ON` ) = DATE('2015-05-22') AND
           dc_sprints.PJT_ID = dc_tasks.project_id
       GROUP BY `CREATED_BY` , `TSK_ID` ORDER BY `TSK_ID`
  ) t2 on t1.ID = t2.task_id
  inner join dc_users on dc_users.FIRST_NAME = t2.CREATED_BY
  GROUP BY t2.task_id


text:
Q: Showing a counter-example for a 4 sets that share a subset relation What is the easiest and correct way of finding a counter-example of this kind of questions:

Do these relation holds for every sets $A,B,C,D$?
1) $ (A \setminus C) \times (B \setminus D)) = (A \times B)\setminus(C
 \times D) $
2) $ (C \times D) \setminus (A \times (D \setminus B)) \subset (A
 \times D)  \cup  (C \times (D \setminus B)) $

Thanks in advance.

A: Here's my answer to the actual question you asked, not the specific set theory questions.
For me the "easiest and correct way" to decide whether such a statement is true is to play with small examples. That often leads either to a counterexample (if the assertion is false) or to an idea of how to prove it (if it's true).


text:
Q: How to manage the registration quota in Firebase authentication using Firebase Functions? I am creating a user registration process through firebase functions.
I have read in the firebase console the following:

To protect your project from any inappropriate use, we limit the number of records (both anonymous and those that use email and password) that can be made in your application from the same IP address. In this section you can request and schedule temporary changes for this fee.

I understand that the ip registered by the firebase authentication service is the ip of the server where the function is executed.
In this case, how is the registration quota controlled to prevent malicious use? Is there any way to do this correctly?

A: firebaser here
The quota described in that section mostly applies to calls coming from the client-side SDKs, like those from iOS and Android devices, and web pages. Since anyone with your configuration data (which is anyone who uses your app) can call these APIs, the quota protects against abuse from malicious users.
In Cloud Functions you're using the Admin SDK to create users, and the Admin SDK can only be used by someone who has the credentials for your project. For that reason, the code in Cloud Functions runs at a higher trust level and is not subject to these quota.
If you ever hit a Authentication quota issue in Cloud Functions code (or other code in a trusted environment that uses the Admin SDK), reach out to Firebase support for personalized help in troubleshooting.


text:
Q: Sum of Top N in SQL I have a SALES table with Person, Date and Qty:
Person   Date      Qty
Jim     2016-08-01  1
Jim     2016-08-02  3
Jim     2016-08-03  2
Sheila  2016-08-01  1
Sheila  2016-08-02  1
Sheila  2016-08-03  1
Bob     2016-08-03  6
Bob     2016-08-02  2
Bob     2016-08-01  5

I can rank the top 2 by Date with the following code:
/****** Top 2 Salespersons  ******/
SELECT *
FROM(
    SELECT * ,
    ROW_NUMBER() OVER( PARTITION BY [Date]
    ORDER BY Qty DESC) N'Rank'
    FROM [Coinmarketcap].[dbo].[sales]
    GROUP BY [Date], Person, Qty
    ) AS NewTable
WHERE NewTable.Rank  < 3

Person     Date    Qty Rank
Bob     2016-08-01  5   1
Jim     2016-08-01  1   2
Jim     2016-08-02  3   1
Bob     2016-08-02  2   2
Bob     2016-08-03  6   1
Jim     2016-08-03  2   2

My two questions are:
1) How can I just see the total qty for the top 2 for each date, such as:
Date       Total Qty
2016-08-01    6
2016-08-02    5
2016-08-03    8

2) How can I get the total Qty each day for different ranking groups, such as:
Date         Ranking Group    Total Qty
2018-08-01     1-2               6
2018-08-01     3-4               1
2018-08-01     5-6               0
2018-08-02     1-2               5
2018-08-02     3-4               1
2018-08-02     5-6               0
2018-08-03     1-2               8
2018-08-03     3-4               1
2018-08-03     5-6               0

A: First:
SELECT NewTable.Date, Sum(NewTable.Qty)
FROM(
    SELECT * ,
    ROW_NUMBER() OVER( PARTITION BY [Date]
    ORDER BY Qty DESC) N'Rank'
    FROM [Coinmarketcap].[dbo].[sales]
    GROUP BY [Date], Person, Qty
    ) AS NewTable
WHERE NewTable.Rank  < 3
group by NewTable.Date

Second try this:
SELECT NewTable.Date,
       Trunc((NewTable.Rank - 1) / 2) * 2 + 1, -- lower rank
       Trunc((NewTable.Rank - 1) / 2) * 2 + 2, -- upper rank
       Sum(NewTable.Qty)
FROM(
    SELECT * ,
    ROW_NUMBER() OVER( PARTITION BY [Date]
    ORDER BY Qty DESC) N'Rank'
    FROM [Coinmarketcap].[dbo].[sales]
    GROUP BY [Date], Person, Qty
    ) AS NewTable
group by NewTable.Date,
         Trunc((NewTable.Rank - 1) / 2) * 2 + 1,
         Trunc((NewTable.Rank - 1) / 2) * 2 + 2


text:
Q: Can I merge a node server with the polymer init starter-kit application? I have my fledgling polymer application running.  I would like to load and save a file.  I would like to do that by using the ajax element.  But what happens on the server side?
I have made nodejs express applications before.  I could make a separate server for the client to talk to.  But there are at least two other options:

*

*Take the front-end material supplied by the polymer start-kit and put it in the /public directory of an express application.

*Put express routes in my polymer starter-kit application.
I am inclined to bring Express into the existing start-kit application.  But maybe someone else has already tried this, and can tell me what I will run into?
I looked at the starter-kit code a little bit.  Apparently, it uses the spdy package and not the http package, but I can work with that.  That's as far as I have gotten.  Any advice?
Regards, Rick

A: I talked to the guys on the Polymer slack channel.  Thanks, milesje.  polymer serve is just supposed to be a light server to serve static files.  If you want to do something more substantial, you should create your own server (nodejs or something else) and put your Polymer files in the public/ directory.
Hope this saves someone else some time.


text:
Q: Missing operand error when filtering data I get this error when I try to filter data: Server Error in '/' Application. Syntax error: Missing operand after ''%1%'' operator.
This is the code that produces the problem:
protected void Page_Load(object sender, EventArgs e)
{
    using (con = new OleDbConnection(@"PROVIDER=Microsoft.ACE.OLEDB.12.0;" + @"DATA SOURCE= C:\Users\ASAD\Docements\Student.accdb")) ;
}
protected void Button1_Click(object sender, EventArgs e)
{
    string FilterExpression = string.Concat(DropDownList1.SelectedValue, "LIKE '%{0}%'");
    SqlDataSource1.FilterParameters.Clear();
    SqlDataSource1.FilterParameters.Add(new ControlParameter( DropDownList1.SelectedValue, "TextBox1", "Text" ));
    SqlDataSource1.FilterExpression = FilterExpression;
}

A: I think you're just missing a space before the keyword LIKE:
protected void Button1_Click(object sender, EventArgs e)
{
    string FilterExpression = string.Concat(DropDownList1.SelectedValue, " LIKE '%{0}%'");
    SqlDataSource1.FilterParameters.Clear();
    SqlDataSource1.FilterParameters.Add(new ControlParameter( DropDownList1.SelectedValue, "TextBox1", "Text" ));
    SqlDataSource1.FilterExpression = FilterExpression;
}

If your selected value is "BOB", your expression will result in BOBLIKE '%1%' instead of BOB LIKE '%1%'.
Also, depending on the content of your DropDownList and the context, you may need to quote that value.


text:
Q: How to show partial content of a page on another in wordpress? I have a page called Dashboard and would like to show the contents of say page A and B on the Dashboard page. I can achieve this with the following code but I only want to show partial content of A and B like snippets. How can I show this in exactly the same styling as it appears on page A and B ?
function show_post($path) {
 $post = get_page_by_path($path);
 $content = apply_filters('the_content', $post->post_content);
 echo $content;
}

<?php show_post('pageA');  // Shows the content of the "PageA" page. ?>
<?php show_post('pageB');  // Shows the content of the "PageB" page. ?>

Page A shows the content with this code:

        <?php
        while ( $loop->have_posts() ) : $loop->the_post();
        ?>
        <li class="todo" id="<?php echo get_the_ID();?>" itemage="<?php echo get_post_meta(get_the_ID(),'_todotime',true)?>"><a href="javascript:;"
        <?php if($all_meta_for_user[get_the_ID()][0]){
        ?>
        class="strike"
        <?php
         }
        ?>
        >
        <?php if($all_meta_for_user[get_the_ID()][0]){?>

            <?php }else{?>

        <?php }?>

<?php the_title(); ?>

        <?php
        endwhile;
        ?>

Thanks in advance

A: you can easily do this by post create 2 posts suppose A and B. it will generate id's like 20,22 ... and use this code in your pages for page A:
<?php  $cquery = new WP_Query('cat=20'); $i=1; ?>
      <?php if($cquery->have_posts()): while($cquery->have_posts()):  $cquery->the_post();
      <?php the_post_thumbnail();   ?>
      <?php the_content(); ?>
      <?php $i++; endwhile; endif; endif;  ?>

and similarly for post B with having id 22.

A: I am not extremest php coder. But i am trying it.
Here is the code you can do it by with php explode .
In your page A or B just put an identifier for explode.
Like this :
Here is the first of the contents of the page.

From this part you want to show something

Here is the rest of the contents

And then your function is like :
function show_post($path) {
 $post = get_page_by_path($path);
 $content = apply_filters('the_content', $post->post_content);
 $explode=explode('',$content);
 $explode=explode('',$explode[1]);
 echo $explode[0];
}


text:
Q: Merge two dictionaries while sharing the keys I'm trying to build a small program that, given a dictionary containing names and addresses and another dictionary that contains names and phone numbers, the output should merge them both (and not overwrite one another). The final output dictionary should contain name, address (if available) and phone (if available).
Here's an example:
addr = {'George': 'via Wagner, 23', 'White': 'Piazza Bologna, 1',
    'L. Red': 'via A. Einstein, 12', 'Pete': 'via Pio'}
phone = {'Mark': '347 8987989', 'George': '06 89786765',
     'Mauro B.': '3489878675', 'Pete': '07897878', 'L. Red': '09877887'}

And the final dictionary:
addr_phone(addr, phone) -->
{'George':    {'address': 'via Wagner, 23'},
 'Mark':      {'phone': '347 8987989'},
 'George':    {'phone': '06 89786765'},
 'L. Red':   {'phone': '09877887', 'address': 'via A. Einstein, 12'},
 'Pete':       {'phone': '07897878', 'address': 'via Pio'},
 'Mauro B.':   {'phone': '3489878675'},
 'White': {'address': 'Piazza Bologna, 1'}}

I tried writing this:
def addr_phone(addr, phone):
    d3={}
    d3.update(addr)
    d3.update(phone)
    for k,v in phone.items():
        if k not in addr:
            d3[k]=v
    return d3

But I get multiple instances of the same name, and it's not what I want.
Thanks for your help.

A: Use a defaultdict:
from collections import defaultdict

out = defaultdict(dict)
for name, phonenumber in phone.iteritems():
    out[name]['phone'] = phonenumber
for name, address in addr.iteritems():
    out[name]['address'] = address

For python 3 just replace .iteritems() with .items():
out = defaultdict(dict)
for name, phonenumber in phone.items():
    out[name]['phone'] = phonenumber
for name, address in addr.items():
    out[name]['address'] = address

You do need to loop over both input dictionaries, because you are moving the values to a new dictionary per name.


text:
Q: Troubles with regexp in R: Match word surrounded by whitespace or start/end of string I want to count the number of words from a dictionary that appear in a string if it is surrounded by whitespace or it is at the start or end of the string.
I'm using this answer like this:
library(stringi)

testStr <- c("dutch dutch brown", "brown ", "AAdutch", "dutchAA", "AAbrown",
             "brownAA", "hello")
stri_count_regex(testStr, "(^|\\s+)dutch|brown(\\s+|$)")

Which returns 3 1 0 1 1 0 0, but I'm expecting 3 1 0 0 0 0 0. So the problem is that it also counts "dutchAA" and "AAbrown" which I don't want.
I'm a bit puzzled about this, as this regular expression works fine when I run it on RegExr.

A: Try using the following regex :
(?:\b|\s+)(?:dutch|brown)(?:\s+|\b)

regex demo
r
library(stringi)

testStr <- c("dutch dutch brown", "brown ", "AAdutch", "dutchAA", "AAbrown",
             "brownAA", "hello")
stri_count_regex(testStr, "(?:\\b|\\s+)(?:dutch|brown)(?:\\s+|\\b)")  # 3 1 0 0 0 0 0


text:
Q: Problema con Listas enlazadas ordenadas Tengo un problema al momento de insertar los datos de manera ordenada, tengo entendido que si inserto un 5 al inicio y posteriormente un 3 y después un 10, la lista quedaría 3->5->10, sé muy bien que en alguna parte del método Insertar algo hice mal, una declaración equivocada o error de lógica, pero no lo logro ver aun. así que necesito ayuda para poder resolver el problema que tengo.
using namespace std;
#include <iostream>
#include <conio.h>

class Nodo{
    int dato;
    Nodo *sig;
    Nodo *inicio;
    public:
        Nodo(){
            dato=0;
            inicio=sig= NULL;
        }
        void inserta(){
            Nodo *nuevo= new Nodo;
            Nodo *ind= inicio;
            nuevo->Lee();
            if(inicio==NULL)
                inicio=nuevo;
            else if(dato<=dato){ //si el nodo es menor
                nuevo->sig=inicio;
                inicio= nuevo;
            }
            else if(dato==dato){ //si el nodo es igual
                int num;
                num=dato;
                while (ind && ind ->dato != num)
                    ind= ind->sig;
                if(ind == NULL){
                    cout<<"\nNo se encontro el dato\n";
                }
                else{
                    nuevo->sig=ind->sig;
                    ind->sig=nuevo;
                    cout<<"\nNodo insertado correctamente por el medio\n";
                }
            }
            else if(dato>=dato){ //Si el nodo es mayor
                while (ind->sig != NULL)
                    ind= ind->sig;
                ind->sig=nuevo;
                cout<<"\nNodo insertado al final";
            }
        }
        void Muestra(){
            if(inicio==NULL)
                cout<<"\nLista vacia\n";
            else{
                Nodo *ind= inicio;
                cout<<"\nDatos de la lista\n";
                while (ind != NULL){
                    cout<<ind->dato<<'-> ';
                    ind= ind-> sig;
                }
            }
        }
        void Lee(){
            cout<<"\nIngresa el dato: ";
            fflush(stdin);
            cin>>dato;
        }
        ~Nodo(){
            Nodo *ind;
            while (inicio){
                ind= inicio;
                inicio= inicio->sig;
                delete ind;
            }
        }
};

El detalle: cuando acaba el programa estan mal ordenadas y siento que algo estoy haciendo mal desde el los IF's

A: El diseño de tu "lista" está conceptualmente mal:

*

*Los nodos de las listas enlazadas tienen punteros a los valores anteriores y siguientes, pero tu nodo tiene un puntero a inicio y siguiente. No tiene sentido que todos los nodos apunten al inicio de la lista, seguramente querías que los punteros fuesen anterior y siguiente.

*Los nodos son objetos pasivos que almacenan datos y se enlazan entre si, les has dotado de funciones que no les corresponden como lectura e impresión de datos.

*El destructor del nodo es la receta del desastre. Cuando llamas a delete invocas el destructor del nodo, por lo que en cada borrado haces una eliminación recursiva de nodos y acabas borrando (intentándolo más bien) nodos más de una vez.

Necesitas los siguientes cambios en tu código:

*

*Crea un objeto Lista que gestione los nodos.

*Los nodos deberán ser un tipo interno de la Lista.

*La Lista se encargará de la inserción y borrado de datos, no los nodos.

A: En la operación inserta estás comparando la varaible dato consigo misma así que siempre se cumplirá la primera condición:
else if(dato<=dato){ //si el nodo es menor


text:
Q: Difference between e.Handeld = true and unsubscribing from event? I have an event handler that for some reason (I don't understand) get called twice, I thought that setting e.Handled = true will solve it but it doesn't, finally I unsubscribed from the event inside the handler, and it works:
((FabTabItem)sender).TabClosing -= oTab_TabClosing;

So I have these questions:

*

*What is the difference between the both approches, Don't they stop handling the event?

*Is it OK to unsubscribe from the event inside its handler since its natural to say "stop listening to the event after it's been handled"? (I don't see this a lot)

A: From the following MSDN page on the KeyPressEventArgs.Handled Property:

If the event is not handled, it will be sent to the operating system for default processing.

So setting it to true means that any further processing of the event will not happen for the rest of that call to the event depending on how the other events handle the Handled property. As @Enigmativity put it in the comments to the OP:

When you have several handlers for the one event they are called in series. If one of the handlers thinks that it has "handled" the event and no further handlers need to do anything it can set e.Handled = true. It is up to the subsequent handlers to honour this flag and not do any processing - but they are still called. Also this doesn't change the handling for when the next time the event is raised - all of the handlers get called again.

By unsubscribing from the event the rest of the actions in the event still occur, in the case of the above mentioned event it still goes through to the operating system.
The two scenarios you described are not exactly the same.
Unsubscribing from the event inside the handler itself is fine, all it does is remove the call to that handler next time the event is raised.
With that said if you are doing this because the event is being called more times than it should be you should probably track down where the event is being subscribed too. It is likely you have accidentally subscribed the same handler twice and that is the proper fix rather than hacking around it by unsubscribing from the event.

A:
What is the difference between the both approaches, Don't they sop handling the event?

e.Handled = true; indicates that the event handler has already processed the event and dealt with it, so it doesn't need to be processed any further. In other words, please don't take any further action.
but the second will Remove Event and Don,t happen next time

Is it OK to unsubscribe from the event inside its handler since its natural to say "stop listening to the event after it's been handled"? (I don't see this a lot)

its depend to your Roll if you want not happen after a If use handle but if you want never happen after if use second
and remove event


text:
Q: Which should I choose?
The package can be torn......by pulling on the red tab located at the top left corner of the box.

A.open
B.opening
C.to open
D.opened
and please explain your option.

A:
The package can be torn open...

Open is an adjective complement to the verb tear: it designates the state which the action of the verb effects in the package. Tearing the package causes it to be open.
In the 'canonical' active form of this sentence the package would be the object, so open is often called an 'object complement' or 'object-oriented complement':

He tore [objthe package] [compopen].

But your example is cast in the passive voice, and the canonical-form 'object' is cast as subject, so the term 'object complement' is misleading. Let's call it a 'Patient complement' instead, with 'Patient' designating the object which is acted upon.
With many verbs a Patient complement is obligatory—causative make, for instance, or verbs of caused motion. Depending on the verb the complement may be an adjective phrase, a preposition phrase, or a noun phrase:

He makes [objJanet] [comphappy].
  She put [objthe teacup] [compon the shelf].
  The company named [objHenderson] [compCEO].

Many other verbs do not require a Patient complement but do take one freely—tear in your example, for instance. Such optional complements are often called 'secondary complements' (but the scope of that term varies with different authorities).
Patient complements are of course only possible with transitive verbs—verbs which take a Patient as an object in canonical-form sentences. Intransitive verbs often take Agent complements, complements which designate a state present or effected in the subject Agent:

He has risen [compvery high].
  John flew [compto New York] last night.
  Ancient Greek athletes competed [compnaked].

A: Torn open is correct. The reason that A is the correct form is that open functions as an adverb modifying tear in this case rather than a verb, so forms of the verb do not apply.
Combinations such as this are called phrasal verbs. Phrasal verbs combine a verb with an adverb or preposition (sometimes more than one e.g. add up to) to form an idiomatic meaning.
Other phrasal verbs using tear are tear up, tear down, tear apart, tear off and tear out, among others. For a list of phrasal verbs and their meanings, see this.


text:
Q: Get string from tkinter text object without line break I'm trying to create a basic tkinter app where I prompt the user for a query and it outputs to to an excel file but when I try to get the value of the userinput I always get a linebreak. How do I avoid this?
...
Textinput = Text(app,width=68,height=5,yscrollcommand=sb2.set)
Textinput.grid(row=3,column=0,columnspan=colSpan,sticky=N)
compareButton = Button(text="Output to XLSX",command = lambda: exportToExcel(Textinput.get("1.0","end")))
...

Should I be using something other than "end" for the get command?
I have a workaround, but would prefer to solve the issue at its source.
Thank you!

A: Add .strip() at the end of the get method:
Button(text="Output to XLSX",command = lambda: pressing(Textinput.get("1.0","end").strip())).grid()

Or as @jasonharper suggested, use Entry:
Textinput = Entry(app,width=68,height=5)
Textinput.grid(row=3,column=0,columnspan=1,sticky=N)


text:
Q: Convert a 64bit integer to an array of 7bit-characters Say I have a function vector<unsigned char> byteVector(long long UID), returning a byte presentation of the UID, a 64bit integer, as a vector. This vector is later on used to write this data to a file.
Now, because I decided I want to read that file with Python, I have to comply to the utf-8 standard, which means I can only use the first 7bits of each char. If the highest significant bit is 1 I can't decode it to a string anymore, because those are only supporting ASCII-characters. Also, I'll have to pass those strings to other processes via a Command Line Interface, which also is only supporting the ASCII-character set.
Before that problem arose, my approach on splitting the 64bit integer up into 8 separate bytes was the following, which worked really great:
vector<unsigned char> outputVector = vector<unsigned char>();
unsigned char * uidBytes = (unsigned char*) &UID_;
for (int i = 0; i < 8; i++){
    outputVector.push_back(uidBytes[i]);
}

Of course that doesn't work anymore, as the constrain "HBit may not be 1" limits the maximum value of each unsigned char to 127.
My easiest option now would of course be to replace the one push_back call with this:
outputVector.push_back(uidBytes[i] / 128);
outputVector.push_back(uidBytes[i] % 128);

But this seems kind of wasteful, as the first of each unsigned char pair can only be 0 or 1 and I would be wasting some space (6 bytes) I could otherwise use.
As I need to save 64 bits, and can use 7 bits per byte, I'll need 64//7 + 64%7 = 10 bytes.
It isn't really much (none of the files I write ever even reached the 1kB mark), but I was using 8 bytes before and it seems a bit wasteful to use 16 now when ten (not 9, I'm sorry) would suffice. So:
How do I convert a 64bit integer to a vector of ten 7-bit integers?
This is probably too much optimization, but there could be some very cool solution for this problem (probably using shift operators) and I would be really interested in seeing it.

A: You can use bit shifts to take 7-bit pieces of the 64-bit integer. However, you need ten 7-bit integers, nine is not enough: 9 * 7 = 63, one bit short.
  std::uint64_t uid = 42; // Your 64-bit input here.
  std::vector<std::uint8_t> outputVector;

  for (int i = 0; i < 10; i++)
  {
    outputVector.push_back(uid >> (i * 7) & 0x7f);
  }

In every iteration, we shift the input bits by a multiple of 7, and mask out a 7-bit part. The most significant bit of the 8-bit numbers will be zero. Note that the numbers in the vector are "reversed": the least significant bits have the lowest index. This is irrelevant though, if you decode the parts in the correct way. Decoding can be done as follows:
std::uint64_t decoded = 0;
for (int i = 0; i < 10; i++)
{
  decoded |= static_cast<std::uint64_t>(outputVector[i]) << (i * 7);
}

Please note that it seems like a bad idea to interpret the resulting vector as UTF-8 encoded text: the sequence can still contain control characters and and \0. If you want to encode your 64-bit integer in printable characters, take a look at base64. In that case, you will need one more character (eleven in total) to encode 64 bits.

A: I suggest using assembly language.
Many assembly languages have instructions for shifting a bit into a "spare" carry bit and shifting the carry bit into a register.  The C language has no convenient or efficient method to do this.
The algorithm:
for i =  0; i < 7; ++i
{
  right shift 64-bit word into carry.
  right shift carry into character.
}

You should also look into using std::bitset.


text:
Q: htaccess rewrite rule, root url to index.php fake directory to different .php file I've struggled with exactly what to search to find the answer to this question so I thought I would ask it instead.
I am building a small CMS script with PHP and want to prettify my urls. I have no issue with sending root level requests to my index.php as variables; for example example.com/index.php?p=about-us to example.com/about-us. However, without removing this facility I want to redirect a request like example.com/blog/a-post to example.com/blog.php?b=a-post. How can I achieve this without it getting consumed by the original index rewrite?
I apologise if the terminology I have used to describe my problem is not quite right, it's been some time since I have done any coding and I feel rusty as hell!
--Edit--
The code I currently have is below:
RewriteEngine On

RewriteCond %{THE_REQUEST} \s/+index\.php\?([^\s&]+) [NC]
RewriteRule ^ %1? [R=301,L]

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^([^/]+)/?$ index.php?p=$1 [L,QSA]

I wish the user to be able to access the url
url.com/blog/a-post

But I want this to actually access
url.com/blog.php?b=a-post

A: RewriteEngine On
RewriteRule ^work(.*)/([^/]*) work-single.php$1?slug=$2 [QSA]

work is the pseudo folder and work-single.php is the file which is getting the request of the variable


text:
Q: Received failed to connect error message on Ubuntu when trying to connect to 127.0.0.1, Could someone please help me to figure out the problem?
When curl -v 127.0.0.1 on Ubuntu, I get the following failed to connect error message.
$ curl -v 127.0.0.1
Trying 127.0.0.1:80...
TCP_NODELAY set
connect to 127.0.0.1 port 80 failed: Connection refused
Failed to connect to 127.0.0.1 port 80: Connection refused
Closing connection 0 curl: (7) Failed to connect to 127.0.0.1 port 80: Connection refused
I've been trying to install Magento2 on Ubuntu using WSL2 on Windows 11.
When browse as http://localhost, I see the Apache2 Ubuntu Default Page successfully
when browse as http://localhost/magento/, I see message "Not Found, The requested URL was not found on this server"
when browser as http://127.0.0.1, I see message "This site can't be reached, 127.0.0.1 refused to connect
since I'm not able to access http://localhost/magento/ as mentioned above, so I was just wondering if it has something to do with wsl2 that I can't access 127.0.0.1?
Thank you in advance, Katie


text:
Q: calculating total vat for sales i need to calculate the total  vat(15% of total sales) estimated for the total sales. im struggling with this query i first tried a select sum then  which didnt work-->
SELECT SUM(price) AS total_sales,
       SUM(price) * 0.15 AS fifteen_percent
FROM   sales;

here a is a picture of the products table

here is a picture of the sales table

any help would be greatly appreciated !, thank you.

A: SELECT SUM(price*quantity) AS total_sales,
       SUM(price*quantity) * 0.15 AS fifteen_percent
FROM   sales
JOIN products ON sales.prod_id = products.prod_id;

A: Wawrzyniec is correct, but you can also use a Windowed function for aggregation.
           SELECT DISTINCT prod_name,
                           SUM(price) OVER(PARTITION BY prod_name) * quantity as total_sales,
                           (SUM(price) OVER(PARTITION BY prod_name) * quantity) * 0.15 as  fifteen_percent
           FROM sales
           INNER JOIN products ON sales.prod_id = products.prod_id;