text:
Q: Ploting nested lists in dictionary - python My dataset is looking something like this:
{'Berlin': [[1, 333]],
 'London': [[1, 111], [2, 555]],
 'Paris': [[1, 444], [2, 222], [3, 999]]}

And for each city now I need to make scatter plot, for example, the plot of Paris should have on x-axis numbers: 1 2 3, and on the y-axis: 444 222 999.
I have a really big dataset, so I would like to have 5 cities per plot.
My code is looking something like this, but on the output I get empty plots.
for town in dictionary_town:
    x=[]
    y=[]
    i+=1
    save_plot = 'path'+str(i)+'.png'

    for list in town:
        x.append(list[0])
        y.append(list[1])

    plt.style.use('dark_background')
    plt.figure()
    plt.plot( kind='scatter',x = x, y=y,label=town, s=30,figsize=(50, 20), fontsize=25, alpha=0.5)
    plt.ylabel("Population", fontsize=50)
    plt.title(str(i), fontsize=50)
    legend = plt.legend(fontsize=30, markerscale=0.5, ncol=1)
    plt.savefig(save_plot)
    plt.close()

A: Here is a minimum working piece of code just to focus on saving graphs. I intentionally omitted graph-styling parts of your code to be simple.
import matplotlib.pyplot as plt

dictionary_town = {'Berlin': [[1, 333]],
                   'London': [[1, 111], [2, 555]],
                   'Paris': [[1, 444], [2, 222], [3, 999]]}

path = '/your_path_to_image_saving/' #pls change here
i = 0
for town, values in dictionary_town.items():
    x = []
    y = []
    i += 1
    save_plot = path + str(i) + '.png'
    for value in values:
        x.append(value[0])
        y.append(value[1])
    plt.figure()
    plt.scatter(x=x, y=y, label=town)
    plt.ylabel("Population")
    plt.title(str(i))
    plt.legend(loc=4)
    plt.savefig(save_plot)
    plt.close()

I recommend you to start from here and add some stylings one by one to figure out what's wrong.
Hope this helps.

EDIT:
Plot 5 cities at a time. If you want to change # of cities, change chunk. Also, if # of cities needs to be larger than 5, colors needs to be added accordingly.
import matplotlib.pyplot as plt
import numpy as np

dictionary_town = {'Berlin': [[1, 333]],
                   'London': [[1, 111], [2, 555]],
                   'Paris': [[1, 444], [2, 222], [3, 999]]}

colors = {1: 'r', 2: 'b', 3: 'g', 4: 'k', 5: 'grey'}

path = '/your_path_to_image_saving/' #pls change here
i = 0
chunk = 5
for town, values in dictionary_town.items():
    i += 1
    values = np.array(values)
    x = values[:,0]
    y = values[:,1]
    plt.scatter(x=x, y=y, label=town, color=colors[(i+1)%chunk+1])
    if i % chunk == 0:
        save_plot = path + str(i) + '.png'
        plt.ylabel("Population")
        plt.title(str(i))
        plt.legend(loc=4)
        plt.savefig(save_plot)
        plt.close()
    elif (i == len(dictionary_town)) & (i % chunk != 0):
        save_plot = path + str(i) + '.png'
        plt.ylabel("Population")
        plt.title(str(i))
        plt.legend(loc=4)
        plt.savefig(save_plot)
        plt.close()

A: You can simply transpose your lists with zip
in order to convert x, y pairs to lists:
import matplotlib.pyplot as plt

dictionary_town = {'Berlin': [[1, 333]],
 'London': [[1, 111], [2, 555]],
 'Paris': [[1, 444], [2, 222], [3, 999]]}

for i, town in enumerate(dictionary_town):
    x, y = zip(*dictionary_town[town])
    save_plot = 'path'+str(i)+'.png'

    plt.style.use('dark_background')
    fig = plt.figure(figsize=(50, 20))
    plt.scatter(x, y, s=30,label=town, alpha=0.5)
    plt.ylabel("Population", fontsize=50)
    plt.title(str(i), fontsize=50)
    plt.legend(fontsize=30, markerscale=0.5, ncol=1)
    plt.savefig(save_plot)
    plt.close(fig)


text:
Q: Proof that two sets are equanimous, Proof verification I am trying to prove that $X \cong Y$ from textbook which introduces uni maths.
Given
$X \cong \{1,\ldots , m\}$,
$Y \cong \{1, \ldots, n\}$,
$\{1,\ldots , m\} \cong \{1,\ldots , n\}$.
Proof
Since $X \cong \{1,\ldots , m\}$ and $Y \cong \{1, \ldots, n\}$, then for every $a_i \in \{1, \ldots, m\}$ we have $x_i \in X$ and for every $b_i \in \{1,\ldots , n\}$ we have $y_i \in Y$ such that
$x_1 \neq x_2 \implies a_1 \neq a_2$,
$y_1 \neq y_2 \implies b_1 \neq b_2$ because of bijectivity.
Now since $\{1,\ldots , m\} \cong \{1,\ldots , n\}$ and $X \cong \{1,\ldots , m\}$, by transitivity we have $X \cong \{1,\ldots , n\}$. Same applies to $Y$. Therefore $X \cong Y$.
Edit as suggested by Hagen von Eitzen:
Given
$X \cong \{1,\ldots , m\}$,
$Y \cong \{1, \ldots, n\}$,
$\{1,\ldots , m\} \cong \{1,\ldots , n\}$.
$\{1,\ldots , m\} \cong \{1,\ldots , n\}$ and $X \cong \{1,\ldots , m\}$, by transitivity we have $X \cong \{1,\ldots , n\}$. Same applies to $Y$. Therefore $X \cong Y$.

redpajama_set_name: RedPajamaStackExchange


text:
Q: JavaScript Dropdown Form Validation: Throwing Error when a value of "0" is passed I'm trying to create a form where if a value of "0" is passed, an error is thrown. I'm stumped and could really use some help. There are two functions in this script. The first is working, where I can change the URL based on the selection. Where I'm having a problem is I want the selection"--" AND "Choose State" to fire the second script that in theory would highlight the field and not allow the user to click. This is the function called "validateEmpty"
I'm totally open to a different approach, this is a hacked up version of a tutorial I found that passes a value.length of 0.
The sample page is here:
http://www.brimbar.com/no_crawl/js-test-homepage.html
OR
The code is below:

    <select id="stateType" name="stateType" onchange="dosomething()">
    <option value="select" selected="selected">Choose State</option>
    <option value="IL">Illinois</option>
    <option value="MD">Maryland</option>
    <option value="TX">Texas</option>
    <option value="VA">Virginia</option>
    <option value="--">--</option>
    <option value="other">Other</option>
    </select>

 Get a Quote!

A: 1) Ok, so You have decided to use the old, dark ways of inline javascript ;) instead of using Event Listeners, but why to setup href of the link element every time an option changes? It is not optimal. I would rather redirect when the link is clicked (on demand). This leaves You with only one function.
2) Instead of using if..else try to use switch..case construct it will ease things a little bit later. Moreover it seems more readable, but maybe it is more a matter of preference.
3) Why do You want to use such a twisted logic for validation? You already have a value of your select element which is '--'. Use it or You can also process it in default section of  switch case (see jsFiddle example) this also handles "Select State" option. When You click on the link and the "wrong" option is selected You get a warning instead of redirect.
Here is my jsFiddle example: example.


text:
Q: Python How to clear screen without clearing user input? Currently I am trying to make a chat system, but to update the screen, I need to clear it, then print out the messages.
Here is the code I am using, but it also clears the input that is already typed in by the user when the method clear() is ran:
def receive():
    with connection.cursor() as cursor:
        while True:
        sql = "SELECT * FROM chat"
        cursor.execute(sql)
        rows = cursor.fetchall()
        for row in rows:
            print(row[0]+": "+row[1])
        time.sleep(1)
        clear()

I am using multiprocessing, and here is where I am trying to take input:
p = multiprocessing.Process(target=receive)

p.start()

with connection.cursor() as cursor:
    while True:
        ask = input()
        if ask == "cancel()":
            p.terminate()
            clear()
            main()
        with connection.cursor() as cursor:
            sql = "insert into chat (name, message) values (%s, %s)"
            cursor.execute(sql, (name, ask))
            connection.commit()

clear is defined as clear = lambda: os.system('clear')
Any help as to keep the input from being erased would be appreciated!

A: Use 'clear -x' instead of 'clear' statement


text:
Q: Using JSON-based Database for unordered data I am working on a simple app for Android. I am having some trouble using the Firebase database since it uses JSON objects and I am used to relational databases.
My data will consists of two users that share a value. In relational databases this would be represented in a table like this:
**uname1**  **uname2** shared_value

In which the usernames are the keys. If I wanted the all the values user Bob shares with other users, I could do a simple union statement that would return the rows where:
uname1 == Bob or unname == Bob

