text:
Q: No Gradle "build" task despite build.gradle applying plugin com.android.application Somehow I don't have a build task:
$ ./gradlew tasks --all
:tasks

------------------------------------------------------------
All tasks runnable from root project
------------------------------------------------------------

Build Setup tasks
-----------------
init - Initializes a new Gradle build. [incubating] [wrapper]
wrapper - Generates Gradle wrapper files. [incubating]

Help tasks
----------
components - Displays the components produced by root project 'apps-android-commons'. [incubating]
dependencies - Displays all dependencies declared in root project 'apps-android-commons'.
dependencyInsight - Displays the insight into a specific dependency in root project 'apps-android-commons'.
help - Displays a help message.
model - Displays the configuration model of root project 'apps-android-commons'. [incubating]
projects - Displays the sub-projects of root project 'apps-android-commons'.
properties - Displays the properties of root project 'apps-android-commons'.
tasks - Displays the tasks runnable from root project 'apps-android-commons'.

BUILD SUCCESSFUL

Despite my commons/app/build.gradle that applies (as described in this other QA) a relevant plugin:
apply plugin: 'com.android.application'

dependencies {
    compile fileTree(include: '*.jar', dir: 'libs')
    compile 'fr.avianey.com.viewpagerindicator:library:2.4.1.1@aar'
    compile 'in.yuvi:http.fluent:1.3'
    compile 'com.android.volley:volley:1.0.0'
    compile 'com.nostra13.universalimageloader:universal-image-loader:1.8.4'
    compile 'ch.acra:acra:4.5.0'
    compile 'org.mediawiki:api:1.3'
    compile 'commons-codec:commons-codec:1.10'
    compile 'com.android.support:support-v4:23.4.0'
    compile 'com.android.support:appcompat-v7:23.4.0'
    compile 'com.android.support:design:23.4.0'

    //noinspection GradleDependency - old version has required feature
    compile 'com.google.code.gson:gson:1.4'
}

android {
    compileSdkVersion 23
    buildToolsVersion "23.0.3"

    useLibrary  'org.apache.http.legacy'

    defaultConfig {
        applicationId "fr.free.nrw.commons"
        minSdkVersion 11
        targetSdkVersion 23

        ndk {
            moduleName "libtranscode"
        }
    }

    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.txt'
        }
    }

    lintOptions {
        disable 'MissingTranslation'
        disable 'ExtraTranslation'
    }
}

QUESTION: Why is that, am I doing something wrong?
Here is my project structure:
ROOT
 /commons
   /app

... and I execute ./gradlew in ROOT.

A: If your folder is:
ROOT
 /commons
   /app

... then execute .gradlew in the commons folder, not in ROOT.
Thanks @Opal for the tip!


text:
Q: 1st datatable breaking 2nd datatable I have well functioning datatable(1st) on one page of my webapp and decided to make another datatable(2nd) on a different page.  A portion of the js/jquery associated with the 1st datatable, when commented out, allows the 2nd table to function properly. When not commented out the table returns "Showing 0 to 0 of 0 entries" as if someone were to have searched for something not at all contained in the table. I've resorted to even using the exact example html/jquery that they use in the initial example on datatables.net and still have issues.
Below is the code pertaining to the 1st table that when commented out allows the 2nd datatable to function fully.
    $(document).ready( function () {

  /* Custom filtering function which will search data in column four between two values */
$.fn.dataTable.ext.search.push(
    function( settings, data, dataIndex ) {
        var min = $('#min').val();
        var max = $('#max').val();
        var date =  data[4]; // use data for the age column

        if ( ( min == '' && max == '' ) ||
             ( min == '' && date <= max ) ||
             ( min <= date && '' == max ) ||
             ( min <= date && date <= max ) )
        {
            return true;
        }
        return false;
    }
);

  var table = $('#datat').DataTable();

   // Event listener to the two range filtering inputs to redraw on input
        $('#min, #max').keyup( function() {
            table.draw();
        } );
} );

I'm not sure what in the above code might be breaking my 2nd datatable.

A: if #min and #max doesn't exists your filter wont work, add this to handle this case:
if( $('#min').length == 0 || $('#max').length == 0)
    return true

redpajama_set_name: RedPajamaStackExchange


text:
Q: How does this Python Generator work? Can someone please explain what this generator code is doing?
>>> def f():
...     return next((i for i in [{'a':1, 'b':2}, {'c':3, 'd':4}]))
...
>>> t = f()
>>> for item in t:
...     print(item)
...
a
b
>>> t
{'a': 1, 'b': 2}
>>>

Actually, is this function designed to return only a single value?

A:
Can someone please explain what this generator code is doing?

(i for i in [{'a':1, 'b':2}, {'c':3, 'd':4}])

This is the syntax for a generator comprehension. Try iterating over it like this:
In [205]: for x in (i for i in [{'a':1, 'b':2}, {'c':3, 'd':4}]):
 ...:     print(x)
 ...:
{'b': 2, 'a': 1}
{'d': 4, 'c': 3}

The next() function returns the next item from the generator. From the documentation of next:

next(iterator[, default])
Retrieve the next item from the iterator by calling its next() method.
  If default is given, it is returned if the iterator is exhausted,
  otherwise StopIteration is raised.

In this case, what is returned is
{'a':1, 'b':2}

This is a dictionary. If you use a for loop on this as you do, you iterate over the keys, so you print out a, and b in turn (if you're on python3.6) because the order of keys is guaranteed. On older python versions, you will print the keys in some arbitrary order.

Actually, is this function designed to return only a single value?

Yes it is. As an exercise, try changing return to yield from, like this:
def f():
    yield from (i for i in [{'a':1, 'b':2}, {'c':3, 'd':4}]))


text:
Q: Drawing attention to unanswered questions by new users I have been using Stack Overflow for a couple weeks now as an active member and have previously been aware of the site through searching Google for answers to questions.
I have found that most of the questions I have asked have been promptly and thoroughly answered by an experienced userbase, but I have several questions which I see slipping into the abyss unanswered whcih I suspect may never be due to their decreasing level of visibility.
As a new user I have no hope of raising a bounty on any of these questions to solicit a response. I also dont see my reputation going up particularly quickly because any question I would have a chance of answering is picked up within seconds and answered better than I ever could by someone with greater knowledge.
This means the only way I can see of raising my reputation high enough to bring attention to these questions any time soon would be to spam the system with easy to answer questions (don't worry, I won't).
Therefore what I would like to see is some way for users with low reputations to be able to offer a bounty or at least in some way encourage an answer to a question - for example allowing them a free 50 rep bounty once a month to offer on an important question that has not been answered for a period of time and has not been downvoted (is a sensible question that is not easy to answer.)
We are probably the ones who need the most help after all.
P.S. love the site - I've leart more in the last two weeks of membership than the two months previous.

A: When you edit a question, you "bump" it to the top, so the question gains visibility.
So, if a question is starting to languish, you can consider making a meaningful edit, to add detail to the question.  That'll make it more visible, and hopefully someone will be able to help you with your newly improved question.
If this is your question, consider editing it down to the bare minimum of what you need to get the problem across.  Right now the question is quite long, and the tl;dr factor might be scaring some people away.

A: I have never once been motivated to answer a question because of a bounty. I suspect this probably isn't true for most users, which is why we have the bounty system and it works. But I also think it presents sufficient evidence to negate the argument that without the ability to offer bounties, new users won't be able to get good answers to their questions.
By far, the biggest problem I see with questions from new users (particularly those that have not been answered, although not exclusively) is a lack of clarity. Sometimes the questions are appallingly bad, but other times they're just not nearly as clear as they need to be to elicit good responses. They don't give enough background information and/or context (why do you need to do this?), they don't tell us what that person might have already tried to fix their problem, they don't tell us what type of constraints they might be working under (oh, this actually has to run on Windows 95...), etc.
So the real solution here is to improve your questions! And there's a little bonus feature that works to your advantage if you continually improve and update your question: it gets "bumped" back up to the top of the list of questions every time it is edited. That helps to ensure that people will see it.
The only time I've ever seen a good question go unanswered is when it was either so hard that it took a special person with incredible insider knowledge to answer it (e.g., Eric Lippert answering questions about the C# compiler or language design decisions) or there was no good answer because the task pursued was essentially impossible. In neither of those cases is a bounty going to encourage anyone to answer the question when they wouldn't otherwise.
TL;DR I don't think this is necessary. It would just add unnecessary complexity to the system. Just edit the question and improve it; that automatically "bumps" it. Most new user questions are bad anyway.


text: Q: How to preserve original formatting in an epub file After converting a basic doc file to an html file and thereafter converting it to an epub file, certain parts of my original format is getting disturbed. For example certain paragraphs are not coming as paragraphs where it is supposed to. Is there any way to preserve the original format of the text in the final epub file?


text:
Q: Fortify -Denial of Service_Format String I am seeing the Denial of Service format string fortify issue in line String.format.
Attackers are able to control the format argument to format() which could enable them to cause exceptions to be thrown or leak information.How can i fix this fortify issue??
 public String formatMessage(String code, Object... args) {
   Optional<ErrorDetails> error = errorRepository.findByCode(code);
   if (error.isPresent()) {
   String msg = error.get().getMessage(); //msg is for e.g "Message with parameters: %s, %s"
   return String.format(msg, args);
   }
   return "";
}


text:
Q: Not able to get Facebook Reviews through PHP SDK V4. Error: (#210) Subject must be a page I am trying to use PHP SDK V4 to retrieve 'Facebook Page Ratings' in my website's page. For that I created an fb app, and got a page access token from Graph API Explorer.
As described in this link. My code was working properly when I access ONLY page details
$request = new FacebookRequest(
  $session,
  'GET',
  '/{page-id}'
);

But when I try to retrieve ratings of that Facebook page as described here-
$request = new FacebookRequest(
  $session,
  'GET',
  '/{page-id}/ratings'
);

I get following Error-

Fatal error: Uncaught exception 'Facebook\FacebookPermissionException' with message '(#210) Subject must be a page.'.......

Why is that? Please Help!

A: You're getting this error coz you're not using the page access token with the API call.
Getting the page access token–
Instead of using the page access token from the Graph API Explorer, get one from the API call. Remember that the user must authorize the app with manage_pages permission. You'l l get the page access token in the response of following call (demo)-
$request = new FacebookRequest(
  $session,
  'GET',
  '/{page-id}?fields=access_token'
);

PS, if required, you can also get a page access token of a page which you authored that never expires. See this answer.
Using page access token with a call–
To get the ratings you have to use the page access token with the API /{page-id}/ratings, just like this-
$request = new FacebookRequest(
  $session,
  'GET',
  '/{page-id}/ratings?access_token='.$page_access_token  //use the page access token obtained from above step here
);

Note:
From v2.0 onwards, the permissions other than public_profile, email and the user_friends need to the submitted for review before you can make your app live; else you wont be able to use them. Only the testers/admin/developers of the app will be able to test with those permissions until the permissions are reviewed.
So, you just have to submit login review before you make your app live. Here are the details for login review


text:
Q: Convert an array to hash, where keys are the indices I am transforming an array into a hash, where the keys are the indices and values are the elements at that index.
Here is how I have done it
# initial stuff
arr = ["one", "two", "three", "four", "five"]
x = {}

# iterate and build hash as needed
arr.each_with_index {|v, i| x[i] = v}

# result
>>> {0=>"one", 1=>"two", 2=>"three", 3=>"four", 4=>"five"}

Is there a better (in any sense of the word "better") way to do it?

A: arr = ["one", "two", "three", "four", "five"]

x = Hash[(0...arr.size).zip arr]
# => {0=>"one", 1=>"two", 2=>"three", 3=>"four", 4=>"five"}

A: x = Hash.new{|h, k| h[k] = arr[k]}

A: %w[one two three four five].map.with_index(1){ |*x| x.reverse }.to_h

Remove (1) if you want to start the index from 0.

A: Ruby < 2.1:
Hash[arr.map.with_index { |x, i| [i, x] }]
#=> {0=>"one", 1=>"two", 2=>"three", 3=>"four", 4=>"five"}

Ruby >= 2.1:
arr.map.with_index { |x, i| [i, x] }.to_h

A: Here is a solution making use of Object#tap, to add values to a newly-created hash:
arr = ["one", "two", "three", "four", "five"]

{}.tap do |hsh|
  arr.each_with_index { |item, idx| hsh[idx] = item }
end
#=> {0=>"one", 1=>"two", 2=>"three", 3=>"four", 4=>"five"}

A: Many good solutions already, just adding a variant (provided you do not have duplicated values):
["one", "two", "three", "four", "five"].map.with_index.to_h.invert
# => {0=>"one", 1=>"two", 2=>"three", 3=>"four", 4=>"five"}

A: You could monkey patch Array to provide a new method:
class Array
  def to_assoc offset = 0
    # needs recent enough ruby version
    map.with_index(offset).to_h.invert
  end
end

Now you can do:
%w(one two three four).to_assoc(1)
# => {1=>"one", 2=>"two", 3=>"three", 4=>"four"}

This is a common operation I'm doing in Rails apps so I keep this monkey patch around in an initializer.

A: You should go with the map method, it's better and uses less memory. Another solution is with while loop. Good to know this way too, because often you may need to use the while loop.
At example 2, if you want to take each odd index in the an array as a key in the hash, and each even index as a value in the hash
Example 1:
some_array = ["one", "two", "three", "four", "five"]

def to_hash(arr)
  counter = 0
  new_hash = Hash.new(0)
  while counter < arr.length
    new_hash[counter] = arr[counter]
    counter += 1
  end
  return new_hash
end

puts to_hash(arr)
# Output
{0=>"one", 1=>"two", 2=>"three", 3=>"four", 4=>"five"}

Example 2 -
Perhaps after getting data as a string, and you split this string to an array, and now you want to convert to key, value.
some_array = ['KBD', 'King Bedroom', 'QBD', 'Queen Bedroom', 'DBD', 'Double Bedroom', 'SGLB', 'Single Bedroom']

def to_hash(arr)
  new_hash = Hash.new(0)
  counter = 0
  while counter < arr.length
    new_hash[arr[counter]] = arr[counter+1]
    counter += 2
  end
  return "#{new_hash}"
end

puts to_key_value_hash(some_array)

# Output
{"KBD"=>"King Bedroom", "QBD"=>"Queen Bedroom", "DBD"=>"Double Bedroom", "SGLB"=>"Single Bedroom"}

Many ways to do this, but just saying not to forget the while loop.


text:
Q: Aframe physics sphere breaks into smaller spheres on collision In my game, I make a sphere (created using a-sphere), a dynamic body, collide with another dynamic body (a-box).
Upon collision, the sphere breaks into multiple smaller spheres. I need to stop this disintegration
Here is the codepen - sphere breaks on collision with dynamic body
Here is the accompanying code -
HTML
<a-scene physics="debug: true; gravity: -5.0">
  <a-entity camera="userHeight: 1.6"
                look-controls
                kinematic-body>
        <a-entity cursor
                  position="0 0 -1"
                  geometry="primitive: circle; radius: 0.01; segments: 4;"
                  material="color: #FF4444; shader: flat"></a-entity>
    <a-entity position="0 0 1" id="attachment"></a-entity>
  </a-entity>

  <a-entity geometry="primitive: box; height:2" material="color: black; shader: flat" position="0 2 -5" dynamic-body></a-entity>

  <a-plane static-body color="#ccc" height="100" width="100" position="0 -0.1 0" rotation="-90 0 0"></a-plane>
</a-scene>

and JS
const scene = document.querySelector('a-scene');
const camera = document.querySelector('[camera]');
const attachment = document.querySelector('#attachment');

function spawnBullet() {
    let entity = document.createElement('a-sphere');
    let impulseAmount = 8;

    entity.setAttribute('radius', 1);
    // Set initial position of projectile to that of the camera.
    entity.setAttribute('position', camera.getAttribute('position'));
    entity.setAttribute('color', '#00FFCC');
    entity.setAttribute('shader', 'flat');
    entity.setAttribute('mass', 10);

    // Append projectile to the scene, not to the camera, to
    // avoid all sorts of complications. Most notably, CANNON.js
    // has no scene graph or nesting.
    scene.appendChild(entity);

    entity.setAttribute('dynamic-body', true);

    entity.addEventListener('body-loaded', function(){
      // Can't apply forces during the same tick that attaches the body, because
      // it hasn't been fully synced to the physics sim. (bug)
      setTimeout(function () {
        let pStart = new CANNON.Vec3();
        // Use an origin point behind the head, not at the head, so
        // there's a useful vector between the origin and the projectile.
        pStart.copy(attachment.object3D.getWorldPosition());
        let force = entity.body.position.vsub(pStart);
        force.normalize();
        force.scale(impulseAmount, force);
        entity.body.applyImpulse(force, entity.body.position);
      }, 0);

      entity.addEventListener('collide', function(e){
        console.log("hit");
      })
    });
}

if (scene.hasLoaded) init(); // change 2
else scene.addEventListener('loaded', init);

function init () {
  // any code that appends things to the scene
  scene.addEventListener('click', spawnBullet);
}

Is there a way that this can be stopped and the sphere remains intact after collision?

A: The sphere is not breaking, what's happening is that your click event handler is being called multiple times for each click, and creating many spheres at once. I'm not entirely sure why that's happening. One way around that, use AFRAME.utils.throttle to prevent creating spheres too quickly:
spawnBullet = AFRAME.utils.throttle(spawnBullet, 100);
scene.addEventListener('click', spawnBullet);

Updating to a newer version of A-Frame may also fix the issue.

A: Listening for the click event on the scene is backfiring, because you get three events
- the cursor emits one when clicked on something
- the target emits one when clicked
- the canvas emits one (mouse clicking, not the a-frame cursor - on the DOM canvas element).
You can see it in this example, click on any object on the scene, and check out the console.

You can listen for the mousedown event which is emitted by the cursor everytime its "clicked". Check it out here

Provided you're on a PC, you can also listen for the click on the aframe canvas. If you're on a vive then just call the shootBullet when a trigger is pulled.

Check it out working properly here.


text:
Q: How to explode a one row Spark dataframe in JSON format to multiple rows? Context: I'm learning PySpark and I am trying to run a sentiment analysis on tweets. After loading the data (that is in JSON format), I want to store it in a Spark Dataframe for preprocessing (removing uncessary symbols/words). Currently, I'm using an intermediate step that I want to eliminate: I'm loading the JSON into a pandas DataFrame and then to the spark Dataframe and it all works well.
However, when loading the JSON directly onto a PySpark DataFrame, all the data is stored in one row only.
How I'm loading the data:
df = spark.read.json("dbfs:/FileStore/tables/json_twitter.json").select("full_text")

The df is constituted by only one row and one column (full_text) with the following format:
{"0": "Hello", "1": "Tweet","2": "Bye"}

How can I efficiently turn this into a "normal" dataframe, having one row for each word?
Thank you

A: If the value inside fulltext is a string you may first convert it to a map type using from_json example
from pyspark.sql import functions as F
from pyspark.sql import types as T

df = df.withColumn("fulltext",F.from_json("fulltext",T.MapType(T.StringType(),T.StringType())))

before applying the explode function to split the values into multiple rows eg:
from pyspark.sql import functions as F
from pyspark.sql import types as T

df = df.select(F.explode("fulltext"))

df.show(truncate=False)

+---+-----+
|key|value|
+---+-----+
|0  |Hello|
|1  |Tweet|
|2  |Bye  |
+---+-----+

Edit 1
If the value inside fulltext is  a struct, you may first

*

*cast it to a string using cast

*replace extra character braces using regexp_replace

*split the string by comma using split

*exploding the split value to get the desired rows using explode
eg
from pyspark.sql import functions as F
from pyspark.sql import types as T

df = df.withColumn("fulltext",F.col("fulltext").cast("string"))
df.printSchema() # only for debugging purposes
df.show() # only for debugging purposes

df = df.withColumn("fulltext",F.explode(F.split(F.regexp_replace("fulltext","\\{|\\}",""),",")))

df.show() # only for debugging purposes

root
 |-- fulltext: string (nullable = false)

+-------------------+
|           fulltext|
+-------------------+
|{Hello, Tweet, Bye}|
+-------------------+

+--------+
|fulltext|
+--------+
|   Hello|
|   Tweet|
|     Bye|
+--------+


text:
Q: Moving fields from QA to Dev Org with same Api Name I have some fields in an org that I am working in building out some functionality. I was told that I need to move them into my dev org so that we can refresh the other org. I had originally build some functionality in my dev org but rebuilt it in QA manually. I realize now this was a bad idea, but the fields exist in both orgs with the same API names. I've tried googling to figure out what sort of issues this is going to cause but cannot seem to find an answer. Any guidance would be greatly appreciated.

A: If they're the same data type, nothing happens when you deploy fields with duplicate API names. If they are of differing types, you may get errors. In that case, just rename the fields so they have a new API name before trying to deploy again. Be aware that changing between some data types, like Phone to Number, may delete all data for all records in that field. Since this is apparently not a live org, that's probably an acceptable consequence.


text:
Q: Script using requests library throws "no connection adapters found" error when trying to supply url's from Postgres table I'm trying to test the validity of URLs stored in Postgres database using the requests library in a Python 3.x script, but am getting the following error:
$ python3 test_urlvalid.py
Traceback (most recent call last):
  File "test_urlvalid.py", line 55, in <module>
    response = requests.get(row)
  File "...python3.7/site-packages/requests/api.py", line 75, in get
    return request('get', url, params=params, **kwargs)
  File "...python3.7/site-packages/requests/api.py", line 60, in request
    return session.request(method=method, url=url, **kwargs)
  File "...python3.7/site-packages/requests/sessions.py", line 533, in request
    resp = self.send(prep, **send_kwargs)
  File "...python3.7/site-packages/requests/sessions.py", line 640, in send
    adapter = self.get_adapter(url=request.url)
  File "...python3.7/site-packages/requests/sessions.py", line 731, in get_adapter
    raise InvalidSchema("No connection adapters were found for '%s'" % url)
requests.exceptions.InvalidSchema: No connection adapters were found for '('http://sampleurl.com',)'

Here's a snippet of my script:
dbconn = create_engine('postgresql+psycopg2://' + user + ':' + password + '@' + host + ':' + str(port) + '/' + database , echo=False)
dbconnraw = dbconn.raw_connection()
cur = dbconnraw.cursor()
cur.execute('SELECT email_domain_url FROM testurlsource')
rows = cur.fetchall()

for row in rows:
    response = requests.get(row)
    urlstat = response.status_code
    if urlstat<400:
        print('valid')
    else:
        print('invalid')

The line the error code refers to is:
response = requests.get(row)

Since the last line of the error code references %s in url and '('http://sampleurl.com',)' so it's probably related to converting each table entry into a string.
Maybe I need to change something so the characters "(),'" are removed when feeding the rows into the script.
I tried using regex to do the latter but got the error:
AttributeError: 'list' object has no attribute 'encode'

Any advice?

A: If you use print(type(row)) in your for-loop, you might find that the variable row is probably a tuple (or maybe a list) with one element inside. The error message seems to suggest that same issue.
So you could try to pass that element to the requests call (instead of passing the whole tuple), changing this line:
response = requests.get(row)

to this:
response = requests.get(row[0])


text:
Q: Wicket RestartResponseException with session We have two URL-mounted pages (running Wicket 6.11). When the browser (tried with Chromium) opens the URL for page 1 with a certain parameter, the constructor saves an information in the session and redirects to page 2 (pseudo-code):
public Page1(Pageparameters parameters) {
    super(parameters);

    String value = parameters.get("magicProperty").toString();
    if (value != null && isValid(value)) {
       Serializable key = createKey(value);
       getSession().setAttribute("key", key);
       throw new RestartResponseException(Page2.class);
    }
}

In the page 2 constructure we want to get the key from the session again:
public Page2(PageParameters parameters) {
    super(parameters);

    Serializable key = getSession().getAttribute("key");
    ...
}

The problem is, that when the browser is freshly opened, the key in page 2 is null - it looks like the session object is freshly created for page 2. How can I resolve/work around this problem?

A: I don't know why but before throwing the RestartResponseException it looks like I need to invoke session.bind():
public Page1(Pageparameters parameters) {
    super(parameters);

    String value = parameters.get("magicProperty").toString();
    if (value != null && isValid(value)) {
       Serializable key = createKey(value);
       Session session = getSession();
       session.setAttribute("key", key);
       session.bind();
       throw new RestartResponseException(Page2.class);
    }
}


text:
Q: How to detect vulnerable/personal information in CVs programmatically (by means of syntax analysis/parsing etc...) To make matter more specific:

*

*How to detect people names (seems like simple case of named entity extraction?)

*How to detect addresses: my best guess - find postcode (regexes);  country and town names and take some text around them.

*As for phones, emails - they could be probably caught by various regexes + preprocessing

*Don't care about education/working experience at this point

Reasoning:
In order to build a fulltext index on resumes all vulnerable information should be stripped out from them.
P.S. any 3rd party APIs/services won't do as a solution.

A: The problem you're interested in is information extraction from semi structured sources. http://en.wikipedia.org/wiki/Information_extraction
I think you should download a couple of research papers in this area to get a sense of what can be done and what can't.

A: I feel it can't be done by a machine.
Every other resume will have a different format and layout.
The best you can do is to design an internal format and manually copy every resume content in there. Or ask candidates to fill out your form (not many will bother).

A: I think that the problem should be broken up into two search domains:

*

*Finding information relating to proper names

*Finding information that is formulaic

Firstly the information relating to proper names could probably be best found by searching for items that are either grammatically important or significant. I.e. English capitalizes only the first word of the sentence and proper nouns. For the gramatical rules you could look for all of the words that have the first letter of the word capitalized and check it against a database that contains the word and the type [i.e. Bob - Name, Elon - Place, England - Place].
Secondly: Information that is formulaic. This is more about the email addresses, phone numbers, and physical addresses. All of these have a specific formats that don't change. Use a regex and use an algorithm to detect the quality of the matches.
Watch out:
The grammatical rules change based on language. German capitalizes EVERY noun. It might be best to detect the language of the document prior to applying your rules. Also, another issue with this [and my resume sometimes] is how it is designed. If the resume was designed with something other than a text editor [designer tools] the text may not line up, or be in a bitmap format.
TL;DR Version: NLP techniques can help you a lot.


text:
Q: ID from parents parent adjacent element I need to get the ID of the "parents parent adjacent" element. I've come so far that I can select the element that contains the ID. Now I just need to output the ID.

JSFiddle
jQuery:
$(function(){
    var a = $('.function').closest('li').find('a:first').attr('id');
    console.log(a);
});

HTML:

            Link 1.

                Function 1 here.

            Link2 1.

            Link 2.

                Function 2 here.

            Link2 2.

            Link 3.

                Function 3 here.

            Link2 3.

A: You are on the right track. The issue is attr returns value of the first element in the collection. You should iterate through the collection and get the ID of each element individually.
Here is an example using map method for generating an array of IDs:
var a = $('.function').closest('li').find('a:first').map(function() {
    return this.id;
}).get();

You could also use the :has selector:
$('li:has(.function)').children('a').each(function() {
    console.log(this.id);
});

A: Try it: use map()
var a = $('.function').map(function () {
    return $(this).closest("li").find(" > a")[0].id;

}).get();

updated fiddle

A: Can you try changing from first to first-child:
$(function () {
    var a = $('.function').closest('li').find('a:first-child').attr('id');
    console.log(a);
});

Fiddle: http://jsfiddle.net/ztuttzuL/3/


text:
Q: Meteor reloads endlessly after re-deployment on server with appcache My Meteor app runs fine but after doing some changes and redeployment.
In fiefox there is an endless reloading
in android it seems that no connection is possible after updating the app (also endless reloading).
I tried to set the DDP_DEFAULT_CONNECTION_URL in the node configuration but it did not help. On my test-system the app is running beyond a NGINX server.
Cleaning the appcache helped for firefox (i am using AppCache plugin) and cleaning the app's data on android helped also.
Did this occur for anyone else? How can we solve this?
Thank you.
=== UPDATE:
In Chrome the following exception is visible:
Document was loaded from Application Cache with manifest http://xxxxxx/app.manifest
list:1 Application Cache Checking event
list:1 Application Cache NoUpdate event
list:1 Application Cache Checking event
list:1 Application Cache NoUpdate event
Uncaught Error: Two migrations in progress?

    ....
=== UPDATE 2:
After investigating the issue, i came across a lot of similar issues regarding the endless reload and appcache on meteor:

*

*Meteor infinite redirect instead of render 404

*https://meteor.hackpad.com/Hot-Code-Push-design-notes-9o22fy6gruu

*https://github.com/meteor/meteor/issues/2261

*Meteor infinite redirect instead of render 404

*https://github.com/meteor/meteor/issues/4722
=== UPDATE 3:
this is a current log:

Application Cache Checking event
Checking for manifest
Application Cache NoUpdate event
No cache updates
Navigated to http://xxxxxxx/
Document was loaded from Application Cache with manifest http://xxxxxxx/app.manifest
Application Cache Checking event

//... and so on

Connecting the Android-Device and debugging with Chrome it says
Uncaught SyntaxError: Unexpected token <

after updating.
After uninstalling appcache package, everything works fine but the app must be available offline.
This is a very annoying bug in Meteor AppCache package. Does anyone know a solution to this?
==== update
we tried:

*

*remove all notFoundTemplates:

*add at LAST rule the solution described at: https://github.com/iron-meteor/iron-router/issues/1202

*clean your appcache and the re-deployment will work on the second deployment after the cache was cleaned

on the deployment next to the second, the error was present again :/
===== update end

A: I don't know if this helps, but if you are using nginx+ passenger setup, try removing meteor_runtime_config.js from cache config.
The following worked for me
eg config:
location /meteor_runtime_config.js {
   expires -1;
}


text:
Q: Prove an inequality. Prove that $$\displaystyle{(|x_1+y_1|^p + |x_2+y_2|^p +\dots +|x_n+y_n|^p)^{\frac{1}{p}}\leq (|x_1|^p + |x_2|^p +\dots +|x_n|^p)^{\frac{1}{p}}+(|y_1|^p + |y_2|^p +\dots +|y_n|^p)^{\frac{1}{p}}}$$ for all $p\in\Bbb{N}$.
I tried methods like taking the $p$th power on both sides and differentiating with respect to $x_1$, taking the rest of the variables as constants. I didn't get much farther.
A helpful hint would be great, and would suffice. I am not looking for a solution.
Thanks in advance!

A: This is known as Minkowski's Inequality. The easiest proof is using duality as is shown in this answer. The only tool needed there is Hölder's Inequality.

A: Hint
The expression in question is the $p$-Norm of vectors $x,y \in \mathbb{R}^n$ and translates to
$$\lVert x+y \rVert_p \leq \lVert x\rVert_p + \lVert y \rVert_p$$
Prove using the Cauchy-Schwarz inequality after taking the $p$-th power elementwise.

A: Hint: If $p\geq 1$, then the function $f:[0,\infty)\rightarrow[0,\infty),x\to x^p$ is convex. That is, for any $x,y\in[0,\infty)$ and $0\leq\theta\leq1$,
$$f(\theta x+(1-\theta)y)\leq \theta f(x)+(1-\theta)f(y).$$


text:
Q: How do I delete a related object with a 1 to 1 relationship in the Entity Framework? I'm using EF Model First and in my Employee class I have a Manager property with a 1 to 1 relationship to itself, the Employee class:
public partial class Employee
{
    public Employee()
    {
    }

    public int Id { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }

    public virtual Employee Manager { get; set; }
}

Now, when I get an existing object from the database and change the manager with:
employee.Manager = otherEmployeeInstance;
Context.Entry(employee).State = System.Data.EntityState.Modified;
Context.SaveChanges();

It works just fine; however, if I want to remove the manager this will not work:
employee.Manager = null;

It looks to me that I first need to "load" the manager (Employee) instance into the context since this makes it work:
var dummyVar = employee.Manager.Id;
employee.Manager = null;

So the question is, what's the best (proper) way to remove a related object?

A: obviously, when you want to delete an entity of the one-to-one relationship, the EF doesn't allow to delete it without preparing it before. that is, removing any dependent entity information from that entity. Remember, we are using Relational Database system and any breaking relation without any coordination causes to anomaly and failure.
When you want to remove a relation, you can use this at your controller:
employee.Remove(Manager);//Automatically Removes Navigational Properties at both entities
db.SaveChanges();

Instead of this :
employee.Manager = null;


text:
Q: Cannot open files with Umlaut with Libreoffice on Debian I have set up a new system with a backported debian 11 and KDE Plasma 5 and wanted to continue working on my files. Some of them are from shared project containing Umlaute (ö, ü, ä) which I cannot rename for various reasons.
I am asking here because it seems like to be an issue co-depending on the OS and libreoffice at the same time and on my last system with a "regular" debian 11 there werent any issues.
However I am struggling to open those files with the error either saying:

*

*The operation on <path-to-file-with-umlaut> was started with an invalid parameter.

*<path-to-file-with-umlaut> does not exist.
Please note, that an exemplary file name would be Stückliste.xlsx displayed with "??".
So far I tried installing the latest libreoffice via aptitude (7.0.4.2) or via flatpak. Neither where able to solve this. I also tried 7.3.1 via direct download from the libreoffice website.
Furthermore in the "Language settings" of libreoffice I tried multiple "locale settings", as my system is setup with the following locale:
locale: Cannot set LC_CTYPE to default locale: No such file or directory
locale: Cannot set LC_MESSAGES to default locale: No such file or directory
locale: Cannot set LC_ALL to default locale: No such file or directory
LANG=en_DE.UTF-8
LANGUAGE=en_GB:de
LC_CTYPE="en_DE.UTF-8"
LC_NUMERIC="en_DE.UTF-8"
LC_TIME="en_DE.UTF-8"
LC_COLLATE="en_DE.UTF-8"
LC_MONETARY="en_DE.UTF-8"
LC_MESSAGES="en_DE.UTF-8"
LC_PAPER="en_DE.UTF-8"
LC_NAME="en_DE.UTF-8"
LC_ADDRESS="en_DE.UTF-8"
LC_TELEPHONE="en_DE.UTF-8"
LC_MEASUREMENT="en_DE.UTF-8"
LC_IDENTIFICATION="en_DE.UTF-8"
LC_ALL=

As this shows some issues with locale itself, I had the same settings and issues resulting from it on my old system. So far Ive never been able to address this (I can only assume it results from the mixup between German and English), but libreoffice worked fine on the old system nonetheless.
EDIT1: Both systems were running debian 11 (bullseye)
EDIT2: Named an exemplary file name

A: The is no en_DE Language AFAIK.
Do an sudo dpkg-reconfigure locales and best to Choose all three de_DE-Languages if you work with different Files from different Systems/Persons.
I would also suggest you add at least en_US.UTF-8.
It should look like this if everything worked.
> locale
LANG=de_DE.UTF-8
LANGUAGE=de_DE:de
LC_CTYPE="de_DE.UTF-8"
LC_NUMERIC="de_DE.UTF-8"
LC_TIME="de_DE.UTF-8"
LC_COLLATE="de_DE.UTF-8"
LC_MONETARY="de_DE.UTF-8"
LC_MESSAGES="de_DE.UTF-8"
LC_PAPER="de_DE.UTF-8"
LC_NAME="de_DE.UTF-8"
LC_ADDRESS="de_DE.UTF-8"
LC_TELEPHONE="de_DE.UTF-8"
LC_MEASUREMENT="de_DE.UTF-8"
LC_IDENTIFICATION="de_DE.UTF-8"

After the dpkg-reconfigure it maybe best to log out and in your User-Session.

A: Recently encountered the same problem.
In addition to the system locale settings, I needed to set the settings in LibreOffice itself.
Tools > Options  > Language Settings > Languages - here put correct Locale for the files


text:
Q: query data according into specific timezone in mongodb As you know, by default mongoDB saves records with timestamps (createdAt, updatedAt) into utc timezone.
Issue:
At our system, one user is registered on 21st December at 2 AM. But as per UTC timezone, mongoDB stored that record with createdAt as 20st december, 8:30 PM in users collection. So, when I am trying querying users which are registered on 21st December, MongoDB not returning me that user according to below query.
Query:
How can I find records according to specific timezone or how can I modify my aggregate query to return me that user also?
Current Code:
let currentWeekDates = [
   '2022-12-19T00:00:00+08:00',
   '2022-12-20T00:00:00+08:00',
   '2022-12-21T00:00:00+08:00',
   '2022-12-22T00:00:00+08:00',
   '2022-12-23T00:00:00+08:00',
   '2022-12-24T00:00:00+08:00',
   '2022-12-25T00:00:00+08:00'
]

for (let date of currentWeekDates) {
    const formatedDate = moment(date).format('YYYY-MM-DD');
    facet[formatedDate] = [
      {
        $match: {
          createdAt: { $gte: moment(date).startOf('day').toDate(), $lte: new Date(moment(date).endOf('day').toDate()) }
        }
      }
    ]
}

let data = await User.aggregate([
  {
    $facet: facet
  }]
);

Record from database:
{
   first_name: 'test',
   email: 'test@gmail.com',
   createdAt: 2022-12-20T20:40:09.275+00:00
   updatedAt: 2022-12-20T20:40:09.275+00:0
}

A: I think this would be an easier solution:
let currentWeekDates = [
   ISODate('2022-12-19T00:00:00+08:00'),
   ISODate('2022-12-20T00:00:00+08:00'),
   ISODate('2022-12-21T00:00:00+08:00'),
   ISODate('2022-12-22T00:00:00+08:00'),
   ISODate('2022-12-23T00:00:00+08:00'),
   ISODate('2022-12-24T00:00:00+08:00'),
   ISODate('2022-12-25T00:00:00+08:00')
]

let data = await User.aggregate([
{
  $bucket: {
      groupBy: "$createdAt",
      boundaries: currentWeekDates ,
      output: {
         data: { $push: { "$$ROOT" } }
      }
   }
}]);


text:
Q: Cocoa - Whats the best way for modifying NSOutlineView Result should be an settings panel with an OutlineView and "add item", "add group" and "delete" buttons. The buttons add entries to an NSOutlineView. The data is stored in a NSMutableDictionary (or whatever is suitable). Sorting/DragDrop enabled for the OutlineView.
What is the best or most comfortable way for this (and write less code)?
Modifying NSMutableDictionary, NSOutlineView refreshes from NSMutableDictionary?
Modifying NSOutlineView, Result is stored in NSMutableDictionary?
... NSTreeController?
... CoreData?
What's best practice for that?
Thanks in advance!

A: This is a pretty broad question. You should always store your model data in a model object of some kind, be that a Core Data entity, an NSMutableDictionary or a custom object of your own creation. You should definitely NOT be storing the data in an NSTreeController or NSOutlineView instance, these are not model objects.
If you're using Core Data for the rest of your app and you need to persist the data that is manipulated by the outline view then this is a good choice, but it might be overkill if you have only simple requirements.
To control what is displayed in the outline view you can either use NSTreeController or your own controller object that responds to the NSOutlineView datasource and delegate protocols. In practice you might use both, as some things such as whether or not an item is a group item can only be controlled by the NSOutlineView delegate methods.
In my personal experience I've found that NSTreeController can be very difficult to deal with for anything beyond very simple tasks and I now longer use it, I find it's much simpler to just use the datasource methods in my own controller.
As far as modifying the contents of the outline view, you should always modify the model via a controller, you should never update the view directly. You would implement methods such as -add: in your controller or use the -add: method of NSTreeController if you're using it.
Your view's controller should then detect the change in the model and ask the view to update. The view controller and model controller can be the same object but they don't have to be. Key-Value Observing is a useful technology that can inform your controller of a change in the model.
Here's some sample code from Apple that you might find useful:
http://developer.apple.com/mac/library/samplecode/SourceView/
http://developer.apple.com/Mac/library/samplecode/AbstractTree/


text:
Q: Rcpp compiled Attributes not available for call First I know this is probably an Rcpp-Devel function, but when I try to subscribe using Firefox or Chrome, I get an error at my work ethernet that the connection is not secure, so I have to ask here for now.
So I purchased Dirk's book and it is written excellently.
I am getting a similar error here
https://www.mail-archive.com/rcpp-devel%40lists.r-forge.r-project.org/msg08059.html
Sage<-testArm(set,labels,contrast,geneSets,var.equal=FALSE)
Calculating comparisons...Error in .Call("sigmaCalc", PACKAGE = "mySage") :
 "sigmaCalc" not available for .Call() for package "mySage"

note, my NameSpace has the useDynLib(mySage), and I can successfully run compileAttributes and R CMD build (in an outside directory) and install the package successfully.
when I try to call one of the RcppExport.R functions, I generate the error
here is one of my Cpp codes
//[[Rcpp::depends(RcppArmadillo)]]
#include <RcppArmadillo.h>
#include <algorithm>
#include <vector>
 #include <Rcpp.h>
 #include <math.h>
#include <R.h>
using namespace arma;
using namespace Rcpp;
//'calculates the sd and mindof in order , names are assigned in R, as of     now, there is no NA error checking.  not very robust
//' @param SDs standard deviations from geneResults returned by     makeComparison
//' @param DOFs degrees of freedom from geneResults returned by makeComparison
//' @param geneSets a set of genes for enrichment testing
//' @export
//' @return a List with SumSigma and MinDof
//[[Rcpp::export]]
List sigmaCalc( SEXP SDs, SEXP DOFs, SEXP geneSets) {
Rcpp::NumericVector SD(SDs);
Rcpp::NumericVector DOF(DOFs);
Rcpp::List geneSet(geneSets);
 more code ....

the comments here get created and export into the R nameSpace properly
here is the RcppExports.R
# This file was generated by Rcpp::compileAttributes
# Generator token: 10BE3573-1514-4C36-9D1C-5A225CD40393

#'calculates the sd and mindof in order , names are assigned in R, as of now, there is no NA error checking.  not very robust
#' @param SDs standard deviations from geneResults returned by makeComparison
#' @param DOFs degrees of freedom from geneResults returned by makeComparison
#' @param geneSets a set of genes for enrichment testing
#' @export
#' @return a List with SumSigma and MinDof
 sigmaCalc <- function(SDs, DOFs, geneSets) {
.Call('mySage_sigmaCalc', PACKAGE = 'mySage', SDs, DOFs, geneSets)
}

here is the RcppExport.cpp
// This file was generated by Rcpp::compileAttributes
// Generator token: 10BE3573-1514-4C36-9D1C-5A225CD40393

#include <RcppArmadillo.h>
#include <Rcpp.h>

using namespace Rcpp;

// sigmaCalc
List sigmaCalc(SEXP SDs, SEXP DOFs, SEXP geneSets);
RcppExport SEXP mySage_sigmaCalc(SEXP SDsSEXP, SEXP DOFsSEXP, SEXP geneSetsSEXP) {
BEGIN_RCPP
Rcpp::RObject __result;
Rcpp::RNGScope __rngScope;
Rcpp::traits::input_parameter< SEXP >::type SDs(SDsSEXP);
Rcpp::traits::input_parameter< SEXP >::type DOFs(DOFsSEXP);
Rcpp::traits::input_parameter< SEXP >::type geneSets(geneSetsSEXP);
__result = Rcpp::wrap(sigmaCalc(SDs, DOFs, geneSets));
return __result;
 END_RCPP
 }

I am not sure about several things, are header files required?  the text suggests that rcpp_hello_world.h  is needed, however after reading the RcppExport.cpp  the cpp function declaration is included in the Export.cpp, so I am not sure I need to write declarative header files.  also  networkBMA, wordcloud, and pcaMethods are all Rcpp packages and they don't include headers, so are headers needed for interfacing an API only?
the other thing that may cause this error is that my function parameters are SEXP objects and not Rcpp:NumericVectors.../NumericMatrix ,  should I write the cpp code sigmaCalc to input  Rcpp types, and then ensure that the Export.cpp functions handles the SEXP casting?
thank you.
P.S.  here is my Makevars  in src/
## Use the R_HOME indirection to support installations of multiple R version
PKG_LIBS = `$(R_HOME)/bin/Rscript -e "Rcpp:::LdFlags()"` $(LAPACK_LIBS) $(BLAS_LIBS) $(FLIBS)
PKG_CXXFLAGS=`$(R_HOME)/bin/Rscript -e "Rcpp:::CxxFlags()"`

I htink the error is that I am input SEXP as input into the cpp funcitons, this is only required when protoyping sourceCpp to go from C++ to R,  when packaging, the RcppExports.cpp is the mediator between the two systmes.

A: The post is pretty long and it is tricky to see the structure. I recommend you start over and do either one of

*

*call Rcpp.package.skeleton() and study that package, or

*use RStudio to create a package for you, or

*use an example package like RcppExamples
Start with these, rebuild them.  Then slowly add your function, run compileAttributes() and rebuild/reinstall.


text:
Q: Metrics of degree higher than 2 Suppose I have a metric (special relativity) as follows:
$$
(ds)^2 = -(dt)^2+(dx)^2+(dy)^2+(dz)^2  \tag{1}
$$
Here there are no cross-terms. Let's consider for instance this metric (which could be used in general relativity, and has cross-terms):
$$
(ds)^2=-(dt)^2+(dx)^2+(dy)^2+(dz)^2+(dxdy)+... \tag{2}
$$
Both the previous metrics have "degree 2". I am interested in metrics that are of "degree 4". For example:
$$
(ds)^4=(dt)^4+(dx)^4+2(dx)^2(dy)^2+(dx)^3dy+... \tag{3}
$$
We note that this metric cannot be written as a polynomial of degree 2.

How can I work with such a metric using conventional tools?

For instance, in special relativity (equation 1), I can write the metric as a tensor:
$$
(ds)^2=\pmatrix{dt&dx&dy&dz}\pmatrix{-1&0&0&0\\0&1&0&0\\0&0&1&0\\0&0&0&1}\pmatrix{dt\\dx\\dy\\dz}\tag{4}
$$
How can I write $(ds)^4$ (equation 3) as a metric tensor using a similar form as equation 4, but adapted to a degree 4 metric polynomial?

A: Instead of writing $ds^2=g_{ab}dx^adx^b$ with $g$ symmetric, you'd want $ds^4=g_{abcd}dx^adx^bdx^cdx^d$ with $g$ fully symmetric. But there are very good theoretical reasons physicists work with degree-$2$ metrics, such as wanting to be able to move indices viz.$$dx_a=g_{ab}dx^b\implies ds^2=dx_adx^a,\,dx^b=g^{bc}dx_c\implies dx_a=g_{ab}g^{bc}dx_c\implies g_{ab}g^{bc}=\delta_a^c.$$

A: You should keep in mind that the metric in GR is a "semi-definite bi-linear symmetric form on every tangent space that varies smoothly with the base point". In the same manner you can define a symmetric n-linear form on every tangent space ($n \geq 2$ can be whatever you want), but you wouldn't call it a "metric".


text:
Q: Casting of Generic List to a Class derived from a List I created a class derived from List. However when I tried casting the class to another List object I get a runtime error. My code is similar to the one posted below:
public class CategoryObj
{
    public int CategoryID { get; set; }
    public string CategoryName { get; set; }
    public string Description { get; set; }
}

public class CategoryObjCollection:List<CategoryObj>
{

}

public void Test()
{
        CategoryObjCollection cat = new CategoryObjCollection();
        using (NWDataContext db = new NWDataContext())
        {
            var qry = (from c in db.Categories
                       select new CategoryObj
                       {
                           CategoryID = c.CategoryID,
                           CategoryName = c.CategoryName,
                           Description = c.Description
                       }).ToList();
            cat = (CategoryObjCollection)qry; //runtime error Unable to cast object of type 'System.Collections.Generic.List`1[WindowsFormsApplication1.CategoryObj]' to type 'WindowsFormsApplication1.CategoryObjCollection'.
        }
}

I hope someone can help me on this. Thanks.

A: try this
public class CategoryObjCollection:List<CategoryObj>
{
   public CategoryObjCollection(IEnumerable<CategoryObj> items) : base(items){}
}

cat = new CategoryObjCollection(qry);

A: The cast would only work if you have implemented a conversion operator. But it is not a very effective approach.
Are you trying to create a type alias (like in C++ typedef)?
using CategoryObjCollection = System.Collections.Generic.List<myNamespace.CategoryObj>;

Now you can freely convert between CategoryObjCollection and List<CategoryObj> (which is the same type - only named differently.
I would also use a different method to fill the list up:
db.Categories.ForEach(c =>
    cat.Add(new CategoryObj()
        {
            CategoryID = c.CategoryID,
            CategoryName = c.CategoryName,
            Description = c.Description
        }));

A: Why would you expect to be able to cast? The object isn't an instance of CategoryObjCollection. The point of reference type casts (when they're actually casting rather than invoking explicit conversions) is to tell the compiler that you believe the execution time type of the object is actually compatible with the type you specify, so that you can use members of that specific type (after the execution time test). In this case, the ToList extension method just creates a new List<T>.
More to the point, what is your CategoryObjCollection type meant to achieve in the first place? If it has any state other than the normal list, where would you expect that state to come from after your LINQ query? If it doesn't have any other state, is it really adding any benefit? Maybe your type should actually contain a list rather than deriving from it? Then you could create a new instance of the type using the results of the query.
In general, it's usually a design smell to derive from List<T>. It doesn't provide many ways to specialize its "listiness" (unlike, say, Collection<T>). It's usually a sign that you should be thinking of composition instead of inheritance.

A: why are you casting ? You actually shouldn't be casting ....just add a loop over qry and fill your cat list up.

A: You can use this Extension Method
public static M Cast<T, M>(this IEnumerable<T> input) where M : ICollection<T>, new()
{
  var ret = new M();
  foreach(var item in input?? Enumerable.Empty<T>())
  {
    ret.Add(item);
  }
  return ret;
}

then you can use it like
var qry = (from c in db.Categories
   select new CategoryObj
   {
       CategoryID = c.CategoryID,
       CategoryName = c.CategoryName,
       Description = c.Description
    }).Cast<CategoryObj,CategoryObjCollection>()


text:
Q: JavaScriptSerializer to Serialize internal property member I have a Class Library project with something like this....
[DataContract]
public class DomainVerify
{
    [DataMember]
    internal string key { get; set; }
    public string domain { get; set; }
    public string mailbox { get; set; }
}

I made key Internal, so my other projects can't see this property. Now problem is, within the same project where I have "DomainVerify" Class, I am using JavaScriptSerialize to Serialize my Class into a JSON string & it seems like I can't serialze the "key" property since its "internal".
var json = new JavaScriptSerializer().Serialize(DomainVerify); // Skips Key property

is there anyway so I can hide this property to other projects and yet can serialize this property within same project?

A: I think you have to use DataContractJsonSerializer.
Following is the example provided on MSDN. This example is with internal property.
http://msdn.microsoft.com/en-us/library/bb412179(v=vs.110).aspx.
I did not tried with JavaScriptSerializer but if there is some setting that allow then only it is possible to serialize internal so I suggest tried with DataContractJsonSerialier.
If this not solve your problem then look for Newton.Json.
http://www.tecsupra.com/serializing-only-some-properties-of-an-object-to-json-using-newtonsoft-json-net/
Last but not least make sure that your internal property has some value.
DataContractJsonSerializer
class Program
    {
        static void Main(string[] args)
        {
            DomainVerify verify = new DomainVerify() { domain = "test", key = "myKey", mailbox = "Newkey" };
            Console.WriteLine(GetJsonString(verify));
            Console.ReadLine();

        }

        public static string GetJsonString(object o)
        {
            DataContractJsonSerializer ser = new DataContractJsonSerializer(o.GetType());
            using (MemoryStream ms = new MemoryStream())
            {
                ser.WriteObject(ms, o);
                string jsonData = Encoding.Default.GetString(ms.ToArray());
                return jsonData;
            }
        }
    }

    [DataContract]
    public class DomainVerify
    {
        [DataMember]
        internal string key { get; set; }
        [DataMember]
        public string domain { get; set; }
        [DataMember]
        public string mailbox { get; set; }
    }

In case of WCF you have to mark each property that you want to take part in serialization using datacontract.
you have to add System.ServiceModel and System.Runtime.Serialization assembly.
In case of Json.net ( you have to add package)
public class DomainVerify
    {
        [Newtonsoft.Json.JsonProperty]  // if you don't mark this attribute then as this is internal property it will not serilize.
        internal string key { get; set; }
        [Newtonsoft.Json.JsonProperty] // as this is public property it always include in serilization unless you mark it with JsonIgnore.
        public string domain { get; set; }
        [Newtonsoft.Json.JsonProperty]
        public string mailbox { get; set; }
    }

    class Program
    {
        static void Main(string[] args)
        {
            DomainVerify verify = new DomainVerify() { domain = "test", key = "myKey", mailbox = "Newkey" };
            Console.WriteLine(GetJsonString(verify));
            Console.ReadLine();
        }

        public static string GetJsonString(object o)
        {
            return JsonConvert.SerializeObject(o);
        }
     }

I hope above thing help you.
Note: I still have some doubt that if you pass this object from other project then it may possible that this field does not contain proper value or empty because it is internal.


text:
Q: Ember computed property or observer within a service I have a service, and declare a property in the service
bucket: []

Later in the service, I add something to bucket.
I'm trying to set up in this same service an Ember computed property or observer to listen/respond to changes in bucket.
Something like:
bucketListener: Ember.computed('bucket', function() {
   //do stuff in response to something being added to or removed from the bucket
}

But I can't get this to work. I've tried a lot of different permutations,using Ember.computed and Ember.observer, but I can never get bucketListener to fire.
I have checks in place and am sure that bucket is getting added to as expected or removed from as expected, but bucketListener still isn't getting called into.
Is there some trick to doing this within a service? Or am I just bungling something more basic?

A: Service is no different from usual Ember.Object in terms of computed properties or observer. Please use .[] to watch for elements being added or removed and observer intead of CP to fire when property changes. You can also watch main property to be sure it will fire:
bucketListener: Ember.observer('bucket', 'bucket.[]', function() {
   //do stuff in response to something being added to or removed from the bucket
}

A: To trigger computed properties, you need to use this.get('bucket').pushObject('something') instead of usual push().
When you access/use bucketListener only then computed property will be called.
Working example twiddle.https://ember-twiddle.com/776ffb2be7e129655ef62e59b2dc8697?openFiles=services.cart.js%2C


text:
Q: Why jest.fn() can be assigned to any function in Typescript? I'm confused how jest.fn() works in Typescript. For example
class MyClass {
  myFunction() {
    return 'hello'
  }
}

let myClass = new MyClass()
myClass.myFunction = jest.fn()

From my understanding, myClass.myFunction has a type of '() => string' but jest.fn() returns a 'Mock'. I notice that 'Mock' is in fact extends 'Function' but Function is less specific then () => string so how could this work?

A: Looking at the types from @types/jest, it extends function but with a specific call signature:
interface Mock<T = any, Y extends any[] = any>
  extends Function, MockInstance<T, Y> {
    new (...args: Y): T;
    (...args: Y): T; // <--
}

fn() returns just Mock and because the default return type (T) is any, this is allowed.
fn can be called with type arguments to specify the return type explicitly or, more conveniently, the types can be inferred from the implementation function:
function fn<T, Y extends any[]>(implementation?: (...args: Y) => T): Mock<T, Y>;

Example:
// Identifies wrong return type (Type 'void' is not assignable to type 'string')
myClass.myFunction = jest.fn(() => { })

// Correct return type
myClass.myFunction = jest.fn(() => '')

Playground

If the types from the jest packages themselves are used, then jest.fn() without anything else will also yield an error, because it returns a Mock<UnknownFunction>.
Playground


text:
Q: View does not affect models changes I have an get action, which has a couple of parameters. In view I have a form, that fills after get action. Action creates an instance of model using received parameters, but if parameter has special value then action set to model some default values despite parameters. After that action return view with model.
The problem is that after changing the model in View shows data of the parameters, and not from the modified model.

A: This happens because, by design, all HTML helpers first look at the ModelState when binding and after that in the model itself. So if you intend to modify some value that was part of the POST request you will need to remove it from ModelState first if you want this change to be reflected in the view:
[HttpPost]
public ActionResult SomeAction(MyViewModel model)
{
    // We remove the Bar property that was part of the request because
    // we modify its value here
    ModelState.Remove("Bar");
    model.Bar = "Some modified value";

    return View(model);
}

This assumes that in the corresponding view you have an input field for it:
@Html.EditorFor(x => x.Bar)


text:
Q: django: pip install 'app' installs to the venv? I read that it is not proper to have the venv in the git repo, which should be taken care of by requirements.txt, but I have run into a problem...
If I am working in my venv and I do a pip install of some app, it installs it into the venv site-packages. It still works and everything if I add it to installed_apps, but what if I make some changes within that directory? Then git doesn't track them and I am out of luck when I try to push it.
What is the proper way to do this?
EDIT: I must be having a huge miscommunication here so let me explain with a concrete example...

*

*I run...
pip install django-messages

*This then install django messages into me venv, I know I can run...
local...pip freeze > requirements.txt
remote....pip install -r requirements.txt

*My problem is that I want to make changes to django-messages/templates or django-messages/views thus deviating my django-messages from the one which can be installed from requirements.txt
I don't see how these are to remain in my venv without being completely uneditable/untrackable

A: This is exactly how it is supposed to work. You track what libraries you install via your requirements.txt, which is committed along with your code. You use that file to generate your venv, and the libraries are installed there. You don't include the venv itself in your repo.
Edit The reason you are finding this hard is that you are not supposed to do that. Don't change third-party projects; you should never need to. They will be configurable.
If you really really find something you need to fix, do as suggested in the comments and fork the app. But this is definitely not something you need to do all the time, which points to the likelihood that you have not understood how to configure the apps from within your own project.
For example, in the case of customising templates, you can simply define the templates inside your own templates dir, rather than editing the ones provided with the app; Django does the right thing and uses yours first.

A: From your edits it looks like what you want to do is fork the django-messages library. This means that installing it into site-packages is a bad idea in the first place, since site-packages is not supposed to be version controlled or edited, it is designated for 3rd party software. You have two options. You can just grab the source from GitHub and put it somewhere where your Django app can find it (maybe fiddle with your python path) and add this location to git. Maybe even make your own fork on github. The second option is to use pip install -e github.com/project to have pip install an "editable" version. The advantage of the first way is better control over your changes, the advantage of the second way is having pip manage source download and install.
That being said, you seem kinda new to python environment. Are you REALLY sure you want to make your own fork? Is there some functionality you are missing that you want to add to the messages library? You do know that you can override every single template without changing the actual library code?


text:
Q: How do I change the timezone of my GraphQL time? I've found a lot of good info on using Date() and getting timezones, but something just isn't working. I have my GraphQL (sourcing from Sanity) set to use formatString, like this:
export default function MinutesItemGrid() {
  const { minutes } = useStaticQuery(graphql`
    query {
      minutes: allSanityMinutes {
        nodes {
          endTime(formatString: "h:mma [on] MM/DD/YYYY")
         }
      }
   }
`);

Then calling it in a .map:
const allMinutes = minutes.nodes;
return (
    <CardStyles>
      {allMinutes.map((minute) => (
        <ItemStyles>

Meeting began at: {minute.endTime}

        </ItemStyles>
     ))}
    </CardStyles>
  );

Which displays as 11:33pm on 10/14/2020. That is 6 hours ahead of what it should be.
I know this returns UTC time standardly. I know how to get the local time offset (new Date().getTimezoneOffset();) and get the local timezone (Intl.DateTimeFormat().resolvedOptions().timeZone), but I don't see an option to change the timezone to display to MST (or local time) instead of UTC. I have tried subtracting the 6 hours in various ways, tried using moment.js and moment.js timezone to change the timezones based on their docs. I've just found out that Luxon is a better option now, but even in their docs I don't see a resolution when pulling the data from GraphQL.

A: If you plan to use Luxon, you can use DateTime to convert and format datetime to any given time zone.
For example, MDT is UTC-6. So, to convert datetime in ISO string format.
import { DateTime } from "luxon"

DateTime.fromISO(datetime, { zone: 'utc-6' }).toString()

This would output the datetime in MDT zone as 2021-04-21T07:36:04.529-06:00

A: I have discovered the answer after much trial
& error in case this helps anyone in the future. The problem that I was running into is this bit: endTime(formatString: "h:mma [on] MM/DD/YYYY")
What this did is format the string before I called the DateTime.from(minute.endTime, { zone: 'utc-6',}) so that it returned an invalid entry because .fromISO is expecting this kind of format 2020-10-14T17:33:00.000. Once I removed that all was well except for the format, which I discovered instead of using the .toString() method I had to use the .toFormat() method. So this is the corrected code from my original question:
export default function MinutesItemGrid() {
  const { minutes } = useStaticQuery(graphql`
    query {
      minutes: allSanityMinutes {
        nodes {
          endTime
         }
      }
   }
`);

then .map over the graphql:
const allMinutes = minutes.nodes;
return (
<CardStyles>
  {allMinutes.map((minute) => {
    const endMDT = DateTime.fromISO(minute.endTime, {
      zone: 'utc-6',
    }).toFormat('h:mma MM/dd/yyyy');
    <ItemStyles>

Meeting began at: {endMDT}

    </ItemStyles>
 ))}
</CardStyles>

);


text:
Q: Calculating grid convergence (True North to Grid North) I would like to know how to calculate the grid convergence angle between True North and Grid North for UTM maps.
I am using ArcGIS 10.0 (ArcView licence). and have used the Calculate Grid Convergence Angle tool from the Cartography toolbox.
However, I would like to know how to calculate this angle myself (using Excel) to compare against the ArcGIS result?

A: The formula for calculating grid convergence (sometimes called meridian convergence) for spherical UTM projections was given (very incorrectly until just now) at How to Calculate North?
In case that is not clear
γ = arctan [tan (λ - λ0) × sin φ]
where
γ is grid convergence,
λ0 is longitude of UTM zone's central meridian,
φ, λ are latitude, longitude of point in question
See Transverse_Mercator_projection#Convergence where it also gives γ as a function of grid coordinates.

A: I've always used this formula:
CA = (λ - λCM) × sin φ
Given: CA is the grid Convergence Angle for any transverse Mercator projection; λCM is the longitude of the zone's Central Meridian; φ, λ are the latitude and longitude of the point in question.
Pay attention to the resulting algebraic sign!

A: The book "The Mercator Projection" by Peter Osborne (https://zenodo.org/record/35392#.XvGjn5MzY3h) goes a bit in depth on this topic, but it seems to be no trivial topic for the general transverse mercator projection of the ellipsoid, however it agrees with Martin and Bellis for the spherical case.
It should still be the same angle regardless of wheter it is calculated in the projection or on the ellipsoid/tangential plane by the conformal property of the projection.

A: Complementing the answers by @Martin F and @V. Kelly Bellis, an article by Ontario land surveyor Tim Hartley (see p.4) gives the formula:
CA = 32.39 arc seconds * (distance from central meridian in km) * tan(latitude)
The other answers require longitude of each point where being calculated, while this formula can be used with the UTM/MTM X coordinate, yielding:
CA = (8.997E-06) degrees * (delta X from central meridian in m) * tan(latitude)
You still have to calculate tan(latitude), but in tropical and temperate regions tan(latitude) changes much, much less per delta Y than the linear dependency on delta X, (and the convergence error of true longitude vs delta X itself) so you can do this once for your whole map for a survey area.
I expect this is equivalent to @V. Kelly Bellis's formula, with the tan() representing the 1/cos() dependency of (spherical) ground scale by latitude combined with the sin() in that formula, with units converted.

A: Complementing the answers by @Martin F
Grid Convergence = atan {tan [longitude - (6 × Grid Zone Designation Number - 183)] × sin (latitude)}
The longitude of the zone's Central Meridian can be calculated using this formula: (6 × Grid Zone Designation Number - 183).


text:
Q: spring batch getting data from file and passing to procedure For a Spring batch project, I need to get the date from a file and then I need to pass this date to a procedure and then run the procedure.
Then the result of the procedure must be written to a csv file.
I tried using listeners but couldn't do this.
Can anyone please tell how this can be achieved or if possible can you share any sample code in github.

A: First of all, you will need to get the date from your file and store it in the JobExecutionContext. One of the most simple solution would be to create a custom Tasklet to read the text file and store the result String in the context via a StepExecutionListener
This tasklet takes a file parameter and stores the result string with the key file.date :
public class CustomTasklet implements Tasklet, StepExecutionListener {

    private String date;
    private String file;

    @Override
    public void beforeStep(StepExecution stepExecution) {}

    @Override
    public ExitStatus afterStep(StepExecution stepExecution) {
        stepExecution.getJobExecution().getExecutionContext().put("file.date", date);
    }

    @Override
    public RepeatStatus execute(StepContribution contribution, ChunkContext chunkContext) throws Exception {

         // Read from file using FileUtils (Apache)
         date = FileUtils.readFileToString(file);
    }

    public void setFile(String file) {
        this.file = file;
    }
}

Use it this way :
 <batch:step>
      <batch:tasklet>
            <bean class="xx.xx.xx.CustomTasklet">
                <property name="file" value="${file.path}"></property>
            </bean>
        </batch:tasklet>
 </batch:step>

Then you will use a Chunk with late binding to retrieve the previously stored value (i.e. using #{jobExecutionContext['file.date']}).
The reader will be a StoredProcedureItemReader :
<bean class="org.springframework.batch.item.database.StoredProcedureItemReader">
    <property name="dataSource" ref="dataSource" />
    <property name="procedureName" value="${procedureName}" />
    <property name="fetchSize" value="50" />
    <property name="parameters">
        <list>
            <bean class="org.springframework.jdbc.core.SqlParameter">
                <constructor-arg index="0" value="#{jobExecutionContext['file.date']}" />
            </bean>
        </list>
    </property>
    <property name="rowMapper" ref="rowMapper" />
    <property name="preparedStatementSetter" ref="preparedStatementSetter" />
</bean>

The writer will be a FlatFileItemWriter :
<bean class="org.springframework.batch.item.file.FlatFileItemWriter" scope="step">
    <property name="resource" value="${file.dest.path}" />
    <property name="lineAggregator" ref="lineAggregator" />
</bean>


text:
Q: Qt download images | Returns Empty Byte Array I have a program that is supposed to access a selected Imgur album, get the list of photos, and then download them. All goes well and I can get the URL(s), but when it goes to download them they are empty. Any help is greatly appreciated!
Main.cpp:
#include "mainwindow.h"
#include <QApplication>

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
    MainWindow w;
    QList<QUrl> imageUrls;
    QNetworkAccessManager manager;
    QNetworkReply *response = manager.get(QNetworkRequest(QUrl("http://imgur.com/a/pthXN")));
    QEventLoop event;
    QObject::connect(response,SIGNAL(finished()),&event,SLOT(quit()));
    event.exec();
    QByteArray data = response->readAll();
    QWebView *view = new QWebView;
    view->setHtml(QString::fromUtf8(data));
    QWebElementCollection colls = view->page()->mainFrame()->findAllElements("div.post-image-container a");
    foreach(QWebElement elemento, colls)
    {
        imageUrls << elemento.attribute("href");
    }
    if (!QDir(QDir::homePath() + "/Documents/imgurvaca/").exists())
    {
        QDir().mkdir(QDir::homePath() + "/Documents/imgurvaca/");
    }
    QNetworkAccessManager *manager2 = new QNetworkAccessManager;
    QEventLoop eventLoop;
    QObject::connect(manager2, SIGNAL(finished(QNetworkReply*)), &eventLoop, SLOT(quit()));
    for (int x = 0; x < imageUrls.count(); x++)
    {
        QNetworkRequest request;
        request.setUrl(QUrl(imageUrls[x]).toString().remove("//"));

        QNetworkReply *pictureReply = manager2->get(request);

        qDebug() << QUrl(imageUrls[x]).toString().remove("//");//produces the url

        qDebug() << pictureReply->readAll();//returns "" empty

    }
    eventLoop.exec();
    w.show();

    return a.exec();
}

MainWindow.cpp:
#include "mainwindow.h"
#include "ui_mainwindow.h"

QList<QUrl> imageUrls;
int xval = 0;

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    QPixmap bkgnd(":/images/background.jpg");
    bkgnd = bkgnd.scaled(this->size(), Qt::IgnoreAspectRatio);
    QPalette palette;
    palette.setBrush(QPalette::Background, bkgnd);
    this->setPalette(palette);

    QPixmap leftBkgnd(":/images/leftArrow.png");
    QIcon leftIcon(leftBkgnd);
    ui->pushButtonLeft->setIcon(leftIcon);
    ui->pushButtonLeft->setIconSize(QSize(150, 150));

    QPixmap rightBkgnd(":/images/rightArrow.png");
    QIcon rightIcon(rightBkgnd);
    ui->pushButtonRight->setIcon(rightIcon);
    ui->pushButtonRight->setIconSize(QSize(150, 150));
    ui->pushButtonLeft->hide();
}

MainWindow::~MainWindow()
{
    delete ui;
}

void MainWindow::resizeEvent(QResizeEvent* event)
{
    QPixmap bkgnd(":/images/background.jpg");
    bkgnd = bkgnd.scaled(this->size(), Qt::IgnoreAspectRatio);
    QPalette palette;
    palette.setBrush(QPalette::Background, bkgnd);
    this->setPalette(palette);
}


text:
Q: C# WCF Sessions with Asynchronous functions
What happens in the case of a wcf session that has created an asynchronous function (such as background automated emailing ) when the client closes session ie client.Close()/client.Abort()?
In otherwords if have some as below:
[OperationContract(IsOneWay = true, IsInitiating = true, IsTerminating = false)]
void RegisterUser(string user);

[OperationContract(IsOneWay = false, IsInitiating = false, IsTerminating = false)]
void SendEmails(T[] listofDetails);

[OperationContract(IsOneWay = false, IsInitiating = false, IsTerminating = true)]
void UnRegisterUser();

and SendEmails creates a task or async function (the async call isn't done client side) that sends off all the emails in the background.
And the user Terminates the session before all the emails are finished sending? Does the session still stay open and wait or does it close and the emailing just keeps going until it finishes or what happens?
Thanks All
Sorry if the question is a bit ambiguous :/

A: In your example you have defined a request-response operation called SendEmails which returns void. This is not the same thing as an asynchronous operation.
I am assuming you are creating a new background thread within the operation method which then goes away and send the emails.
In this instance the operation will return void to the caller once the operation method has finished execution. If the client then terminates the channel the background thread will continue its work.


text:
Q: Google Tag Manager: fire tag on element load I am working on a project and the site has a lot of the same pages - they are versions of the homepage. But, depending on what page you open, it will give you a different message in a lightbox.
The whole set-up is a bit strange to me, but that's what it is....
So there are countless pages, such as "~/erejib", "~/12312", "~123niwoenf123". Due to there being no fixed length, naming convention or anything, I cannot really use a regex.
However, I could say fire on all pages that contain this lightbox ID. Does Google Tag Manager support this at all?
Thanks,
Chris

A: Well yes, there is nothing build into Google Tag manager for this particular problem. I ended up writing all the existing pages that I want to exclude into a giant RegEx.


text:
Q: Is it correct/proper to use DialogBox as the main window? Is it correct-proper as in windows doesn't say it's bad or not recommended.
For example like this:
int APIENTRY _tWinMain(HINSTANCE hInstance,
                     HINSTANCE hPrevInstance,
                     LPTSTR    lpCmdLine,
                     int       nCmdShow)
{
    UNREFERENCED_PARAMETER(hPrevInstance);
    UNREFERENCED_PARAMETER(lpCmdLine);
    UNREFERENCED_PARAMETER(nCmdShow);

    INT_PTR result = DialogBox(hInstance, MAKEINTRESOURCE(IDD_MAINWINDOWBOX), nullptr, MainWindow);

    return static_cast<int>( result );
}

A: Using a Dialog Box as the main window is actually supported as one of the default configurations by MFC, so yes, that's fine (according to Microsoft).
For what it's worth, virtually every Windows app I've written in years used a dialog box as the main window, but that's because I don't write office-type applications.

A: Yes definitely...Haven't you seen calculator (calc.exe)? it is a dialog based application having main window as a dialog.


text:
Q: What does `::*` (colon colon star) means in C++? There is a segment of code incomprehensible when my friend was reading this hpp file. Specifically,

*

*what does certain formation such as A(B, C), int(int, int), or in this case T(Type::*) means? I've already seen usages such as std::function<int(int, int)>, but still have no idea what int(int, int), alone, means.

*what does Type::* mean? How can a asterisk mark follows :: directly?

A: ::* is used to declare a pointer to a member of class. So in this case, it's pointing to a member of the template type callled Type.
std::function<int(int, int)> is an std::function for holding a method that takes paramters of (int, int), and returns an integer result. (This is an example of the famously complicated C/C++ type declaration syntax).


text:
Q: Access table data in local PostgreSQL I installed PostgreSQL on my local machine and create the table in my own database.
Database properties looks like
Name: MyDB
Tablespace: pg_default
Default tablespace: pg_default
System database? No

And my table properties looks like
Name: mytable
Tablespace: pg_default
System table? No

But when I try to do
select * from mytable;

I am getting
ERROR: relation "mytable" does not exist

Create table statement
create table mytable (
  .....
);

Any suggestion?

A: I had the same issue, and clearly, if the create statements were including double quotes around the tables names, you have to use them too in your select statement to see the table (granted that you are the proper user with the proper privileges on tables). (and it's case sensitive even in Windows...)


text:
Q: Visual Studio Plugin for Team Explorer (TFS) - How to get a selection in query editor? I am developing a Visual Studio Plugin to extend TFS Query handling (2012 version).
After a lot of (re)search I am almost done.
What the plugin can do is extend the context menu in the Query Editor. There I can add additional filters, this works. But I would like to insert the filter above the selected row in the editor.
I cannot find a possibility to retrieve this selection.
I fetch the current QUeryDocument with
IWorkItemTrackingDocument wtd = GetActiveDocument();
IQueryDocument queryDoc = wtd as IQueryDocument;

public IWorkItemTrackingDocument GetActiveDocument()
{
    object _lockToken = new object(); // token used for locking the document
    if (DTE.ActiveDocument != null)
    {
        string activeDocumentMoniker = DTE.ActiveDocument.FullName;
        IWorkItemTrackingDocument doc = DocService.FindDocument(activeDocumentMoniker, _lockToken);
        if (doc != null)
        {
            doc.Release(_lockToken);
        }
        return doc;
    }

    return null;
}

But IQueryDocument does not seem to have a possibility to get the selected rows. There is a SelectedItemIds-Property, but this property contains the selected work item IDs in the results view, not in the query editor.
Any ideas?
Thanks,
Klaus


text:
Q: Differentiate between macros and keywords of the same name in lstlisting I'd like to display the following code fragment in a lstlisting environment:
\begin{tikzpicture}
  \duck[stripes=text]
  \stripes{}
\end{tikzpicture}

The syntax highlighting should be

*

*red for tikzpicture

*blue for commands \begin \duck \stripes \end

*orange for keyword stripes

*other elements like text should remain black (or should at least have another colour then the keywords)

I tried to misuse emphstyle to colour the keyword, but as there is a command of the same name \stripes also changes colour, while I only want stripes to be in orange and \stripes to remain blue.
This seems to be a known bug, from p. 31 of the listings documentation:

Bug: texcs... interferes with other keyword lists. If, for example, emph contains the word foo, then the control sequence \foo will show up in emphstyle.

Is there any  other way to colour keywords or workaround?
MWE:
\documentclass{article}

\usepackage{xcolor}
\usepackage{listings}

\lstdefinestyle{duckstyle}{%
    language={[latex]TeX},
    basicstyle=\footnotesize\ttfamily,
    %
    keywordstyle=\color{red!60!black}\bfseries,
    morekeywords={tikzpicture},
    %
    texcsstyle=*\color{blue}\bfseries,
    moretexcs={duck,stripes},
    %
    emphstyle=\color{orange!70!black},
    emph={stripes}
}

\lstset{style=duckstyle}

\begin{document}

\begin{lstlisting}
\begin{tikzpicture}% <- Perfect color
  \duck[stripes=text]% <- Perfect color
  \stripes{}% <- \stripes should be blue :(
\end{tikzpicture}% <- Perfect color
\end{lstlisting}

\end{document}

EDIT
To make things even more complicated, my real use case is to show the code in a tcblisting which has the unfortunate side effect that the perfect solution of Ulrike Fischer fails to compile the output of the listing.
\documentclass{article}

\usepackage{tikzducks}% needs version 0.4
% this will be available on ctan sometime in the next 24 hours
% currently: https://github.com/samcarter8/tikzducks/blob/master/tikzducks.sty

\usepackage{listings}
\usepackage[most]{tcolorbox}

\lstdefinestyle{duckstyle}{%
    language={[latex]TeX},
    basicstyle=\footnotesize\ttfamily,
    %
    keywordstyle=\color{red!60!black}\bfseries,
    morekeywords={tikzpicture},
    %
    texcsstyle=*\color{blue}\bfseries,
    moretexcs={duck,stripes},
    %
    moredelim=[is][\footnotesize\ttfamily\color{orange!70!black}]{|}{|},
}

\lstset{style=duckstyle}

\tcbset{listing options={style=duckstyle}}

\begin{document}

\begin{tcblisting}{title={duck}}
\begin{tikzpicture}
  \duck[|stripes|]
  \stripes{}
\end{tikzpicture}
\end{tcblisting}

\end{document}

EDIT2
Getting closer: The \pgfkeys{/duck/|stripes|/.style={stripes=#1}} solution works for \duck[|stripes|], but fails for \duck[|stripes|={\stripes[color=blue]}] with the error message
! Extra \fi.
\pgfkeyscurrentkey ->color\fi
                              \ifduck@cape \begin {pgfinterruptboundingbox} ...
l.2     \duck[|stripes|={\stripes[color=blue]}]

I'm ignoring this; it doesn't match any \if.

MWE:
\documentclass{article}

\usepackage{tikzducks}% needs version 0.4
% this will be available on ctan sometime in the next 24 hours
% currently: https://github.com/samcarter8/tikzducks/blob/master/tikzducks.sty

\usepackage{listings}
\usepackage[most]{tcolorbox}

\lstdefinestyle{duckstyle}{%
    language={[latex]TeX},
    basicstyle=\footnotesize\ttfamily,
    %
    keywordstyle=\color{red!60!black}\bfseries,
    morekeywords={tikzpicture},
    %
    texcsstyle=*\color{blue}\bfseries,
    moretexcs={duck,stripes},
    %
    moredelim=[is][\footnotesize\ttfamily\color{orange!70!black}]{|}{|},
}

\lstset{style=duckstyle}

\tcbset{listing options={style=duckstyle}}

\pgfkeys{/duck/|stripes|/.style={stripes=#1}}

\begin{document}

\begin{tcblisting}{title={working}}
\begin{tikzpicture}
  \duck[|stripes|]
  \stripes{}
\end{tikzpicture}
\end{tcblisting}

\begin{tcblisting}{title={not working}}
\begin{tikzpicture}
    \duck[|stripes|={\stripes[color=blue]}]
\end{tikzpicture}
\end{tcblisting}

\end{document}

A: As a work-around you can use a delimiter to get orange keywords:
\documentclass{article}

\usepackage{xcolor}
\usepackage{listings}

\lstdefinestyle{duckstyle}{%
    language={[latex]TeX},
    basicstyle=\footnotesize\ttfamily,
    %
    keywordstyle=\color{red!60!black}\bfseries,
    morekeywords={tikzpicture},
    %
    texcsstyle=*\color{blue}\bfseries,
    moretexcs={duck,stripes},
    %
    moredelim=[is][\footnotesize\ttfamily\color{orange!70!black}]{|}{|},
}

\lstset{style=duckstyle}

\begin{document}

\begin{lstlisting}
\begin{tikzpicture}% <- Perfect color
  \duck[|stripes|=text]% <- Perfect color
  \stripes{}% <- \stripes should be blue :(
\end{tikzpicture}% <- Perfect color
\end{lstlisting}

\end{document}

Edit
When using tcblisting (where the code is also executed) one must ensure that the key |stripes| is not unknown and does something senseful.
The easiest is to define alias-keys:
  \pgfkeys{/duck/|stripes|/.style={stripes={#1}}}


text:
Q: Checking if animated sliding panel is active I successfully implemented a sliding down panel in my app. with animations from an answer i found on stackoverflow.
But there are some features that i am trying to implement. And i don't know how to. I have sat down for hours trying to figure out how to do them but i still haven't able to solve my problems.
I have a layout that contains 2 buttons and an empty framelayout. OnClick of the buttons, a fragment transaction loads a fragment into the empty framelayout and the layout slides down. All these parts work fine.
The problems i am having now is:
1. How to check if the sliding panel is already active.
2. How to stop the panel from sliding up onClick of the same button if it is already active.
3. Also putting the fragment transaction inside the onClick method of the button, reloads the fragment even when it is active. how to i stop this.
Please i am still relatively new to app development. I have tried to solve this problem but havent had any success so far. So any help would be useful.
Also i would like to know if there is a better way of implementing this sliding down panel?
Thank you.
Here is my code:

*

*ExpandCollapseAnimation class that holds the animation
public class ExpandCollapseAnimation extends Animation {
private FrameLayout mAnimatedView;
private int mEndHeight;
private int mType;

/**
 * Initializes expand collapse animation, has two types, collapse (1) and expand (0).
 * @param view The view to animate
 * @param duration
 * @param type The type of animation: 0 will expand from gone and 0 size to visible and layout size defined in xml.
 * 1 will collapse view and set to gone
 */
public ExpandCollapseAnimation(FrameLayout view, int duration, int type) {
    setDuration(duration);
    mAnimatedView = view;
    mEndHeight = mAnimatedView.getLayoutParams().height;
    mType = type;
    if(mType == 0) {
        mAnimatedView.getLayoutParams().height = 0;
        mAnimatedView.setVisibility(View.VISIBLE);
    }
}

@Override
protected void applyTransformation(float interpolatedTime, Transformation t) {
    super.applyTransformation(interpolatedTime, t);
    if (interpolatedTime < 1.0f) {
        if(mType == 0) {
            mAnimatedView.getLayoutParams().height = (int) (mEndHeight * interpolatedTime);
        } else {
            mAnimatedView.getLayoutParams().height = mEndHeight - (int) (mEndHeight * interpolatedTime);
        }
            mAnimatedView.requestLayout();
    } else {
        if(mType == 0) {
            mAnimatedView.getLayoutParams().height = mEndHeight;
            mAnimatedView.requestLayout();
        } else {
            mAnimatedView.getLayoutParams().height = 0;
            mAnimatedView.setVisibility(View.GONE);
            mAnimatedView.requestLayout();
            mAnimatedView.getLayoutParams().height = mEndHeight;
        }
    }
  }
}

MainActivity:
   public class MainActivity extends ActionBarActivity {

    private boolean mActive = false;

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

        btntap();
        btnTwoTap();

    }

    public void btnTwoTap() {
        Button button2 = (Button) findViewById(R.id.openAnimTwo);
        FrameLayout frameLayout= (FrameLayout) findViewById(R.id.slidin);

        button2.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View arg0) {
                // TODO Auto-generated method stub

            FragmentManager fm = getSupportFragmentManager();
            FragmentTransaction ft = fm.beginTransaction();
            Fragment fragmen = new TestFragTwo();
            ft.replace(R.id.slidin, fragmen);
            ft.commit();

            }
        });

    }

    private void btntap() {

        final FrameLayout animatedFrameLayout = (FrameLayout) findViewById(R.id.slidin);

        final Button button = (Button) findViewById(R.id.openAnim);

        button.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {

                ExpandCollapseAnimation animation = null;

                if(mActive) {
                    animation = new ExpandCollapseAnimation(animatedFrameLayout, 1500, 1);
                    mActive = false;

                }
                else if (mActive = false){

                    animation = new ExpandCollapseAnimation(animatedFrameLayout, 0, 1);
                }
                else {
                    animation = new ExpandCollapseAnimation(animatedFrameLayout, 1000, 0);
                    mActive = true;
                }
                animatedFrameLayout.startAnimation(animation);

                //button.setVisibility(View.GONE);

                }
        });
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

}


text:
Q: brew doctor returns not a valid keg (Trying to uninstall liberica-jdk-8-full installed via homebrew) I was trying to install autopsy using this guide
https://slo-sleuth.github.io/tools/InstallingAutopsyOnMacOS.html which I couldn't get it to work. So I have decided to uninstall and find something else to work with.
Kindly advise how can I uninstall liberica-jdk-8-full? I have ran brew doctor and below is the error I get.
Error: /Library/Java/JavaVirtualMachines/liberica-jdk-8-full.jdk/Contents/Home is not a valid keg

A: Ok I was able to fix my issue!! (related s/o link)

*

*Remove liberica-jdk8-full from /usr/local/Caskroom

*Remove liberica-jdk-8-full.jdk from /Library/Java/JavaVirtualMachines

*Run brew cleanup to remove the broken symlink /usr/local/opt/openjdk


text:
Q: Can an SVN checkout be multi-threaded? I have a repo with 30k+ small files, and I can only access the server over the internet via https://.  Checkout are very, very slow.  On the order of hours.  Internet connection speed is ~20Mbs and local machine is 3Ghz multi-core & 10k RPM HD.
(svn:// protocol is not an option, sadly.)
So my question:
Can svn do a multi-threaded parallel checkout of a working copy?
It looks like the svn checkout is going file-by-file in a sequential order.  There is a minuscule delay between each file and I suppose that's the http request/reply and possibly my local filesystem's delays.  (Perhaps a little server filesystem latency as well?)
Thanks

A: You can use GNU Parallel for parallel svn checkouts.
Example-
svn ls 'https://foo/bar' | parallel svn export 'https://foo/bar/'{}

This will start parallel svn checkouts under 'bar' directory.

A: Might sparse checkouts (newer SVN versions, >= 1.6 or so!) happen to help performance-wise?
time svn co --depth=empty http://URI

cd svn_repo_root/

time svn up --depth=infinity *

Also, perhaps it's useful to supply server and/or client with SSDs in order to work around bad operating system or SVN server/client implementation performance in the case of multi-lookup of many small files (due to seek time latency thoroughly dominating file system operations in case of small files - seeking is much less of a problem with SSDs).
And perhaps it's worth ensuring cache-hotness of all files on the server in advance of checking things out, by writing a script to parse through the entire repository tree on the server.

A: I don't know of a command, but you could write a small Python (or the tool of your choice) script to help.  "svn list" gives you the name of each subdirectory.  You can then do a checkout of each subdirectory in the background so they happen in parallel.  You may need to do this at the 2nd/3rd/whatever level deep depending on your directory structure and where all the tiny files reside.
I'm assuming you don't have 30K files in the same directory of course.

A: Although I can't think of any reason why SVN could not checkout more than one file at a time,  I don't know any SVN client that does so.

A: Would it not depend a lot on the ping time to the server?
If the ping is long, then you may not be able to do anything about it.
There is also a chance that the router that handles the firewall is falling behind and using something like stateful packet inspection, ie looking at each packet. the router can be changed to let stuff from the svn server escape packet scanning.


text:
Q: get html from a variable by id i have a variable name value in my javascript code that contain html data.i want to get the data inside form specific id  that is inside #myDiv
  var value="

Hi cname@gmail.com

              sgdhsagdhagh
              dhsajdgasj
              cjzjcg

"

Thanks

A: You should create a DOM element, then traverse up to it and get html() or .text()

  var value = '
\

Hi cname@gmail.com
\

\

\

\
              sgdhsagdhagh\
              dhsajdgasj\
              cjzjcg\

\

';

  alert($(value).find('#myDiv').html())

If you need to get parent element, then use
alert($('
', {html: value}).find('#myDiv').html())

A: How about you do like this?
var variable = "stuff n things";
document.getElementById( 'myDiv' ).innerHTML = variable;

Thats the native way :)
EDIT:
if you want to get the data you just do like this:
var variable = document.getElementById( 'myDiv' ).innerHTML;

That will give you the markup of whats inside the div.
Or use document.querySelector("#myDiv") to get the first match on the selector.querySelectorAll returns array.

A: You can use the HTML of the value variable to create an jQuery object. From this object you can search for the element with the id, and get its HTML content:
var html = $(value).find('#myDiv').html();
console.log(html); //sgdhsagdhaghdhsajdgasjcjzjcg

Or a pure javascript implementation:
var el = document.createElement('div');
el.innerHTML = value;
var html = el.getElementById('myDiv').innerHTML;
console.log(html); //sgdhsagdhaghdhsajdgasjcjzjcg

A: Using plain Javascriptuse:
document.getElementById("myDiv").innerHTML;

Using jQuery:
$("#myDiv").html();

A: There are Two ways- Angular way-
var elem = angular.element(value);
var innerDive=elem[0].getElementById('myDiv');
var text= angular.element(innerDive[0]).innerText;

Jquery-
var text= $(value).find('#myDiv').text();


text:
Q: SQL Select Help I'm trying to count how many created vs published posts there are per user in my database.
POST ID | USER ID | STATUS

...and an example would be

User ID 1 has 5 posts (5 distinct post IDs) with 3 STATUS = CREATED and 2 STATUS = PUBLISHED. I want the output to show the following columns

USER  CREATED  PUBLISHED
----------------------------
 1    3        2

A: Use:
  SELECT t.user,
         SUM(CASE WHEN t.status = 'CREATED' THEN 1 ELSE 0 END) AS created,
         SUM(CASE WHEN t.status = 'PUBLISHED' THEN 1 ELSE 0 END) AS published
    FROM YOUR_TABLE t
GROUP BY t.user