However, in JSON databases, there seems to be a tree-like hierarchy in the data, which is complicated since I would not be able to search for users at the top level. I am looking for help in how to do this or how to structure my database for best efficiency if my most common search will be one similar to the one above.
In case this is not enough information, I will elaborate: My database would be structured like this:
{
     'username': 'Bob'
            {
                   'username2': 'Alice'
                         {
                               'shared_value' = 2
                         }
            }
      'username': 'Cece'
            {
                   'username2': 'Bob'
                         {
                               'shared_value' = 4
                         }
            }

As you can see from the example, Bob is included in two relationships, but looking into Bobs node doesn't show that information. (The relationship is commutative, so who is "first" cannot be predicted).
The most intuitive way to fix this would be duplicate all data. For example, when we add Bob->Alice->2, also add Alice->Bob->2. In my experience with relational databases, duplication could be a big problem, which is why I haven't done this already. Also, duplication seems like an inefficient fix.

A: Is there a reason why you don't invert this? How about a collection like:
{ "_id": 2, "usernames":[ "Bob", "Alice"]}
{ "_id": 4, "usernames":[ "Bob", "Cece"]}

If you need all the values for "Bob", then index on "usernames".
EDIT:
If you need the two usernames to be a unique key, then do something like this:
{ "_id": {"uname1":"Bob", "uname2":"Alice"}, "value": 2 }

But this would still permit the creation of:
{ "_id": {"uname1":"Alice", "uname2":"Bob"}, "value": 78 }

(This issue is also present in your as-is relational model, btw. How do you handle it there?)
In general, I think implementing an array by creating multiple columns with names like "attr1", "attr2", "attr3", etc. and then having to search them all for a possible value is an artifact of relational table modeling, which does not support array values. If you are converting to a document-oriented storage, these really should be an embedded list of values, and you should use the document paradigm and model them as such, instead of just reimplementing your table rows as documents.

A: You can still have old structure:
[
    { username: 'Bob', username2: 'Alice', value: 2 },
    { username: 'Cece', username2: 'Bob', value: 4 },
]

You may want to create indexes on 'username' and 'username2' for performance. And then just do the same union.

A: To create a tree-like structure, the best way is to create an "ancestors" array that stores all the ancestors of a particular entry. That way you can query for either ancestors or descendants and all documents that are related to a particular value in the tree. Using your example, you would be able to search for all descendants of Bob's, or any of his ancestors (and related documents).
The answer above suggest:
{ "_id": {"uname1":"Bob", "uname2":"Alice"}, "value": 2 }

That is correct. But you don't get to see the relationship between Bob and Cece with this design. My suggestion, which is from Mongo, is to store ancestor keys in an ancestor array.
{ "_id": {"uname1":"Bob", "uname2":"Alice"}, "value": 2 , "ancestors": [{uname: "Cece"}]}

With this design you still get duplicates, which is something that you do not want. I would design it like this:
{"username": "Bob", "ancestors": [{"username": "Cece", "shared_value": 4}]}
{"username": "Alice", "ancestors": [{"username": "Bob", "shared_value": 2}, {"username": "Cece"}]}


text:
Q: Azure Congnitive Service Skill not persisting custom skill value I have create a custom skill for my Azure Cognitive Service. After creating the datasouce, index, indexer and running the indexer I can see that my function is being called and it is outputting the correct information, but when I search the index the field that is connected to the custom skill is empty.
This is my indexer definition:
{
  "name": "idxdocs",
  "description": null,
  "dataSourceName": "dsdocs",
  "skillsetName": "skillset-procuradores",
  "targetIndexName": "customer-documents",
  "disabled": null,
  "schedule": null,
  "parameters": {
    "batchSize": null,
    "maxFailedItems": -1,
    "maxFailedItemsPerBatch": null,
    "base64EncodeKeys": null,
    "configuration": {
      "indexedFileNameExtensions": ".pdf,.docx,.doc",
      "dataToExtract": "contentAndMetadata",
      "failOnUnprocessableDocument": false,
      "failOnUnsupportedContentType": false,
      "indexStorageMetadataOnlyForOversizedDocuments": true,
      "allowSkillsetToReadFileData": true
    }
  },
  "fieldMappings": [],
  "outputFieldMappings": [
    {
      "sourceFieldName": "/document/content/procuradores",
      "targetFieldName": "procuradores"
    }
  ],
  "cache": null,
  "encryptionKey": null
}

This is my index:
{
  "name": "customer-documents",
  "fields": [
    {
      "name": "key",
      "type": "Edm.String",
      "facetable": true,
      "filterable": true,
      "key": true,
      "retrievable": true,
      "searchable": false,
      "sortable": true,
      "analyzer": null,
      "indexAnalyzer": null,
      "searchAnalyzer": null,
      "synonymMaps": [],
      "fields": []
    },
    {
      "name": "content",
      "type": "Edm.String",
      "facetable": false,
      "filterable": false,
      "key": false,
      "retrievable": true,
      "searchable": true,
      "sortable": false,
      "analyzer": "es.lucene",
      "indexAnalyzer": null,
      "searchAnalyzer": null,
      "synonymMaps": [],
      "fields": []
    },
    {
      "name": "procuradores",
      "type": "Edm.String",
      "facetable": false,
      "filterable": true,
      "key": false,
      "retrievable": true,
      "searchable": false,
      "sortable": false,
      "analyzer": null,
      "indexAnalyzer": null,
      "searchAnalyzer": null,
      "synonymMaps": [],
      "fields": []
    }
  ],
  "suggesters": [],
  "scoringProfiles": [],
  "defaultScoringProfile": null,
  "corsOptions": null,
  "analyzers": [],
  "charFilters": [],
  "tokenFilters": [],
  "tokenizers": [],
  "similarity": {
    "@odata.type": "#Microsoft.Azure.Search.BM25Similarity",
    "k1": null,
    "b": null
  },
  "encryptionKey": null,
  "@odata.etag": "\"0x8D98BC85E9F6996\""
}

My skill set definition:
{
  "name": "skillset-procuradores",
  "description": "",
  "skills": [
    {
      "@odata.type": "#Microsoft.Skills.Custom.WebApiSkill",
      "name": "procuradores",
      "description": "",
      "context": "/document",
      "uri": "my url ommited for secure reasons",
      "httpMethod": "POST",
      "timeout": "PT3M50S",
      "batchSize": 1,
      "degreeOfParallelism": null,
      "inputs": [
        {
          "name": "text",
          "source": "/document/content"
        }
      ],
      "outputs": [
        {
          "name": "procuradores",
          "targetName": "procuradores"
        }
      ],
      "httpHeaders": {}
    }
  ],
  "cognitiveServices": null,
  "knowledgeStore": null,
  "encryptionKey": null
}

And finally my function output:
{
    "values": [
        {
            "recordId": "1",
            "data": {
                "procuradores": "people's names"
            }
        }
    ]
}

What am I missing?

A: Rafael, can you give debug sessions a try? I suspect there is something happening in your custom skill that means the data is not coming back. By using this, you can test the actual input and output.
https://learn.microsoft.com/en-us/azure/search/cognitive-search-debug-session

A: This is just a hunch, but in the indexer definition, try changing your output field mapping sourceFieldName from "/document/content/procuradores" to "/document/procuradores".  The context that you are giving in the skill is just "/document" so it should append the output onto that.


text:
Q: Populating Menu from a database I need to populate an ASP.NET menu control with hierarchical structure with menu items that can be constantly changed, from a database (categories with n levels of sub categories).
There are some approaches for that and I would like to hear which one is the most efficient one.
I have those in mind:

*

*Retrieving data from database and converting it to xml then transforming it with customized  XSLT  file and binding it to Menu control

*Retrieving data from database and while looping through (recursive), inserting menu items and children to the menu control

*SQL Site Map Provider (thanks to Made4Print)

*Something else?

A: The ASP.NET Menu Control can use a .SiteMap file through a SiteMapDataSource.
You can implement your own SiteMapProvider, this way you can have your SiteMap heirarchy within your database and wireup the same components making things more dyanamic.
Here is an example: http://weblogs.asp.net/scottgu/archive/2006/01/11/435108.aspx
HTH

A: If you want to do this, I would definitely recommend option 2, since it contains one level of transformation less than option 1. If you already loop through the menu items and their hiearchies, you might as well build up the menu items and subitems directly - I don't see any big benefit from taking a detour over XML and then through XSLT into a menu structure, really.
Marc
PS: Option 3 (the SQL Sitemap provider) also sounds like a really good idea, if the site map structure and options are good enough for you (they usually should be). I would probably try that option first, and go from there.

A: I agree with Marc. You could then package everything inside a server-control for reusability. Converting everything into XML and then using XSLT to somehow "convert" it back seems an overhead to me.


text:
Q: Pass URL path into $http get url- AngularJS I'm trying to get a value from a URL part, into my $http getURL request. I have tried a few solutions (such as HTML5mode) but have not had success.
Here is my code:
angular.module('myapp123.products', [])

.factory('productsApi', ['$http', '$location',
    function($http, $location){

        var BASE_URL = 'http://stashdapp-t51va1o0.cloudapp.net/api/item/';

        return {
            get: getApiData
        };

        function getData() {
            var product_id = $location.path().split("/")[3] || "Unknown"; //URL = /#/product/id/1234 <---
            return $http.get(BASE_URL + product_id);
        }
    }]
)

.controller('productsCtrl', ['$scope', '$log', 'productsApi', 'UserService',
    function($scope, $log, productsApi, UserService) {

        $scope.isVisible = function(name){
            return true;// return false to hide this artist's albums
        };

        // <======  Rewrite with accounts preferences
        productsApi.getApiData()
            .then(function (result) {
                //console.log(JSON.stringify(result.data)) //Shows log of API incoming
                $scope.products = result.data;
            })
            .catch(function (err) {
                $log.error(err);
            });
    }
]);

A: The code in your example has a lot of syntax errors in it. Here is what it should look like, based on what I think you are going for...
angular.module('myapp123.products', [])
    .config(locationConfig)
    .factory('productsApi', productsApiFactory)
;

locationConfig.$inject = ['$locationProvider'];
function locationConfig($locationProvider) {
    $locationProvider.html5Mode(true);
}

productsApiFactory.$inject = ['$http', '$location'];
function productsApiFactory($http, $location) {
    var BASE_URL = 'http://stashdapp-t51va1o0.cloudapp.net/api/list/';

    return {
        get: getData
    };

    function getData() {
        var product_id = $location.path().split("/")[3] || "Unknown";
        return $http.get(BASE_URL + product_id);
    }
}

In this version, the config function is correctly defined to set up html5mode and the service factory is configured to use $location each time the get() method is called.
You would use the service in a controller like this:
ExampleController.$inject = ['productsApi'];
function ExampleController(productsApi) {
    productsApi.get()
        .then(function onSuccess(res) {
            // handle successful API call
        })
        .catch(function onError(err) {
            // handle failed API call
        })
    ;
}


text:
Q: Closure (the good way book) I am going over the 4th chapter of this book and have run into a problem on the code below. This code goes right over my head and I cant seem to figure out why the (i) is there. He explains in the book but its just not that great of an explanation.
  //Make a function that assigns event handler functions to an array of nodes the right way
  //When you click on a node, an alert box will display the ordinal of the node.

    var add_the_handlers = function(nodes){
        var i;
        for (i = 0; i < nodes.length; i += 1){
            nodes[i].onclick = function(i){
                return function (e){
                    alert(i);
                };
            }(i); // <-------------this i  right here.
        }
    };

A: Putting (someValue) after a function expression will immediately call that function.
foo = function (i){ ... }(i);

will give you the same result as:
bar = function (i){ ... };
foo = bar(i);

By having a locally scoped variable i inside that function (defined via function (i)), the value is captured (closed over) and won't change when the other i (the one in scope outside the function) changes (which it will every time you go around the loop).
I'd generally use a different name for the variable inside the closure. Duplicate variable names can be confusing.
nodes[i].onclick = function(closed_over_i){
    return function (e){
        alert(closed_over_i);
    };
}(i);

A: The (i) calls the first anonymous function immediately, meaning that nodes[i].onclick gets the second anonymous function.
There are actually two is there which may be confusing the issue a bit - there is one in the scope of the add_the_handlers function, and another in the onclick function.
I'll rewrite it and number the lines to help explain:
1.  var add_the_handlers = function (nodes) {
2.      var i;
3.      for (i = 0; i < nodes.length; i += 1){
4.          nodes[i].onclick = function (j) {
5.              return function (e) {
6.                  alert(j);
7.              };
8.          }(i);
9.      }
10. };

This is functionally identical to your original code; because they're different scopes, your version can have the same variable name without them interfering with each other; it's just a new variable i which is only available within that function. I've changed it to j just to make it clearer where the two scopes are.
On line 4 you define an anonymous function which takes a single argument j, and then call it immediately on line 8 with the current value of i. You do this to create a new scope, copying the current value of i into it. The value of j is no longer linked to the i being incremented by the loop.
This means that you can now define the second anonymous function on line 5 (the closure) in that new scope, so j will always refer to the variable in that scope. You then return that function and assign it to nodes[i].onclick, so when it is called it will always alert the value of i that it was when it was defined, even thought it is now called in a different scope.
Without the function call on line 8, the i on line 6 of your example would be in the scope of the outer function starting at line 1; because that value is changed in the loop on line 3 for each item in the array, all onclick functions would alert the final value of i, nodes.length.
The example code is just a more compact and confusing way of writing:
var create_closure = function (val) {
    // This val is in a separate scope to the i
    return function (e) {
        // This is the closure; it references a variable in the parent scope
        alert(val);
    };
};

var add_the_handlers = function (nodes){
    var i;
    for (i = 0; i < nodes.length; i += 1) {
        nodes[i].onclick = create_closure(i);
    }
};

Although the example is making a point, in general this will be a better way to write the solution - less nesting and a named function makes it clearer to anyone coming along afterwards, and less likely you'll make a mistake with it later. At the very least use a different variable name in your closure.


text:
Q: Python crashing while processing cursor I have a fairly small script which is running a cursor on a small feature class (~2500 features) which is crashing python with a python.exe has stopped working message.

I have a cursor that loops over features, deletes any that don't meet a set criteria, looks up field value keys in a dictionary, and updates another field with the dictionary value.  This works well.  But if I add in a check to deleteRow() any records that have a Null or a value that doesn't start with the letter O.
arcpy.FeatureClassToFeatureClass_conversion(r"mydatabase.sde\mydatabase.dbo.SitePolygon", "in_memory", "xTempPolygon")

with arcpy.da.UpdateCursor(r'in_memory\xTempPolygon', ['RecID', 'LotID', 'Owner', 'Manager', 'Class']) as cursor:
    for row in cursor:
        if row[2] != 'CITY' or row[4][:4].upper() == 'ROAD' or row[3].upper() in ['WASTEWATER', 'STORMWATER', 'WATERSUPPLY']:
            cursor.deleteRow()
        elif row[0] in resultDict:
            row[1] = resultDict[row[0]]
            cursor.updateRow(row)

        #################################################
        # If I add this block, it crashes
        if row[1] is None or row[1][0].upper() != 'O':
            cursor.deleteRow()
        #################################################

The resultDict is a dictionary that comes from a SQL lookup that returns RecID and LotID.  These are looked up in the cursor and populates the LotID on the feature based on its RecID.
If I leave out the final if block, it runs without issue.  If I add it in it crashes.  I need it there because I'm ending up with some records that have a NULL or a value that doesn't start with O in the LotID field.  I need these records deleted.
I need the extra if to run after the update to allow for the update to run, as no records have any values in row[1] before the update - they are all NULL so they'd all be deleted.
What is causing this crash, and how do I avoid it?

A: Thanks to @Vince and @NateWanner for two suggestions that pointed me in the right direction.
As @Vince had commented, I was trying to access a row that had been deleted.
I created an else block and moved my elif (and turned it into if) and the failing if block into the else so that it would only process on rows that hadn't yet been deleted.
arcpy.FeatureClassToFeatureClass_conversion(r"mydatabase.sde\mydatabase.dbo.SitePolygon", "in_memory", "xTempPolygon")

with arcpy.da.UpdateCursor(r'in_memory\xTempPolygon', ['RecID', 'LotID', 'Owner', 'Manager', 'Class']) as cursor:
    for row in cursor:
        if row[2] != 'CITY' or row[4][:4].upper() == 'ROAD' or row[3].upper() in ['WASTEWATER', 'STORMWATER', 'WATERSUPPLY']:
            cursor.deleteRow()
        else:
            if row[0] in resultDict:
                row[1] = resultDict[row[0]]
                cursor.updateRow(row)
            if row[1] is None or row[1][0].upper() != 'O':
                cursor.deleteRow()

This is now working as desired, although thinking on the two comments further leads me to believe there may be even better ways to construct this cursor that'll I'll investigate.


text:
Q: Removing bit at specific index I'm basically trying to remove a bit from an integer at a specific index. That is, I do not want to unset/clear the bit; I actually want to strip it, so that every higher bit moves down, replacing the respective bit at its position. Visually, this could be compared to deleting an element from an array or removing a character from a string.
For the sake of clarity, some examples:
1011011 (original number)
    ^ index = 2
0101111 (result)

10000000000000000000000000000001
^ index = 31
00000000000000000000000000000001

1111111111111111111111111111110
                              ^ index = 0
0111111111111111111111111111111

Full of confidence, I started shifting some bits, and came up with the following Java method...
public static int removeBit(int num, int i) {
    int out = (num >>> (i + 1)) << i;
    out  |= (num << (32 - i)) >>> (32 - i);
    return out;
}

... which almost always works, except for some extreme cases:
10000000000000000000000000000001 (= Integer.MAX_VALUE - 1)
^ index = 31, results in:
10000000000000000000000000000001

1011011
      ^ index = 0, results in:
1111111

In other words, if the index is 0 or 31 (least or most significant bit), my method will output garbage.
I can't seem to wrap my head around it, and that's why I'm asking: How can I remove an arbitrary bit in a 32-bit integer?
I'm especially looking for the most performant way to do it in Java (smallest possible memory and CPU consumption), since this operation has to run at least a couple million times. That's why something like "convert it into a string, remove the char and convert it back" is out of the question.

A: As explained in the comments, the shift counts rolled over to >= 32, which caused trouble.
Anyway, let's derive a way to do it.
Start by considering the two "pieces", the low piece (which gets copied in its original position and may be anywhere between 0 .. 31 bits long) and the high piece (which gets shifted down by one, and can also be between 0 .. 31 bits long). The total length of the pieces is always 31.
The mask for the low piece is obvious: ~(-1 << i)
Which makes the mask for the high piece obvious: ~lowmask << 1. The high piece is shifted anyway, so that shift can go.
Now all that's left is to take the pieces and OR them together, and you would get
static int removeBit(int x, int i)
{
    int mask = ~(-1 << i);
    return (x & mask) | ((x >>> 1) & ~mask);
}

Throw out the double negation:
static int removeBit(int x, int i)
{
    int mask = -1 << i;
    return (x & ~mask) | ((x >>> 1) & mask);
}

A: Just mask out the bits needed, no need to shift back and forth
public static int removeBit(int num, int index) {
    int mask = (1 << index) - 1;
    return ((num & ((~mask) << 1)) >>> 1) | (num & mask);
}

or
public static int removeBit(int num, int index) {
    int mask = (1 << index) - 1;
    return ((num >>> 1) & ~mask) | (num & mask);
}

Some platforms have very efficient parallel bit extract so if you can do the job in JNI or if Java has some intrinsic similar to Bmi2.ParallelBitExtract then you can do like this
public static int removeBit(int num, int index) {
    return Bmi2.ParallelBitExtract(num, ~(1 << index));
}

A: If it is important to use the minimum number of instructions, for these kind of bit shuffling it is often best to calculate the bits that need to be toggled and then use xor to apply that. Also here this saves one instruction compared to harold's solution:
static int removeBit(int x, int i)
{
    int mask = -1 << i;
    return ((x ^ (x >>> 1)) & mask) ^ x;
}

or
static int removeBit(int x, int i)
{
    return (((x ^ (x >>> 1)) >>> i) << i) ^ x;
}


text:
Q: Import CSV to Update only one column in table I have a table that looks like this:
products
--------
id, product, sku, department, quantity

There are approximately 800,000 entries in this table. I have received a new CSV file that updates all of the quantities of each product, for example:
productA, 12
productB, 71
productC, 92

So there are approximately 750,000 updates (50,000 products had no change in quantity).
My question is, how do I import this CSV to update only the quantity based off of the product (unique) but leave the sku, department, and other fields alone? I know how to do this in PHP by looping through the CSV and executing an update for each single line but this seems inefficient.

A: I would load the update data into a seperate table UPDATE_TABLE and perform an update within MySQL using:
UPDATE PRODUCTS P SET P.QUANTITY=(
    SELECT UPDATE_QUANTITY
    FROM UPDATE_TABLE
    WHERE UPDATE_PRODUCT=P.PRODUCT
)

I dont have a MySQL at hand right now, so I can check the syntax perfectly, it might be you need to add a LIMIT 0,1 to the inner SELECT.

A: You can use LOAD DATA INFILE to bulk load the 800,000 rows of data into a temporary table, then use multiple-table UPDATE syntax to join your existing table to the temporary table and update the quantity values.
For example:
CREATE TEMPORARY TABLE your_temp_table LIKE your_table;

LOAD DATA INFILE '/tmp/your_file.csv'
INTO TABLE your_temp_table
FIELDS TERMINATED BY ','
(id, product, sku, department, quantity);

UPDATE your_table
INNER JOIN your_temp_table on your_temp_table.id = your_table.id
SET your_table.quantity = your_temp_table.quantity;

DROP TEMPORARY TABLE your_temp_table;

A: Answer from @ike-walker is indeed correct but also remember to double check how your CSV data if formatted. Many times for example CSV files can have string fields enclosed in double quotes ", and lines ending with \r\n if working on Windows.
By default is assumed that no enclosing character is used and line ending is \n.
More info and examples here https://mariadb.com/kb/en/importing-data-into-mariadb/
This can be fixed by using additional options for FIELDS and LINES
CREATE TEMPORARY TABLE your_temp_table LIKE your_table;

LOAD DATA INFILE '/tmp/your_file.csv'
INTO TABLE your_temp_table
FIELDS
   TERMINATED BY ','
   OPTIONALLY ENCLOSED BY '"'    -- new option
LINES TERMINATED BY '\r\n'       -- new option

(id, product, sku, department, quantity);

UPDATE your_table
INNER JOIN your_temp_table on your_temp_table.id = your_table.id
SET your_table.quantity = your_temp_table.quantity;

DROP TEMPORARY TABLE your_temp_table;


text:
Q: JavaFX 8 hiding side panel and mini window with button Good evening.
After playing around with a few Java FX 8 tutorials and making some simple applications, I decided to take a slightly more difficult project.
I had an old Swing map application that displayed maps, layers and meteorological data from a DB using map objects and taking the maps from a local map server. I wish to update this application to pure Java FX 8 and probably the geoserver java api, which I recently added to my old swing app.
The first thing I did, is try to build a model for the application in Scene Builder 2.0, to have the general idea. Since I was making this from scratch, I wished to make it a little more modern.
And here is the problem. I wish to have the map in a tabbed pane, taking almost the whole screen, with a minor panel bellow displaying some data ( I have yet to decide which of the old data is actually useful), and a menu bar on top. I user the border pane for the central app, with the menu bar north, the pane south and the tab in the center.
So far so good. But, I cannot figure out how to add a button with which the user can hide/unhide an accordion pane and a minimap of the whole world, as the picture bellow show:

I think the accordion panel will actually be with the map inside an HBOX, with the map panel having the Hgrow set as Always and the button actually resizing the accordion panel to hide/unhide it. Also, I want the mini-map to be always on top of both windows.
However, I have no idea how to put the buttons there. I tried many different layouts and tricks, but have found no actual solution. I cannot find any examples, and unfortunately the 2 books I bought do not even go beyond the given layouts. Is there any way to do this?
Also, while not a priority, does JavaFX have the capability to drag and drop components (p.ex. the minimap) and lock it on a certain place? For a user that could perhaps want the minimap to the down-right corner instead?

A: I would suggest using/writing a custom Pane.
Add the Map, SideBar, SideBar ToggleButton, Minimap ToggleButton and the MiniMap to its children. And do not forget to call toFront() and toBack() accordingly to put the the elements in the correct layers.

Now there are two ways on how to position your elements:

*

*Overwrite the layoutChildren() method of the StackPane and set the coordinate of the components there with relocate(x,y) or resizeRelocate(x,y,width,height). Or

*Set the managed property of the aforementioned elements to false (setManaged(false)) and bind layoutX and layoutY Properties to the desired values.

If you are going for #1 (not really code, but hopefully you get the idea):

*

*The MiniMap Button, should be left bottom so: x = 0 | y = Pane.getHeight() - button.getHeight()

*The SideBar Button should be left center: x = SideBar.getWidth() - Button.getWidth() | y = Pane.getHeight() / 2 - button.getHeight() / 2

*and so on...

If you are going for #2 (again not really tested code):

*

*The MiniMap Button: setLayoutX(0) | layoutY.bind(Pane.heightProperty())

*The SideBar Button: layoutXProperty.bind(SideBar.widthProperty().subtract(button.widthProperty)) | `layoutYProperty.bind(Pane.heightProperty().divide(2).subtract(button.heightProperty().divide(2)))

*and so on...

And yes, you can move the MiniMap with mouse gestures. Have a look at setOnMousePressed() and setOnMouseDragged(). With the first event you would typically store the current coordinate and with the second event calculate the delta by which you would adjust the layoutX/layoutY values.

Edit:
You might also have a look at ControlsFX, they have a HiddenSidesPane and a MasterDetailPane which might (partly) be what you are looking for.


text:
Q: Fix Postfix Authentication for Sendgrid? I'm having trouble configuring Postfix to deliver e-mail via relay to Sendgrid.
I get the following error: "Unauthenticated senders not allowed"

A: Looks like it was the SASL config within Postfix authenticating to Sendgrid.  We were able to use the following:
smtpd_sasl_local_domain = $myhostname
smtpd_recipient_restrictions = permit_sasl_authenticated, permit_mynetworks, reject_unauth_destination
mailbox_size_limit = 256000000

# Sendgrid Settings
smtp_sasl_auth_enable = yes
smtp_sasl_password_maps = static:SENDGRID_ACCOUNT_EMAIL_HERE:PASSWORD_HERE
smtp_sasl_security_options = noanonymous
smtp_tls_security_level = may
header_size_limit = 4096000
relayhost = [smtp.sendgrid.net]:587


text:
Q: Error: Package exports for /node_modules/@babel/helper-compilation-targets' do not define a '.' subpath I just created a new project folder and ran the following commands:

*

*npm init

*npm install express

*npm install express-react-views react
react-dom

Created index.js with express imported and views for a sample jsx file. When I run on localhost, I get this error:
Error: Package exports for '<path_to_project_folder>/node_modules/@babel/helper-compilation-targets' do not define a '.' subpath
    at applyExports (internal/modules/cjs/loader.js:485:15)
    at resolveExports (internal/modules/cjs/loader.js:508:12)
    at Function.Module._findPath (internal/modules/cjs/loader.js:577:20)
    at Function.Module._resolveFilename (internal/modules/cjs/loader.js:879:27)
    at Function.Module._load (internal/modules/cjs/loader.js:785:27)
    at Module.require (internal/modules/cjs/loader.js:956:19)
    at require (internal/modules/cjs/helpers.js:74:18)
    at Object.<anonymous> (<path_to_project_folder>/node_modules/@babel/preset-env/lib/debug.js:8:33)
    at Module._compile (internal/modules/cjs/loader.js:1063:30)
    at Module._compile (<path_to_project_folder>/node_modules/pirates/lib/index.js:99:24)

In Oct 2019, I created an express app using the same steps ran, and found there is no such package (@babel/helper-compilation-targets), and it ran fine.
I'm not sure what is wrong. Can anyone help to advice?
Thank you!

A: It will be fixed on babel v7.8.4, see https://github.com/babel/babel/pull/11006. Before a new babel release is cut, please upgrade node.js to >=13.2.0, which incorporates the necessary upstream fix.
Note that node.js 12 is not affected unless you have manually toggled on --experimental-modules flag. If that is the case, please also upgrade node.js to >=13.2.0.

A: So this seems to be an incompatibility between Babel and Node.js. The general solution is to switch to nodejs 12 (e.g. if you are using nvm), since it only affected nodejs 13:
nvm install 12
nvm use 12

However, for my Rails 6 application this was not sufficient alone, as I still got the same error. Telling Yarn about the node version I am expecting to use was necessary in addition to that. So I added this to the package.json:
"engines": {
  "node": "12.14.1"
}

A: Had the same issue. Updating the node.js fixed that for me


text:
Q: How to find angles of a triangle inside a circle given a perpendicular tangent line?
As the title says, I'm having trouble with tangent perpendicular lines and circles in triangles. I was given the problem linked above for practice & given the answer, but I am still stumped on it.
I was only able to solve for angle a, which equals 80, since 60 + 40 + a = 180.
The given answers to the equation are:

*

*Angle a = 80

*Angle b = 40

*Angle c = 60

I'm more confused on how to solve for angle b & c in the first place. I would also greatly appreciate a breakdown of the steps of solving this problem if possible. Thanks in advance.

A: the angles in the tangent, they are incribed angles too, the same as c and b
Improving what i said, the angle c = the angle 60 and the angle 40 = to the angle b, because the angle formed by the tangent and a segment passing through the circuference twice it is an inscribed angle.

A: Illustration just for one angle, $\beta$:

\begin{align}
\angle EAO&=\angle OFA=90^\circ
,\\
\angle ABC&=\tfrac12\angle AOC=
\angle AOF=\angle FOC=\beta
,\\
\angle FAO&=90^\circ-\beta
,\\
\angle EAF&=\angle EAO-\angle FAO
=90^\circ-(90^\circ-\beta)=
\beta
.
\end{align}
The reasoning for the other angle ($\gamma)$ is similar.

A: One of Euclid's propositions..
In a circumscribed  triangle the angle between a chord and tangent at a point equals the angle in the alternate segment.
That determines where the angles $ 40^0, 60^0 $ should go.


text:
Q: CocoaPods Swift and Objective-C Pods Can you have both Swift and Objective-C Pods? I currently only have Objective-C pod installed, and trying to add "SwiftyJSON" but it is a swift pod. It is telling me to add use_frameworks!. but that messes up my Objective-C pod.

A: Yes you should be able to use use_frameworks! with both Objective-C and Swift. Keep in mind these are specific to iOS 8 and newer. Also in theory the Objective-C library you're using could have strange compatibility issues with frameworks.


text:
Q: Castle.Windsor: IoC resolution of SWF controls without skinned look and feel I am using several services that are registered inside my IoC container. There is an interface IFormService to make forms accessible from within my main application. The interface is defined by
public interface IFormService
{
    System.Windows.Forms.Form Form { get; }
}

and for example implemented by a class MainFormService which returns the main form instance.
container.Register(
    Component.For<IFormService>()
             .ImplementedBy<MainFormService>()
             .Named("Application.Forms.MainForm")
    );

After application initialization, I am using this service to retrieve the form and let the application run:
Form mainForm = this.ServiceContainer
                    .Resolve<IFormService>("Application.Forms.MainForm")
                    .Form;
Application.Run(mainForm);

This works perfectly. The only issue is that the controls on the form look sort of 95-ish:

Later in my development I want to switch to using DevExpress skins which seems to produce the same issue. Why is that happening and how could I solve this properly?
Thanks in advance.


text:
Q: Are the required parameters of a function called dependencies? I'm studying dependency injection and I want to know if required function parameters can be considered dependencies.
I'd just like to make sure before I go around referring to them dependencies and that turns out to not be exactly accurate.
function doSomething(required){

    if(required !== null){

        // do stuff

    }

}

Are the required parameters of a function called dependencies?

A: Not necessarily.
If you look at the Wikipedia Article, you'll find that a Dependency is considered a service.  In practical terms, this is going to be an object of some sort (a reference type to be more exact). While that object is going to be passed to some class constructor as a parameter, not all constructor parameters are service objects, and therefore not all parameters are dependencies in that sense.
Most IoC Containers are tasked with creating objects, not satisfying primitive (value type) constructor parameters.


text:
Q: Why is ArcGIS Desktop labeling wrong polygons? I am working with a very large data set. When I label my polygons, the labels display like a highway of labels through the middle of my map. I'm using ArcGIS 9.3. I have tried to fix it with Maplex, but then won't even display in any fashion. When I use the standard label method, they show up, but they are all over the place, some polygons show 3 or 4 labels, only one of them being the label for that polygon. Any idea what the problem, or better yet, solution might be?

A: Without seeing an example image or the actual data it is hard to determine.
But, if you have large irregular shaped polys the actual "wieghted" centroid could be outside of the polygon. that is how esri creates their centroids.
If you look for the polygon settings in maplex you should see label only inside polygon. you might try that. see other posts recently for more "tips" on labeling.

A: Maybe you have overlapping polygons in your data set? If you have a large polygon on top of a smaller one, this will hide the smaller polygon - but not the label. In the Placement Properties for labels, you will find the option "Only place label inside polygon", which should prevent labels from being placed on other polygons (unless they are placed on top of each other). If your data set is stored in a file geodatabase or a personal geodatabase - or even in shape files - you could try the Check Geometry tool in ArcToolbox to see if there are any strange geometric errors in your data set. Use the Repair Geometry tool to handle these possible errors and then see how your labels are acting.
Good luck :-)

A: I would create a new shapefile with centroids of your polygons with QGis and this plugin.
Then add this new point shapefile to the project and label it. So at the end, you will have labels at the absolute correct centre of your polygons (centroid points).


text:
Q: Save EmailBody as PDF file using EWS API I'm using Exchange Web Services Managed API 2.0 to connect to Exchange server 2010. I wanted to download email body to a PDF file in a folder on the disk.
I do not want to use any paid third party to integrate.
Any help will be appreciated.

A: PdfSharp is a great free library for creating and manipulating PDFs. See this answer, it should set you in the right direction.
Edit: Seems like PdfSharp doesn't actually provide an option to convert an HTML to PDF. I have since explored different libraries. I found that ChromeHtmlToPdf is a good free alternative and easy to use. Bear in mind that it uses Chrome to work it's magic.


text:
Q: How do I install MarkupSafe into my Flask virtualenv on an Amazon Linux AMI? I created a virtualenv on my Amazon Linux AMI (ID_LIKE="rhel fedora", VERSION="2016.09") and ran pip install flask. But when I invoke python and run import flask, I get:
(env)$ python
Python 2.7.12 (default, Sep  1 2016, 22:14:00)
[GCC 4.8.3 20140911 (Red Hat 4.8.3-9)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import flask
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/home/dspitzer/dev/python/Lonestar/env/local/lib/python2.7/dist-packages/flask/__init__.py", line 19, in <module>
    from jinja2 import Markup, escape
  File "/home/dspitzer/dev/python/Lonestar/env/local/lib/python2.7/dist-packages/jinja2/__init__.py", line 33, in <module>
    from jinja2.environment import Environment, Template
  File "/home/dspitzer/dev/python/Lonestar/env/local/lib/python2.7/dist-packages/jinja2/environment.py", line 15, in <module>
    from jinja2 import nodes
  File "/home/dspitzer/dev/python/Lonestar/env/local/lib/python2.7/dist-packages/jinja2/nodes.py", line 19, in <module>
    from jinja2.utils import Markup
  File "/home/dspitzer/dev/python/Lonestar/env/local/lib/python2.7/dist-packages/jinja2/utils.py", line 624, in <module>
    from markupsafe import Markup, escape, soft_unicode
ImportError: No module named markupsafe
>>>

So I tried pip install markupsafe. It seems to work:
(env)$ pip install markupsafe
Collecting markupsafe
  Using cached MarkupSafe-1.0.tar.gz
Installing collected packages: markupsafe
  Running setup.py install for markupsafe
    building 'markupsafe._speedups' extension
    gcc -pthread -fno-strict-aliasing -O2 -g -pipe -Wall -Wp,-D_FORTIFY_SOURCE=2 -fexceptions -fstack-protector --param=ssp-buffer-size=4 -m64 -mtune=generic -D_GNU_SOURCE -fPIC -fwrapv -DNDEBUG -O2 -g -pipe -Wall -Wp,-D_FORTIFY_SOURCE=2 -fexceptions -fstack-protector --param=ssp-buffer-size=4 -m64 -mtune=generic -D_GNU_SOURCE -fPIC -fwrapv -fPIC -I/usr/include/python2.7 -c markupsafe/_speedups.c -o build/temp.linux-x86_64-2.7/markupsafe/_speedups.o
    gcc -pthread -shared build/temp.linux-x86_64-2.7/markupsafe/_speedups.o -L/usr/lib64 -lpython2.7 -o build/lib.linux-x86_64-2.7/markupsafe/_speedups.so
Successfully installed markupsafe

...but I still get "ImportError: No module named markupsafe" when I import flask.
I downloaded MarkupSafe-1.0.tar.gz from https://pypi.python.org/pypi/MarkupSafe and (with my virtualenv still activated) I ran python setup.py install:
(env)$ python setup.py install
running install
Checking .pth file support in /home/dspitzer/dev/python/Lonestar/env/lib64/python2.7/dist-packages/
/home/dspitzer/dev/python/Lonestar/env/bin/python -E -c pass
TEST FAILED: /home/dspitzer/dev/python/Lonestar/env/lib64/python2.7/dist-packages/ does NOT support .pth files
error: bad install directory or PYTHONPATH

You are attempting to install a package to a directory that is not
on PYTHONPATH and which Python does not read ".pth" files from.  The
installation directory you specified (via --install-dir, --prefix, or
the distutils default setting) was:

    /home/dspitzer/dev/python/Lonestar/env/lib64/python2.7/dist-packages/

and your PYTHONPATH environment variable currently contains:

    ''

Here are some of your options for correcting the problem:

* You can choose a different installation directory, i.e., one that is
  on PYTHONPATH or supports .pth files

* You can add the installation directory to the PYTHONPATH environment
  variable.  (It must then also be on PYTHONPATH whenever you run
  Python and want to use the package(s) you are installing.)

* You can set up the installation directory to support ".pth" files by
  using one of the approaches described here:

  https://pythonhosted.org/setuptools/easy_install.html#custom-installation-locations

Please make the appropriate changes for your system and try again.

Now what do I do? Running sudo python setup.py install might work, but then MarkupSafe isn't installed into my virtualenv.
Update: Out of desperation (since I'm blocked), I ran:
(env)$ export PYTHONPATH=/home/dspitzer/dev/python/Lonestar/env/lib64/python2.7/dist-packages/
(env)$ python setup.py install
running install
running bdist_egg
running egg_info
writing MarkupSafe.egg-info/PKG-INFO
writing top-level names to MarkupSafe.egg-info/top_level.txt
writing dependency_links to MarkupSafe.egg-info/dependency_links.txt
reading manifest file 'MarkupSafe.egg-info/SOURCES.txt'
reading manifest template 'MANIFEST.in'
writing manifest file 'MarkupSafe.egg-info/SOURCES.txt'
installing library code to build/bdist.linux-x86_64/egg
running install_lib
running build_py
running build_ext
creating build/bdist.linux-x86_64/egg
creating build/bdist.linux-x86_64/egg/markupsafe
copying build/lib.linux-x86_64-2.7/markupsafe/_speedups.c -> build/bdist.linux-x86_64/egg/markupsafe
copying build/lib.linux-x86_64-2.7/markupsafe/_constants.py -> build/bdist.linux-x86_64/egg/markupsafe
copying build/lib.linux-x86_64-2.7/markupsafe/_native.py -> build/bdist.linux-x86_64/egg/markupsafe
copying build/lib.linux-x86_64-2.7/markupsafe/_speedups.so -> build/bdist.linux-x86_64/egg/markupsafe
copying build/lib.linux-x86_64-2.7/markupsafe/_compat.py -> build/bdist.linux-x86_64/egg/markupsafe
copying build/lib.linux-x86_64-2.7/markupsafe/__init__.py -> build/bdist.linux-x86_64/egg/markupsafe
byte-compiling build/bdist.linux-x86_64/egg/markupsafe/_constants.py to _constants.pyc
byte-compiling build/bdist.linux-x86_64/egg/markupsafe/_native.py to _native.pyc
byte-compiling build/bdist.linux-x86_64/egg/markupsafe/_compat.py to _compat.pyc
byte-compiling build/bdist.linux-x86_64/egg/markupsafe/__init__.py to __init__.pyc
creating stub loader for markupsafe/_speedups.so
byte-compiling build/bdist.linux-x86_64/egg/markupsafe/_speedups.py to _speedups.pyc
creating build/bdist.linux-x86_64/egg/EGG-INFO
copying MarkupSafe.egg-info/PKG-INFO -> build/bdist.linux-x86_64/egg/EGG-INFO
copying MarkupSafe.egg-info/SOURCES.txt -> build/bdist.linux-x86_64/egg/EGG-INFO
copying MarkupSafe.egg-info/dependency_links.txt -> build/bdist.linux-x86_64/egg/EGG-INFO
copying MarkupSafe.egg-info/not-zip-safe -> build/bdist.linux-x86_64/egg/EGG-INFO
copying MarkupSafe.egg-info/top_level.txt -> build/bdist.linux-x86_64/egg/EGG-INFO
writing build/bdist.linux-x86_64/egg/EGG-INFO/native_libs.txt
creating 'dist/MarkupSafe-1.0-py2.7-linux-x86_64.egg' and adding 'build/bdist.linux-x86_64/egg' to it
removing 'build/bdist.linux-x86_64/egg' (and everything under it)
Creating /home/dspitzer/dev/python/Lonestar/env/lib64/python2.7/dist-packages/site.py
Processing MarkupSafe-1.0-py2.7-linux-x86_64.egg
creating /home/dspitzer/dev/python/Lonestar/env/lib64/python2.7/dist-packages/MarkupSafe-1.0-py2.7-linux-x86_64.egg
Extracting MarkupSafe-1.0-py2.7-linux-x86_64.egg to /home/dspitzer/dev/python/Lonestar/env/lib64/python2.7/dist-packages
Adding MarkupSafe 1.0 to easy-install.pth file

Installed /home/dspitzer/dev/python/Lonestar/env/lib64/python2.7/dist-packages/MarkupSafe-1.0-py2.7-linux-x86_64.egg
Processing dependencies for MarkupSafe==1.0
Finished processing dependencies for MarkupSafe==1.0

Now import flask works, but only if I make sure PYTHONPATH=/home/dspitzer/dev/python/Lonestar/env/lib64/python2.7/dist-packages/.


text:
Q: Store List in SQLite with EntityFramework? I'm trying to run an Add-Migration but I have a property List<string>? and this exception is fired:

System.InvalidOperationException: The entity type 'List' requires a primary key to be defined. If you intended to use a keyless entity type, call 'HasNoKey' in 'OnModelCreating'.

If I change it to: string[]? then:

System.InvalidOperationException: The property 'Profile.AssignedJokes' could not be mapped because it is of type 'string[]', which is not a supported primitive type or a valid entity type. Either explicitly map this property, or ignore it using the '[NotMapped]' attribute or by using 'EntityTypeBuilder.Ignore' in 'OnModelCreating'.

It's just a list of strings, I don't really need an class/entity/table for this. Should I store it as a single string separated by some char? Or is there a solution I'm not aware of.
This is a common SQL thing, or just SQLite?


text:
Q: MySQL Update 'n' number of rows with new info by row[id]? Ok, i have a collection of php files that serve as a web based inventory system. After searching for an item and choosing one from a list, the user is taken to a page that displays the Present quantity for the previously selected items. On that same page, javascript is used to either add or subtract from the present quantity value. I would like to be able to take the updated values in the Present Quantity texboxes, and update them in MySQL.
Note that the number of items displayed varies by the amount selected on the search page.
The following is the update page, where the user can add or subtract from the quantity value:

<title>Update Selections</title>

<?php
    include("menu.php");
    include("sqlconnect.php");

?>

Make Updates:

The following items were selected for quantity update:

Item:
QUANTITY
ADD/SUBTRACT

<form action="updatequantityprocess.php" method="post">
<?php

        //$row_id = $_POST['itemselect'];
        foreach ($_POST['itemselect'] as $confirm)
        {

            $result = mysql_query("SELECT * FROM inventory WHERE id='$confirm'");
            while ($row = mysql_fetch_array($result))
            {
                echo "
" . $row['Item'] . "	";
                echo "<input type='text' id='value' name='itemupdate[]' disabled='disabled' style='text-align: center' value='" . $row['QuaninInventory'] . "'><input type='hidden' value='" . $row['id'] . "' name='itemid[]'>	";
                echo "
<input type='button' value='+' onclick='add(this, 1)'><input type='button' value='-' onclick='add(this, -1)'>

";

            }
        }
        echo "
";
?>

<input type="submit" value="Update">

<INPUT TYPE="BUTTON" VALUE="<-- Back to Results" ONCLICK="window.location.href='http://localhost/Inventory/quantitybybrandprocess.php'">

</form>

I have no idea how to construct the next page, quantityupdateprocess.php, using the itemupdate[] and item[] arrays to update the selected items in the MySQL database.

A: Loop through all of the itemid's with a foreach loop and update each one individually.
foreach($_POST["itemids"] as $itemid){
    //Do mysql update based on other fields (make sure to escape itemid, and the other fields as well, or even better use prepared statements).
}

In order to access the quantity of the current item, do something like this.
foreach($_POST["itemids"] as $i=>$itemid){
    //do mysql updates where $_POST["itemupdate"][$i] is the item update for the item id.
}

A: I'll present it with a simplier approach based on your question's title:
First of all, the mysql extensions use is highly discouraged, instead use PHP PDO.
Example:
$DBH = new PDO('mysql:host=http://yourhost.com;dbname=yourdbname;charset=utf8', 'username', 'password');
$DBH->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

$STH = $DBH->prepare('INSERT INTO `yourtable` (`column1`, `column2`) VALUES (?, ?)');

foreach($array as $value) {
    $STH->bindParam(1, $value);
    $STH->bindParam(2, $value);
    $STH->execute();
}

$DBH = null;

You can use prepared statements which automatically escape all invalid or problematic characters. You can also make a prepared statement and reuse it to insert large series of data while it optimizes the whole process.
You can find more information on phpro.org's PDO tutorial pages. They are pretty well explained.
And regarding your question, in this case you may have to implement something like this:
Let's say that you receive an array of the form id => values[] through the $_POST, so your query would look like this:
$DBH = new PDO('mysql:host=http://yourhost.com;dbname=yourdbname;charset=utf8', 'username', 'password');
$DBH->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

$STH = $DBH->prepare('UPDATE `yourtable` SET `column1` = ?, `column2` = ? WHERE `id` = ?');

foreach($array as $id => $values) {
    $STH->bindParam(1, $values[0]);
    $STH->bindParam(2, $values[1]);
    $STH->bindParam(3, $id);
    $STH->execute();
}


text:
Q: Add a new line to return inside method CODE:
validatePassword(value) {
                if (!value) {
                    return 'This field is required';
                }
                const regex = /^.*(?=.{6,})(?=.*d)(?=.*[A-Z])(?=.*[a-z])(?=.*[!@#$%^&*? ]).*$/i;
                if (!regex.test(value)) {
                    return 'Password must be:\n-Minimum 6 characters\n-Include minimum 1 Uppercase letter\n-Include minimum 1 lowercase letter\n-Include minimum 1 symbol';
                }
                return true;
            },

If you look at the return for the regex test, I am trying to use \n to create a new line, I have tried anything I can think of but cannot get it to give me a new line when the return is called. I cannot remember what the syntax is and its driving me mad! To break it out, this is the specific line I am struggling with
return 'Password must be:\n-Minimum 6 characters\n-Include minimum 1 Uppercase letter\n-Include minimum 1 lowercase letter\n-Include minimum 1 symbol';

A: The new line special character \n only works in Unix systems.
In HTML, you want to use the
 tag to create a new line.
But that means you have to parse your string to html to make it work. You can't specify a new line in a simple string without splitting in to several html tags.
<template>

</template>

Another way to do would be to split your error message so that 1 line is one string. For example, you can set all your error messages to an array, and diplay that array in a ul list.
<template>

{{ error }}

</template>


text:
Q: Kotlin-android-extension communication between Classes similar to Communicating with other Fragments I have 3 Parts to my Project: A Model that does calculations, some Fragments that display the UI and send Trigger to my third part, the main activity. I did all my Fragments with some interfaces like Communicating with Other Fragments.
However now I need one of the part of my Model to trigger some UI changes. And I don't know how to do that. Because my goal is to have one part of my Model send or trigger some functions so that the GUI gets updated but it doesn't know the GUI by itself. (it is totally independent from it)
In Main activity I override all the functions
class MainActivity : AppCompatActivity(), MimaFragment.elementSelectedListener, InstructionFragment.instructionSaveButtonClickedCallback , OptionFragment.optionSaveButtonClickedCallback, MimaFragment.UITrigger{

override fun abortOptions() {
    extendNormal()
}

override fun updateMima() {
    mimaFragment.updateView()
}
override fun normal() {
        mimaFragment.drawArrows()
}}

Fragment exapmle:
class OptionFragment : Fragment() {
var optionCallback : optionSaveButtonClickedCallback? = null

interface optionSaveButtonClickedCallback{
        fun updateMima()
        fun abortOptions()
    }

override fun onViewCreated(view: View?, savedInstanceState: Bundle?) {
        view?.findViewById(R.id.optionsAbort)?.setOnClickListener{

            optionCallback?.abortOptions()
        }
    }

override fun onAttach(context: Context?) {
        super.onAttach(context)
        try {
            optionCallback = context as optionSaveButtonClickedCallback
        } catch (e : ClassCastException){
            throw ClassCastException(activity.toString() + " must implementoptionSaveButtonClickedCallback")
        }
    }
}

That is how you usually do it and it works fine. Now to my Question is there a way to do it just like that for a non Fragment class? I tryed it like this:
class MimaModul(name: String, description : String, context: Context) : Element(name, description) {
 val uiTrigger : UITrigger? = null

init{
   try {
     uiTrigger = context as UITrigger
   } catch (e : ClassCastException){
     Log.d("ClassCastException","Didn't implement uiTrigger")
     }
}

 fun step(){
 //it does some stuff here and then calls for example
    uiTrigger?.normal()
 }

interface UITrigger{
   fun normal()
}
}

However as I expected the UITrigger cast does not work. (it always catches an exception) Do you have any ideas how to solve this. Or how else to do it?
ideally I want MimaFragment to implement the interface. But that didn't work either.
class MimaFragment : Fragment(), MimaModul.UITrigger {
//other stuff
override fun normal() {
        drawArrows()
    }
}

So when ever my Model is done with a step it should trigger some UI change. And I tryed to avoid just doing a loop and update all Elements based on their status because that would take forever. (Though I see this as my only options at the moment)
Let me know if I was unclear and i shall elaborate.


text:
Q: Conditional default route in Angular.js How to make Angular.js to go to /route1 by default if the $rootScope.isAdmin==true, but if isAdmin is false or does not exist - go to /route2 ?
isAdmin is set in a login controller:
.controller(
  'LoginController',
['$scope', '$rootScope', '$http', 'authService',
  ($scope, $rootScope, $http, authService) ->
    $scope.submit = ->
      try
        $http.post("/users/sign_in",
          user:
            email: @username
            password: @password
            remember_me: if @remember_me then 1 else 0
        ).success (response) ->
          $rootScope.isAdmin = response[0].is_admin
          authService.loginConfirmed()
      catch ex
        alert ex
])


text:
Q: Ember. Keep selections from dropdown menu when user refreshes website I have a dropdown menu in an ember component. When the user selects an option, the component sends an action to the route, and the route changes an attribute in a controller and makes a transitionToRoute to a different url.
Example:
rootpath= www.example.com
User selects candy. Url => www.example.com/candy
After candy,User selects kitkat. => www.example/candy/kitkat.
If the user refreshes the website or shares the url, the dropdown menu appears unselected.
I know that using query params fixes this, but I don't want to use query params.
Any idea how can I do this?
Thanks!

A: You could use window.location on initialization. And extract last part out of it. Then find the following from you select data and set it as selection.
Something like this
....
this._super(...arguments);
var fullURL = window.location.href; // www.example.com/candy
var splittedURL = fullURL.split('/');
var lastPart = Ember.get(splittedURL, 'lastObject'); // candy.
var chocolateData = this.get('selectMenuContent');
var toSetOnInit = chocolateData.findBy('value', lastPart);
this.set('myChocolateSelection', toSetOnInit);
...


text:
Q: How to clean up unnecessary file inside wp-content/plugins/wordpress-seo? I currently maintaining 7 years of Wordpress site. Disk usage are recently full, so I need to check automatic back up regularly and save those back up,  and delete it from the server.
And when I check, that wordpress-seo folder inside plugins folder (which is Yoast Seo default plugin folder) are taking too much space. All I know, it's full of that plugins file from various version. To be precise, it's inside js/dist folder of wordpress-seo plugin.
It is containing several type of minified javascript with some kind of sequence or version number at the end of each name, with a total around 250-300 MB.
Can I clean up those file? If yes, is it safe? What might be the worse case I will face if I delete all of those each type from previous version, and just keep like 3 newest version?

A: 250-300MB is really a lot and I'm not sure if that is a normal situation. I'd suggest you to check how was that site maintained and managed. Maybe the updates were not made correctly (for example plugins were not updated and only overwritten using FTP).
And back to your question... The easiest way to clean these files would be to:

*

*Download original, current version from Plugin Repo: https://wordpress.org/plugins/wordpress-seo/

*Login to your FTP server and go to wp-content/plugins/

*Rename wordpress-seo folder

*Upload original folder from downloaded package

*Remove old (renamed) folder.


text:
Q: removing parts of an air core transformer field I sometimes need air core transformers for contactless energy transfer of small powers (usually less then 1 watt).  However, on rotating machines, sometimes a bearing is needed in proximity of the energy transformer. The bearing than gets some coupling to the transformers field and as it's steel just forms a shorted winding, consumes some energy.
Now I have the case of a larger bearing, spanning about half of the transformer coils plane. Obviously, it will short out much of the energy transmitted.
I wonder if it would be possible to remove the inner part of the field, by adding some reversed windings of the bearing diameter to the primary coil. The primary field would then be constricted to the outer part of the primaries core area I guess, leaving the bearing uncoupled. But how many windings would that take? The same amount as there are forward windings in the outer coil?
The situation is most likely this:

red: coils, grey: interfering metal, non-metal parts omitted.

A: I have to tackle similar problems on rotating machines - sending power and receiving data. Do you use power resonant coils? That's the first question. What sort of power transmission frequency do you use? Steel doesn't have to act like a shorted turn and if it does, it won't completely kill the mag field - with resonance you can re-tune and use the metal as part of the tuned circuit.
Trying to cancel parts of the magnetic field is a fruitless task - Sometimes I use ferrites when the metal (such as stainless with poor conductivity) is heating up too much. Normal steel is better but it still has losses and ferrite does the job of masking areas that would otherwise drain all the energy.
Some diagrams/pictures would help but the above are my thoughts to start off with.

A: I second Andy aka for the idea of ferrite.
It can both shield the magnetic field and increase the coupling between the two circuits (static and rotating). In the figure below, a magnetic field line is given in red.


text:
Q: Illegal XML Characters When Declaring XML Variable In SQL The Problem
I am attempting to declare an XML variable and and set it equal to this XML file within my SQL query like this: DECLARE @x XML = 'xml content here';.
However, when I try to do this with my current XML file, I get this error message printed to my screen:
Msg 9420, Level 16, State 1, Line 1
XML parsing: line 1132, character 265, illegal xml character
Ways I've Already Tried To Solve It

*

*I've tried to escape the single quotes by replacing all the single quotes in the XML file with two single quotes and then copying into the query. No luck.

*I've tried taking out the ampersands, but that doesn't seem to work. Near where the error is detected by SQL, there don't seem to be any special characters. No luck again.

The Question
It seems to me that single quotes aren't the problem. I am having trouble finding exactly what the illegal character is, how I filter these characters out. Maybe importing the XML file from an external file and setting the contents equal to the variable instead of heard coding it will solve the issue. How would this work? I am also aware that single quotes have to be replaced by two single quotes. I did that, but I still have the exact same problem. Any help understanding the issue is appreciated.
System Parameters

*

*MS SQL Server Management Studio

*Windows Server 2012 R2 Standard

The Full Code
Here's the full code that I'm executing that's giving me the error:
DECLARE @x XML = ' copy xml file here... ';

With MyPersonCTE AS
(
    SELECT ROW_NUMBER() OVER(ORDER BY (SELECT NULL)) AS PersonID
          ,p.value('FirstName[1]','varchar(max)') AS FirstName
          ,p.value('LastName[1]','varchar(max)') AS LastName
          ,p.value('Biography[1]','varchar(max)') AS Biography
          ,p.value('Expertise[1]','varchar(max)') AS Expertise
          ,p.value('Image[1]','varchar(max)') AS Image
          ,p.value('Link[1]','varchar(max)') AS Link
          ,p.query('Books') AS BookNode
          ,p.query('Articles') AS ArticleNode
          --same for Papers, Artwork...
    FROM @x.nodes('/People/Person') AS A(p)
)
,MyBooksCTE AS
(
    SELECT MyPersonCTE.*
          ,ROW_NUMBER() OVER(ORDER BY (SELECT NULL)) AS BookID
          ,x.value('Year[1]','int') AS BookYear
          ,x.value('Details[1]','varchar(max)') AS BookDetails
    FROM MyPersonCTE
    CROSS APPLY MyPersonCTE.BookNode.nodes('/Books/Book') A(x)
)
,MyArticlesCTE AS
(
    SELECT MyPersonCTE.*
          ,ROW_NUMBER() OVER(ORDER BY (SELECT NULL)) AS ArticleID
          ,x.value('Year[1]','int') AS ArticleYear
          ,x.value('Details[1]','varchar(max)') AS ArticleDetails
    FROM MyPersonCTE
    CROSS APPLY MyPersonCTE.ArticleNode.nodes('/Articles/Article') A(x)
)
--same for Papers, Artwork...
SELECT p.*
      ,b.BookID
      ,b.BookYear
      ,b.BookDetails
      ,a.ArticleID
      ,a.ArticleYear
      ,a.ArticleDetails
INTO #tempAllData
FROM MyPersonCTE AS p
LEFT JOIN MyBooksCTE AS b ON p.PersonID=b.PersonID
LEFT JOIN MyArticlesCTE AS a ON p.PersonID=a.PersonID ;

--#tempAllData is now filled with all data, copied in all combination: much to much
--but DISTINCT is your friend
--in this case you'd use the PersonID as FK in all related tables

SELECT DISTINCT PersonID,FirstName,LastName,Biography,Expertise --other fields
FROM #tempAllData;

SELECT DISTINCT PersonID,BookID,BookYear,BookDetails
FROM #tempAllData;

SELECT DISTINCT PersonID,ArticleID,ArticleYear,ArticleDetails
FROM #tempAllData;

DROP TABLE #tempAllData;

A: Look, this is a reduced example to reproduce the error
In this snippet you've got twice the name "O'Brien" where the ' makes troubles
And here "Experiencing physical warmth promotes interpersonal warmth" the opening and closing qoutes are problematic
DECLARE @x XML=
'<?xml version="1.0" encoding="UTF-8"?>
<People>
<Person>
    <FirstName>Katherine</FirstName>
    <LastName>Corker</LastName>
    <Articles>

            <Year></Year>
            <![CDATA[
Corker, K. S., Lynott, D., Wortman, J., Connell, L., Donnellan, M. B., Lucas, R. E., & O'Brien, K. (2014). High quality direct replications matter: Response to Williams (2014). Social Psychology, 45, 324-326. Available here.

Lynott, D., Corker, K. S., Wortman, J., Connell, L., Donnellan, M. B., Lucas, R. E., & O'Brien, K. (2014). Replication of "Experiencing physical warmth promotes interpersonal warmth" by Williams & Bargh (2008, Science). Social Psychology, 45, 216-222. Available here.
]]>

            </Articles>
</Person>
</People>';
SELECT @x;

And now just change this
'<?xml version="1.0" encoding="UTF-8"?>

to this (don't forget the "N" in the beginning to force this to Unicode)
N'<?xml version="1.0" encoding="UTF-16"?>

But just try this:
DECLARE @yourXML AS XML=
(
SELECT CONVERT(XML, BulkColumn,2) AS BulkColumn
FROM OPENROWSET(BULK 'X:\Path2file\faculty-xml.xml', SINGLE_BLOB) AS x
);
SELECT @yourXML;

With this you do not have to bother about encondings, you just read the file from a location on the disk...


text:
Q: Java Personal Linked List So I am creating a linked list without using the built in one. I have a bunch of methods for my assignment that I need to make work. I have everything working up to removing elements from the LL. I don't really need (although wouldn't mind) a fully functioning method, I just need to know what my steps would be. Here is my code:
public class MoveToFrontList {

    private StringCountElement head; // the head reference
    private StringCountElement tail; // the tail reference
    private int size; // the size of the list (number of valid items)

    /**
     * _Part 1: Implement this constructor._
     *
     * Creates a new, initially empty MoveToFontList. This list should be a
     * linked data structure.
     */
    public MoveToFrontList() {
        head = new StringCountElement();        //allocating memory for head
        tail = head;            //replicating head onto tail
        //head.next = tail;     //making pointer of next from head to tail
        //tail.prev = head;     //making pointer of prev from tail to head
    }

    /**
     * This method increments the count associated with the specified string
     * key. If no corresponding key currently exists in the list, a new list
     * element is created for that key with the count of 1. When this method
     * returns, the key will have rank 0 (i.e., the list element associated with
     * the key will be at the front of the list)
     *
     * @param key
     *            the string whose count should be incremented
     * @return the new count associated with the key
     */
    public int incrementCount(String key) {
        StringCountElement s = find(key);
        if (s != null) {
            // found the key, splice it out and increment the count
            spliceOut(s);
            s.count++;
        } else {
            // need to create a new element
            s = new StringCountElement();
            s.key = key;
            s.count = 1;
        }
        // move it to the front
        spliceIn(s, 0);
        return s.count;
    }

    /**
     *
     * @return the number of items in the list
     */
    public int size() {
        return size;
    }

    /**
     * _Part 2: Implement this method._
     *
     * Find the list element associated with the specified string. That is, find
     * the StringCountElement that a key equal to the one specified
     *
     * @param key
     *            the key to look for
     * @return a StringCountElement in the list with the specified key or null
     *         if no such element exists.
     */
    public StringCountElement find(String key) {
        StringCountElement temp = head;     //creating a temp object to evaluate

        for(int i = 0; i <= size(); i++){
            if(temp.key == null){
                return null;
            }
            if(temp.key.equals(key)){
                return temp;
            }
            if(temp.next != null) {
                temp = temp.next;
            }
        }

        return null;            //returning null since no object with the right key was found
    }

    /**
     * _Part 3: Implement this method._
     *
     * Compute the rank of the specified key. Rank is similar to position, so
     * the first element in the list will have rank 0, the second element will
     * have rank 1 and so on. However, an item that does not exist in the list
     * also has a well defined rank, which is equal to the size of the list. So,
     * the rank of any item in an empty list is 0.
     *
     * @param key
     *            the key to look for
     * @return the rank of that item in the rank 0...size() inclusive.
     */
    public int rank(String key) {
        int rank = 0;
        StringCountElement temp = head;

        do{
            if(temp.key == null){
                return size();
            }
            if(temp.key.equals(key)) {
                return rank;
            }
            if(temp.next != null) {
                temp = temp.next;
            }
            rank++;
        } while(temp.next != null);
        return size();
    }

    /**
     * _Part 4: Implement this method._
     *
     * Splice an element into the list at a position such that it will obtain
     * the desired rank. The element should either be new, or have been spliced
     * out of the list prior to being spliced in. That is, it should be the case
     * that: s.next == null && s.prev == null
     *
     * @param s
     *            the element to be spliced in to the list
     * @param desiredRank
     *            the desired rank of the element
     */
    public void spliceIn(StringCountElement s, int desiredRank) {
        StringCountElement temp = head;

        for(int i=0; i < desiredRank; i++){            //reaching desired rank location
            temp = temp.next;
        }

        if(desiredRank == 0){
            head = s;
            size++;
            return;
        }
        //temp will be the spot that s will take over
        s.next = temp;      // pointing element after s to temp
        s.prev = temp.prev; // pointing previous element before s to be previous element before temp
        temp.prev.next = s; // pointing element before temp to s element
        temp.prev = s;      // pointing previous element before temp to be s
        size++;

        return;
    }

    /**
     * _Part 5: Implement this method._
     *
     * Splice an element out of the list. When the element is spliced out, its
     * next and prev references should be set to null so that it can safely be
     * splicedIn later. Splicing an element out of the list should simply remove
     * that element while maintaining the integrity of the list.
     *
     * @param s
     *            the element to be spliced out of the list
     */
    public void spliceOut(StringCountElement s) {

        return;
    }

}

So I need help with Part 5. Things I know so far, I will need test cases for the first and last element in the LL. Also I think this assignment requires that the head and tail are used, not as empty references.
I also know that the splicein method also needs a test case for the last element. Aside from that is there any recommendation on simplifying and/or cleaning up my code? Any help is appreciated! Thank you!
EDIT: This is what an element contains:
/**
 * A Container class for a doubly linked data structure that
 * stores String keys and associated integer counts.
 */
public class StringCountElement {
    public StringCountElement next;
    public StringCountElement prev;
    public String key;
    public int count;

}

A: The steps that are needed are as below.

*

*Find the element that you need to splice out, let's assume it is
current

*Store the previous and next element in temporaries.

*Set previous.next to next

*Set next.previous to previous Set
current.previous = current.next = null

A: So I did some heavy overhauling to my code. If you guys want to see the updated code, let me know. Anyways, here is my updated spliceOut method, for part 5:
public void spliceOut(StringCountElement s) {
        //checking if only one element in list.
        //if so, then head and tail are the references to that element
        if(size == 1){
            head = null;
            tail = null;
        }
        //if s.prev is null, then that means s is at the beginning of list. so head == s
        if(s.prev == null){
            head = s.next;          //making head reference equal the next element in the list
            head.prev = null;       //since head is equal to element two, erasing head.prev
                                    // pointer will not show first element in the list
        }
        //if s.next is null, then s is the last element in list. So tail == s
        else if(s.next == null){
            tail = s.prev;          //making tail reference equal to element before tail
            tail.next = null;       //making original last tail element null'd out of list
        }
        //s is not at the beginning or end of list
        else{
            s.prev.next = s.next;   //making prev element before s point to element after s
            s.next.prev = s.prev;   //making next element after s point to element before s
        }

        //making pointers of s not point to any other elements
        s.prev = null;
        s.next = null;
        size--;     //since an element was taken out of the list, size of list is reduced by one

        return;
    }

I am confused though, what to do when there is only one element in the list. If there is only one element in the list, isn't the head and tail reference both pointing to that element? So if I wanted to remove that element out of the list, shouldn't I set head and tails to null?


text:
Q: Using @ prefix for variable name In my domain model I have an Event entity. This means that I have to sometimes declare variables as: @event since event is a reserved key word.
I've read on a few stack overflow posts (like What's the use/meaning of the @ character in variable names in C#?) that this is not recommended unless you're interacting with other programming languages. My question is why is it not recommended? What is the issue with using @?
I could use an "Occasion" entity instead but that would mean in my UI layer I would have events which maps to occasions?

A: What you're trying to do is the entire purpose of the @ prefix to prevent name clashes.
But this text from MSDN says everything you're asking:

The prefix "@" enables the use of keywords as identifiers, which is
useful when interfacing with other programming languages. The
character @ is not actually part of the identifier, so the identifier
might be seen in other languages as a normal identifier, without the
prefix. An identifier with an @ prefix is called a verbatim
identifier. Use of the @ prefix for identifiers that are not keywords
is permitted, but strongly discouraged as a matter of style.

Source
So it just comes down to style, in your case it's the right solution if you don't want to rename your entity.


text:
Q: Php character count without spaces and html tags I want to count characters in a text like Microsoft Word.

Lorem Ipsum is simply dummy text of the printing and typesetting industry.Tom's farm. 12th century.

12th -> 'th' is a special character, under the number 12.
How can I do that in PHP?

A: My solution is;
    $content = 'Some Text...';

    $trim = strip_tags($content);
    $trim=str_replace([" ","\n","\t","–","’","'","""," "], '', $trim);

    $totalCharacter = strlen(utf8_decode($trim));

A: $string = "
Lorem Ipsum is simply dummy text of the printing and typesetting industry.Tom's farm. 12th century.
";
$string = strip_tags($string);
$string = preg_replace("/\s/", "", $string);
$character_count = strlen($string);

If there is a th Unicode character, strlen will probably count it as two characters. Then you should maybe have a look on mb_strlen.


text:
Q: Spring's AspectJ-mode caching versus AspectJ-mode transactions My question relates to Spring's AspectJ mode and especially how to enable it for:

*

*Transaction management

*Caching

1) I noticed that in order to enable the AspectJ mode for transaction management, I only had to do the following:
@Configuration
@EnableTransactionManagement(mode = AdviceMode.ASPECTJ)

2) Whereas in order to use AspectJ mode for caching it seems one has to:
-Put the following jar into Tomcat's lib directory: org.springframework:spring-instrument-tomcat
-Add the following line in Tomcat's server.xml:
<Loader loaderClass="org.springframework.instrument.classloading.tomcat.TomcatInstrumentableClassLoader"/>

-Add the following configuration:
@Configuration
@EnableLoadTimeWeaving(aspectjWeaving = AspectJWeaving.ENABLED)
public class LoadTimeWeavingConfiguration implements LoadTimeWeavingConfigurer {
    @Override
    public LoadTimeWeaver getLoadTimeWeaver() {
        return new ReflectiveLoadTimeWeaver();
    }
}

-to finally be able to use the AspectJ mode as follows:
@Configuration
@EnableCaching(mode = AdviceMode.ASPECTJ)

Is the above right? If so why is AspectJ-mode caching different from AspectJ-mode transaction support?

A: The extra configuration you listed for the @EnableCaching case is not any more needed than in the case of @EnableTransactionManagement. If you choose mode = AdviceMode.ASPECTJ it just means that it will use AspectJ instead of CGLIB proxies for the transaction management / cache functionality. If you have compile-time weaving enabled with spring-aspects-<version>.jar listed as an aspect library, it should work out of the box (given all other required transaction management / cache configuration related beans are available in the application context). If you're not using compile-time weaving but choose instead to go with load-time weaving, having -javaagent:/path/to/aspectjweaver-<version>.jar on the command line as a JVM argument is enough. The ReflectiveLoadTimeWeaver and TomcatInstrumentableClassLoader are only required in case no compile-time weaving is used in your build and a load-time weaving agent is not present in the VM, and you still want to have load-time weaving via classloading.


text:
Q: iOS view/controller lifecycle callback on screen unlock or app switch Is there any function which is get called on view or controller when the user unlocks the phone or comes back to the app? Registering for notifications on app coming to foreground seems to be hacky for me, so I expected something like viewDidLoad or viewDidAppear to be called, but they aren't.
My view has different states, and in one of them it runs a timer (with UI indicating that appropriately). After the timer is fired the view makes some calls to server and updates the UI. Seems like after unlock the NSTimer is continuing from the place the phone was locked, however I would like to refresh it's state, check the timeout left with server and run the timer from correct value (or show "normal" UI if the timeout is already over). I just cannot find a callback which is called for me by the system when it comes back to the app.

A: The proper solution is to have the view controller register with NSNotificationCenter for the appropriate app lifecycle notification such as UIApplicationDidBecomeActiveNotification or UIApplicationWillEnterForegroundNotification.
Remember, these are app events, not view events which is why there are no standard methods in UIViewController or UIView for these.


text:
Q: Stream Analytics UDF - using the output from one UDF in another The following code results in my GT2HP value being null in the follow on UDFs:
SELECT
    UDF.GT2HP(Collect()) as GT2HP,
    UDF.LPLPReturns(Collect()) as LPLPReturns,
    UDF.LPGasHeater(Collect()) as LPGasHeater,
    UDF.HPRaisedSW(Collect(), AVG(GT2HP)) as HPRaisedSW,
    UDF.HPCustomerDemand(Collect(), AVG(GT2HP)) as HPCustomerDemand
INTO SQLDWUKSTEAMLOSS
FROM IotHubInput
WHERE IoTHub.ConnectionDeviceId = 'uk-iotedge'
GROUP BY TumblingWindow(second, 60)

The following code works:
SELECT
    UDF.GT2HP(Collect()) as GT2HP,
    UDF.LPLPReturns(Collect()) as LPLPReturns,
    UDF.LPGasHeater(Collect()) as LPGasHeater,
    UDF.HPRaisedSW(Collect(), UDF.GT2HP(Collect())) as HPRaisedSW,
    UDF.HPCustomerDemand(Collect(), UDF.GT2HP(Collect())) as HPCustomerDemand
INTO SQLDWUKSTEAMLOSS
FROM IotHubInput
WHERE IoTHub.ConnectionDeviceId = 'uk-iotedge'
GROUP BY TumblingWindow(second, 60)

Obviously the second code is way more computationally expensive than the first and I'd like to avoid it if possible.
I'd like to use the output of the first UDF in my follow on UDFs, but it seems to pass on null. All the select statements appear to execute in parallel not serial, which probably explains the null.
Is there a way to use the output of one UDF in another UDF?

A: You can write it as two statements. First one selects Collect() and avg() with a group by. Second select uses the results to call UDF.

A: The reason that GT2HP column referenced in the AVG(GT2HP) is always null is due to the SQL semantics.
Columns in the SELECT clause can only refer to sources referenced in FROM, and since there is no IotHubInput.GT2HP - it is interpreted as null.
If you separate your query into multiple steps, as Vignesh suggested you will end up with the first step just computing the COLLECT over the 60 sec window:
SELECT Collect() AS c
WHERE IoTHub.ConnectionDeviceId = 'uk-iotedge'
FROM IotHubInput
GROUP BY TumblingWindow(second, 60)

Let's name it step1. Now, since you are grouping only by a window, you will have just one value of column c every 60 sec.
Any aggregation over this is not necessary unless you increase the size of the window to aggregate more than one value...
So the AVG in the AVG(GT2HP) is unnecessary.
The second step then will be:
SELECT
    c,
    GT2HP = UDF.GT2HP(c)
FROM step1

Let's call this step step2.
Now the final selection will be:
SELECT
    GT2HP,
    UDF.LPLPReturns(c) as LPLPReturns,
    UDF.LPGasHeater(c) as LPGasHeater,
    UDF.HPRaisedSW(c, GT2HP) as HPRaisedSW,
    UDF.HPCustomerDemand(c, GT2HP) as HPCustomerDemand
INTO SQLDWUKSTEAMLOSS
FROM step2

And putting it all together:
WITH step1 AS (
    SELECT Collect() AS c
    WHERE IoTHub.ConnectionDeviceId = 'uk-iotedge'
    FROM IotHubInput
    GROUP BY TumblingWindow(second, 60)
),
step2 AS (
    SELECT
        c,
        GT2HP = UDF.GT2HP(c)
    FROM step1
)

SELECT
    GT2HP,
    UDF.LPLPReturns(c) as LPLPReturns,
    UDF.LPGasHeater(c) as LPGasHeater,
    UDF.HPRaisedSW(c, GT2HP) as HPRaisedSW,
    UDF.HPCustomerDemand(c, GT2HP) as HPCustomerDemand
INTO SQLDWUKSTEAMLOSS
FROM step2


text:
Q: How to merge module in dll project and define .def file I have a code of dll which were created by MS Visual Studio 6.0 and and quite old build environment and it contain various modules in it,and platform was Pocket PC 2003(ARMV4).
Now I have to convert the solution platform at WIN32 on vs2008.So first I have to convert all the module(all the subproject were static library in vc++) in vs2008.and now we have to merge all the module in one project(dll).So how to merge all the project and how to define single .def file for the main project.


text:
Q: UICollectionView made by code not showing cells I have a main ViewController with multiple views made with the Storyboard. When the client clicks on a cell, a popup with another UICollectionView inside of it should display.
The second view is created by code in ViewDidLoad, but displays only when the client clicks on a cell from the first view (which was made in the Storyboard).
The view displays on top of everything, with an image on top and a label. The CollectionView is also there, but is missing the cell. I used breakpoints and it never updates the cells.
Your help would really be welcome.
in the AirLineViewController.cs
UIImageView cardLogo;
    UILabel cardTitle;
    List<UIImage> cardImages;
    List<string> cardLabels;
    UICollectionView cardView;
    CGRect cardFrame;
    UICollectionViewLayout cardViewLayout;
    List<CardCellData> cardCellData;
    CardSource cardSource;

in the ViewDidLoad i call my function initCardView();
private void initCardView()
    {
        cardFrame = new CGRect(10f,
            UIScreen.MainScreen.Bounds.Height * 0.2f,
            UIScreen.MainScreen.Bounds.Width - 20f,
            UIScreen.MainScreen.Bounds.Height * 0.6f);

        creditCardView = new UIView(cardFrame);
        creditCardView.BackgroundColor = UIColor.White;

        cardTitle = new UILabel(new CGRect(40, 0, 100, 35));
        cardTitle.MinimumFontSize = 20f;
        cardTitle.Text = "Air Canada";

        cardLogo = new UIImageView(new CGRect(2, 2, 35, 35));
        cardLogo.ContentMode = UIViewContentMode.ScaleAspectFit;
        cardLogo.Image = UIImage.FromFile("temp/airline_ac");

        cardCellData = new List<CardCellData>();
        cardCellData.Add(new CardCellData(UIImage.FromFile("temp/AirCanada"), "un"));
        cardCellData.Add(new CardCellData(UIImage.FromFile("temp/AirCanada"), "deux"));
        cardCellData.Add(new CardCellData(UIImage.FromFile("temp/AirCanada"), "trois"));
        cardCellData.Add(new CardCellData(UIImage.FromFile("temp/AirCanada"), "quatre"));
        cardSource = new CardSource(cardCellData, this);

        //CView
        cardViewLayout = new UICollectionViewLayout();
        cardView = new UICollectionView(new CGRect(2f,
            45f,
            cardFrame.Width - 4f,
            cardFrame.Height - 50f), cardViewLayout);

        cardView.BackgroundColor = UIColor.White;

        cardView.RegisterClassForCell(typeof(CardCell), (NSString)CardCell.CELLID);
        cardView.DataSource = cardSource;
        cardView.ReloadData();

        creditCardView.AddSubview(cardTitle);
        creditCardView.AddSubview(cardLogo);
        creditCardView.AddSubview(cardView);

        cardView.ReloadData();
    }

the function to call in order to display the view
 public void displayCardView(int itemIndex)
    {
        //cardView.Source = new CardSource(cardCellData, this);
        this.Add(creditCardView);
        //cardView.ReloadData();
    }

the class CardSource
internal class CardSource : UICollectionViewSource
{
    protected List<CardCellData> items;
    protected NSString cellIdentifier = (NSString)CardCell.CELLID;
    AirLineViewController airLineViewController;

    public CardSource(List<CardCellData> items, AirLineViewController airLineViewController)
    {
        this.items = items;
        this.airLineViewController = airLineViewController;

    }

    public override UICollectionViewCell GetCell(UICollectionView collectionView, NSIndexPath indexPath)
    {
        var cell = (CardCell)collectionView.DequeueReusableCell((NSString)CardCell.CELLID, indexPath);

        //cell.img.Image = items[indexPath.Row].image;
        //cell.footerLabel.Text = items[indexPath.Row].footer;

        cell.updateCell(items[indexPath.Row].image, items[indexPath.Row].footer);

        return cell;
    }

    public override nint GetItemsCount(UICollectionView collectionView, nint section)
    {
        return items.Count;
    }

    public override nint NumberOfSections(UICollectionView collectionView)
    {
        return 1;
    }

    public override void ItemSelected(UICollectionView collectionView, NSIndexPath indexPath)
    {
        airLineViewController.displayCardView(indexPath.Row);
        //collectionView.DeselectItem(indexPath, true);
    }
}

the CardCellData class
public class CardCellData
{
    public UIImage image;
    public string footer;

    public CardCellData(UIImage image, string footer)
    {
        this.image = image;
        this.footer = footer;
    }
}

and finally the CardCell class
public class CardCell : UICollectionViewCell
{
    public UIImageView img;
    public UILabel footerLabel;
    public CGRect rect;
    public const string CELLID = "cardViewCell";

    [Export("initWithFrame:")]
    public CardCell(System.Drawing.RectangleF frame) : base(frame){
        this.Initialize();
    }

    public void updateCell(UIImage image, string footer)
    {
        //img = new UIImageView(image);
        img.Image = image;
        footerLabel.Text = footer;
    }

    private void Initialize()
    {

        rect = new CGRect(0f, 0f, 80f, 70f);
        //BackgroundView = new UIView { BackgroundColor = UIColor.Green };

        //ContentView.BackgroundColor = UIColor.White;
        // this.BackgroundView.Frame = rect;
        //this.SelectedBackgroundView.Frame = rect;
        //this.ContentView.Frame = rect;

        img = new UIImageView(UIImage.FromFile("Flag/Flag_0"));
        img.Center = ContentView.Center;
        img.ContentMode = UIViewContentMode.ScaleAspectFit;
        img.Image = UIImage.FromFile("Flag/Flag_0");
        //img.AutoresizingMask = ~UIViewAutoresizing.None;

        footerLabel = new UILabel(new CGRect(0f, 50f, 80f, 70f));

        this.ContentView.AddSubview(img);
        this.ContentView.AddSubview(footerLabel);;
    }
}