text:
Q: AngularJS: stale UI trying to load cachebusted HTML files that no longer exist when new version deployed I have an angularjs/ui-router application. All the html templates, which are lazyloaded by the framework, are cachebusted so that they are named myTemplate.someHash.html, and the references to those templates are also updated compile-time.
One problem that sometimes occurs is when I deploy a new version while a user is using the application. The sequence of events is as following:

*

*The user has opened a page, which has a link on it to a state called Summary. The Summary state uses an HTML template called summary.html. But since we're cachebustering the HTML templates, this file is actually named summary.12345.html in version of the application currently loaded in the user´s browser.

*A new release is deployed, which contained some changes to summary.html, causing it to get a new hash, so it's now called summary.98765.html.

*The user clicks on the link, and angular tries to fetch summary.12345.html which nolonger exists, causing a 404.

Is there a good pattern for solving this?
My initial thought is to append some HTTP header in all requests, something like Expected-Version: 999 (where 999 is the build number generated in CI), and if that is not the version running on the server, then the server will respond with something like "410 Gone", in which case the application will ask the user to refresh the browser.
But it would require some work on the server side, and I'm not sure how to inject this logic into the template loading on the client side either.
Also, since new versions are typically deployed a few times per week (sometimes many per day), and most of those releases don't even contain any changes that would break the SPA in the above way, I don't want to force the users to reload the page all the time.
Could one approach be to only show the "please refresh" message when a request results in a 404 AND the response contains a header that indicates that you're running a stale version of the SPA?
Or maybe there is a simpler way?

A: I solved it in the following way.
I decided I don't want to ask users to refresh their browser every time a new release has been deployed, because many of those releases only contain backend changes.
I only want to ask them to refresh when a release has been deployed (since the time they opened the app in their browser) which contains changes to either:

*

*the javascript application (which is served as two bundles), or

*any of the html templates that angular lazyloads.

So I had to introduce the notion of a UI version. I decided that the definition of this UI version should be the SHA256 hash of all the filenames (just the names, since those already contain hashes for cachebusting) of the html templates mentioned above, concatenated with the names of the two js bundles (which are also cachebusted).
Here's the solution.
Part 1
I added a step in my CI pipeline, after the js app has been compiled and cachebusted, but before the whole application is built into a Docker image. This new build step looks like this:
const glob = require("glob");
const crypto = require('crypto');
const fs = require('fs');

const jsPromise = new Promise(resolve => {
    glob("./js/*.js", {}, function (err, files) {
        if (!err) {
            resolve(files);
        }
    });
});

const htmlPromise = new Promise(resolve => {
    glob("./app/**/*.html", {}, function (err, files) {
        if (!err) {
            resolve(files);
        }
    });
});

Promise.all([jsPromise, htmlPromise]).then(([files1, files2]) => {
    const allFiles = files1.concat(files2);

    fs.writeFileSync(
        './ui-version.env',
        `UI_VERSION=${crypto.createHash('sha256').update(allFiles.sort().join()).digest('hex')}`
    );
});

As you can see, it writes it to a file called ui-version.env. I then refer to this file in the docker-compose.yml using the env_file command. This way, the backend application is now aware of the current UI version. And the backend now serves this data at the HTTP endpoint GET /ui-version.
Part 2
When the frontend app is loaded, it calls the above mentioned endpoint and stores the current UI version in memory.
When a new release has been deployed, a websocket message is sent to all connected frontend apps with a notification to check whether or not they are still running an up-to-date UI version. They do this by requesting the new endpoint mentioned above, and comparing the result to the version it saved on load.
What about users who´s computers were in sleep mode or without internet connection when the websocket message was sent out?
I already have event listeners setup in the SPA that goes off when the computer comes back from sleep mode, or when it recovers internet connection. So any of those events will now also trigger the UI version check.
To be honest, I'm not super excited about this solution. There are a lot of moving parts. It would be great if someone could offer a simpler solution. But unfortunately I'm skeptical that I will get any good answers at all.


text:
Q: Does a field being named "value" have any special semantics? Examples in the InfluxDB documentation usually include a field named value. For instance, https://docs.influxdata.com/influxdb/v1.4/write_protocols/line_protocol_reference/#examples contains many example inserts that all include a value field, such as:
INSERT mymeas value=1.0

Is this use of value just a convention, or is there some special behaviour associated with the name value? I know that inserts without a value field are legal and that I can query for them with select queries just like rows with a value, but I don't know whether there's some special handling of values hidden under the surface that I'm not noticing.

A: The use of value as field name appears to just be a convention in the documentation. Neither the query language spec for identifiers or field keys mention anything about it (and value is not a keyword).

redpajama_set_name: RedPajamaStackExchange


text:
Q: How do I insert a daterange amongst other placeholder variables in postgresql & express? I apologize for probably the simplest question, but I am self teaching myself SQL & PostgresSQL by jumping into the deep end (I guess!) and ran across this issue.
I'm trying to insert a large amount of placeholders into a INSERT statement, but I can't seem to figure out the correct syntax to pass a daterange into the placeholder. Here is my code:
INSERT INTO campgrounds (campground_name, email_address, address, city, state, zipcode, phone_number, website, number_of_sites,maximum_rv_length, max_amps, description, seasondates, campground_type, region, open_date, close_date) VALUES($1, $2, $3, $5, $5, $6, $7, $8, $9, $10, $11, $12,[$13,$14),$15,$16,$17,$13,$14) RETURNING id

In this example, seasondates is a daterange type, and $13 and $14 are the dates I am trying to insert.
Thank you for your help!

A: Use the function daterange():
INSERT INTO campgrounds (
    campground_name,
    email_address,
    address,
    city,
    STATE,
    zipcode,
    phone_number,
    website,
    number_of_sites,
    maximum_rv_length,
    max_amps,
    description,
    seasondates,
    campground_type,
    region,
    open_date,
    close_date
)
VALUES
    ( $1, $2, $3, $5, $5, $6, $7, $8, $9, $10, $11, $12,daterange($13,$14,'[)'),$15,$16,$17,$13,$14
    ) RETURNING ID;


text:
Q: Integer multiplied by float and then divided by same float - a clean way to force value back to original integer Alright so we have the classic 1 * 1/3 * 3 = 0.9999999. I understand why this is the case.
In my use case, I am trying to result in an integer.  I am happy to take the floor of my value, except when infinite precision math dictates that we should have resulted in an integer to begin with (see: the above use case).
Is there a commonly used way to achieve this?
Examples:
double myFloat = 1.0/2.0;
1 * myFloat * 2 = 2   RESULT: 2
myFloat = 1.0/2.0;
2.5 * myFloat * 2 = 2.5 RESULT: 2
myFloat = 1.0 / 3.0;
1 * myFloat *3 = .9999 RESULT: 1
myFloat = 1.0 / 3.0;
.9 * myFloat *3 = .9   RESULT: 0
One way I thought of was to always tack on some delta to my result before flooring it.  I want to achieve my result in a clean, commonly accepted way though.
EDIT: Changed made for clarity based on feedback.

A: Round f(x) to nearest integer, round(f(x))
Compare f(x) and round(f(x)). If they are close enough for the difference to be due to rounding, use round(f(x)) as result. If not, use floor(x).
If the inputs are all of similar magnitude, it may be sufficient to use abs(f(x)-round(f(x)) < epsilon for some fixed number epsilon. If not, use abs((f(x)-round(f(x))/f(x)) < epsilon for non-zero f(x).


text:
Q: AS3 library for Socket.io I'm using node.js+socket.io in my projects, and one of the issues that bothers me the most is absence of normal AS3 library than can handle communications between as3 and node.js using socket.io.
In my last project, I used https://github.com/simb/FlashSocket.IO this library, but I had to roll back to node.js v0.8.25.
So - requirements:

*

*Works with node.js v0.10.x

*Works with socket.io v0.9.x

*Secure connection support (wss)

It would be nice to have more than one library, maybe someone knows a better one?
Thanks!

A: I also needed this, so here's what I used: https://github.com/sinnus/socket.io-flash.
requires Socket.IO(>= v.0.8)


text:
Q: How can you specify a namespace in a BizTalk expression shape? How can you specify a namespace in a BizTalk expression shape?
We want to check if the message has the EDI.ErrorDescription context property, so using code in an expression shape like ...
EDI.ErrorDescription exists msgTest

which doesn't show any errors, but then on building the solution, the file0.cs throws an error because we a conflicting Company.Project.EDI namespace.
But I can't find anyway to disambiguate the statement in the expression shape?

A: It seems like your Company.Project.EDI namespace is colliding with the EDI namespace that BizTalk uses.
For testing purposes I would try to rename your Company.Project.EDI namespace to something like Company.Project.SomethingOtherThanEdi. This will make the two namespaces different and will most likely work for you.
Hope this helps!

A: Unfortunately, the Orchestration Designer is very sensitive to namespace collisions.  So, yes, the two EDI namespace parts are colliding.
There is no way to specify a using or using alias either.
You have two options:

*

*Change Company.Project.EDI (as noted)

*Add a level of redirection through a helper class with a non-conflicting namespace.


text:
Q: How can I test a class? I have a class like this
public class BonusImageHandler
{   private static IStorageProvider _storageProvider;
    private static Type storageProviderType;
    private static readonly object _lock = new object();
    private static IStorageProvider StorageProvider
    {
        get
        {
            lock (_lock)
            {
                if (_storageProvider == null)
                {
                    lock (_lock)
                    {
                        _storageProvider = (IStorageProvider)Activator.CreateInstance(storageProviderType);
                    }
                }
            }
            return _storageProvider;
        }
    }

    public BonusImageHandler(string providerTypeName)
    {
        storageProviderType = Type.GetType(providerTypeName);
    }

   public void ProcessRequest(HttpContext context)
   {
        //do some thing here
    }

    private static string ParseInputs(string baseUrl, string imageType)
    {
      //do other things
     }
}

the constructor is not static because it takes a string as an argument and the property private static IStorageProvider StorageProvider is a static one. Team leader told me it will not work this way, why?? how can I test it?? how can I pass the httpContext to the ProcessRequest function.
I'm sorry for this silly question but I'm still a beginner.

A: This is bad because an instance constructor assigns the static field; consider:
var x = new BonusImageHandler("foo");
var y = new BonusImageHandler("bar");

now... what is the static storageProviderType, and why should that make sense? What handler does x use? (hint: it isn't "foo").
Now consider multiple callers, perhaps on different threads, calling this seemingly at random.
Frankly, it looks like this should be more like:
public static void InitProvider(string providerTypeName) {...}

but by the time you've done that, you then start thinking maybe it should be:
public static void InitProvider(Type providerType) {...}

or even clearer:
public static void InitProvider(IStorageProvider provider) {...}

Or: just make it an instance field, so you can pass (perhaps via an IoC/DI tool) the provider into each instance separately, i.e.
private readonly IStorageProvider provider;
public BonusImageHandler(IStorageProvider provider) {this.provider = provider;}


text:
Q: awk adds undesired newline at the end of last detected parameter I wrote an awk script designed to inject a function in certain definition files. It looks for lines containing a two word phrase, when found it adds a paragraph after that line, in which the second parameter is used at one point. In this example: If file.txt contains the words "foo bar" on a line, we want to add after it the lines "{" followed by "func(bar)" followed by "}", awk should see $1 as "foo" (static identifier) and $2 as "bar" (can be anything so we read it):
awk '{
    print $0
    if($1 == "foo" && $2 != "") {
        print "{"
        print "func(" $2 ")"
        print "}"
    }
}' file.txt > file_new.txt

The issue is that $2 gains an unwanted newline at the end. This particularly seems to happen if there's nothing else on the line after it. Therefore the result in the produced file ends up being this:
foo bar
{
func(bar
)
}

Instead of the correct format:
foo bar
{
func(bar)
}

Everything else works fine, only problem is this newline getting stored in the second parameter for a strange reason. What do you suggest to get rid of it?
Regarding separators: It's worth noting the detected line can contain any mixture of spaces and tabs, either before after or between the two words. This means something like "    foo    bar    " should still ensure $1 is foo and $2 is bar.
Edit: With the provided example below, the file.txt would be something among the following lines. For different tests try adding spaces or tabs before / between / after foo and bar, as well as the empty line under it:
abc xyz
foo bar

123 789

This is the output of grep foo file.txt | od -c on the original file I'm getting an issue with, it's larger and contains different words but is the exact same functionality as simplified here:
0000000  \t   s   p   e   c   u   l   a   r   m   a   p  \t
0000020       t   e   x   t   u   r   e   s   /   d   a   r   k   m   o
0000040   d   /   m   e   t   a   l   /   f   l   a   t   /   g   e   n
0000060   _   s   m   o   o   t   h   _   g   o   l   d   0   1   _   s
0000100   _   t   i   l   i   n   g   _   1   d  \n                   s
0000120   p   e   c   u   l   a   r   m   a   p  \t                   t
0000140   e   x   t   u   r   e   s   /   d   a   r   k   m   o   d   /
0000160   m   e   t   a   l   /   f   l   a   t   /   g   e   n   _   s
0000200   m   o   o   t   h   _   g   o   l   d   0   1   _   s   _   t
0000220   i   l   i   n   g   _   2   d  \n
0000231


text:
Q: How to find the maximum of a column in Hive? My code:
add jar /home/edureka/Downloads/csv-serde-1.1.2.jar;

Create table loan(id int,loan_amt int,grade string)
row format serde 'com.bizo.hive.serde.csv.CSVSerde'
stored as textfile;

load data local inpath 'Desktop/LMS/Hive_Project/Loan Data.csv' into table loan;

select id,loan_amt,grade from loan
where grade="A"
sort by loan_amt desc
limit 5;

But my results is wrong.
I am getting some random valuw which is not the top 5

A: select    id,loan_amt as ,grade
from      loan
where     grade="A"
order by  cast (loan_amt as int) desc
limit     5;

1.
ORDER BY (and not SORT BY)

Difference between Sort By and Order By
  Hive supports SORT BY which sorts the data per reducer.
  The difference between "order by" and "sort by" is that the former guarantees total order in the output
  while the latter only guarantees ordering of the rows within a reducer.
  If there are more than one reducer, "sort by" may give partially ordered final results.
https://cwiki.apache.org/confluence/display/Hive/LanguageManual+SortBy

2.
cast loan_amt to int

Limitation
  This SerDe treats all columns to be of type String.
  Even if you create a table with non-string column types using this SerDe, the DESCRIBE TABLE output would show string column type.
  . The type information is retrieved from the SerDe.
  To convert columns to the desired type in a table, you can create a view over the table that does the CAST to the desired type.
https://cwiki.apache.org/confluence/display/Hive/CSV+Serde


text:
Q: Removing unwanted files from local and reverse commit/merge My repository is a mess right now...
I have a messed up merges and commits... I want to go back to a specific commit because it has the clean files. Right now I have a few filename.orig in my local, and its in my recent merge because of conflicts I was going through. I'd like to revert my local files to the clean commit (deleting all the crap), and remove all the bad commit/merge and make the clean commit master. Is this possible?
This is what my commit history looks like:
Merge (sha-1) ->
Clean Commit (sha-2) ->
bad commit (sha-3) ->
bad merge (sha-4) ->
bad merge with .orig (sha-5)

A: As I already pointed out in the comments, your question is basically a duplicate of How to revert Git repository to a previous commit?, where the top voted answer offers two solutions that are relevant to you.
Solution 1: Hard Reset
You mentioned that you already pushed to your remote. That's OK, if you're not sharing your branch with other people, then you can simply do a hard reset back to the commit that you want to restore, and then force push back to your remote:
git reset --hard sha-2
git push origin HEAD -f

Warning: don't do this if you're sharing your branch with other people, or at least if it's not OK with them if you throw away commits on the remote branch like this. Those other people may have their own work based off of the old commits that you're throwing away, so it creates more work for those users to resync their own commits with the newly reset branch.
If you can't use this solution for the reason above, then you can use the following alternative solution, as mentioned in How to revert Git repository to a previous commit?.
Solution 2: Revert
This solution simply reverts the previous commits by creating new commits that are a reverse-patch. This is safe to use even if other users are sharing your branch, because it doesn't throw away new commits, it just creates new ones, so it isn't as confusing to synchronize with as throwing away commits would be:
git revert --no-edit sha2..sha5

That will revert the commits in the range (sha2, sha5], where sha2 is an exclusive starting point, meaning it isn't included in the reverts. Then you can simply push the results to your remote,
git push origin HEAD

Documentation

*

*Official git-reset(1) Manual Page

*Official git-revert(1) Manual Page
Additional Notes
I tried to have this question closed as a duplicate of How to revert Git repository to a previous commit?, but it looks like the question isn't getting enough close votes, and might not be closed, so that's why I decided I better answer it just in case it isn't.

A: Try to use:
git reset --hard <previous-commit-hash>

This resets everything to your previous commit. and you will get the fresh copy of your previous-commit-hash.


text:
Q: Displaying data through std Class Object and Array in PHP I am having trouble in displaying data through std Class Object and Array in PHP. Basically I have fetched data from .wsdl file through a web service.
Below is the screenshot of some data. Kindly go through this screenshot.

I am trying to display items:

*

*Ldate

*Ltime

*Satza

For this I am using:
foreach($data as $objects){
echo $objects->Itab->item[0]->Ldate;}

Here $data is an object which contains all values fetched from .wsdl file. I don't understand where I am doing wrong.
Kindly tell me a way by which I can display these three values (Ldate, Ltime, Satza) in a loop.


text:
Q: Mac Downloads Folder in dock doesn't show Icons My Downloads folder in the dock looks like this:

If I click on it, there are also no icons.

I tried removing it from dock and adding it back, but it shows the same result.
My system info:

The system was freshly installed about a month ago.

A: As @benwiggy mentioned, a simple reboot worked...


text:
Q: Applying lambda functions across separate RDD objects

I have an rdd containing the values below.
rdd_2 = sc.parallelize([('f3.txt', 'of', 0.0),
 ('f3.txt',
  'no',
  0.00023241396735284342),
 ('f3.txt',
  'may',
  0.00042318717429693387),
 ('f3.txt',
  'love',
  0.00036660747046705975),
 ('f3.txt',
  'romantic',
  0.00022935755451437367)])

I wish to filter this RDD by the words ('romantic', 'love') using a lambda function such that my resulting output is:
([('f3.txt', 'of', 0),
 ('f3.txt',
  'no',
  0),
 ('f3.txt',
  'may',
  0),
 ('f3.txt',
  'love',
  1),
 ('f3.txt',
  'romantic',
  1)])

I have tried the following code but i get an error:
querylist = ['romantic', 'love']
q = rdd_2.map(lambda x : x[2]=1 if x[1] not in querylist else x[2]=0)

SyntaxError: invalid syntax

What should i do?

A: You can not assign values like that in a lambda function. Instead return a new object containing the modified values.
Try this:
querylist = ['romantic', 'love']
q = rdd_2.map(lambda x : (x[0], x[1], 1 if x[1] not in querylist else 0))

Or equivalently;
q = rdd_2.map(lambda x : (x[0], x[1], int(x[1] not in querylist)))


text:
Q: Serializing a tree structure using JAXB in Java So I have a tree implemented my custom tree structure moreless like this:
The tree class:
@XmlRootElement
public class Tree {

   Set<? extends TreeNode> nodes;
   @XmlElement
   Set<? extends TreeNode> getNodes() {...}
}

The abstract node:
public abstract class Node {
   Set<? extends Node> children;
   private String name;

   @XmlAttribute
   public String getName() {...}
   @XmlElement
   public abstract Set<? extends Node> getChildren();

}

The group (could contain groups and entities):
@XmlRootElement(name = "group")
public class Group extends Node {

    private final Set<Group> groups = new HashSet<Group>();
    private final Set<Entity> entities = new HashSet<Entity>();
    public Set<Group> getGeoups() { ... }
    public Set<Entity> getEntities() { ... }
}

The node:
@XmlRootElement(name = "entity")
public class Entity extends Node {

    public Set<DashboardNode> getChildren() {
        return Collections.<DashboardNode> emptySet();
    }
}

My problem is, that JAXB doesn't use diffrent names for groups and entities. I would like to get result similar to:
<tree>
   <node>
       <group>
            <group>
                <entity/>
            </group>
       </group>
   </node>
   <node>
       <group>
           <entity/>
       </group>
       <group>
       </group>
       <entity/>
   </node>
</tree>

And I get this instead:
<tree>
   <node>
       <children>
            <children>
                <children/>
            </children>
       </children>
   </node>
   (...)
</tree>

IF i remove the annotation in my abstract node class on the getChildren() method I would reveive only this:
<tree>
   <node>
   </node>
  <node>
   </node>
</tree>

A: Have a look at the @XmlElements annotation, adding a suitable one of these to the children property of Node should achieve what you're after.

A: The problem is that your group 'is-a' node. What is the serialiser to do when it encounters an object that both has 'children' and has 'groups'?
It may be better to avoid the java inheritance altogether.
Actually, you don't have a @XMLElement annotation on getGeoups() [sic] or getEntities() either...


text:
Q: Proper way to replace NSTextStorage in NSTextView? I am making some text viewer app. Currently I need very frequent and precise line handling ability, so I want to subclass NSTextStorage class. But I couldn't find any method to set a new text storage to NSTextView. The only method I could find was
-[NSLayoutManager replaceTextStorage:]

method. But it's confusing whether this is what I was looking for. Because it seems just replace text storage of linked NSLayoutManagers instead of NSTextView.
I also considered subclassing NSTextView and overriding -textStorage method, but if the class is not designed for subclassing, it will make undefined result.
Anyone has tried to use custom NSTextStorage on NSTextView? How can I do this? Or is this prohibited by design?

A: You can do something like this to change the storage for an NSTextView:
NSTextStorage *newStorage = [[NSTextStorage alloc] initWithString: @"test"];

[aTextView.layoutManager replaceTextStorage: newStorage];

Since NSTextStorage is a subclass of NSMutableAttributedString you can manipulate it with all of the same methods.


text:
Q: Как правильно получить данные из form и отправить их GET-запросом? По заданию мне нужно взять из form данные (x, y, r) и передать их с помощью GET-запроса. Я понимаю, что это надо сделать с помощью url, но как правильно получить эти данные? Вот нерабочий вариант:
    var formData = new FormData(document.getElementById("coordinates-form"));
    const sendButt = document.getElementById("submit-button");
    const submit = function (e) {
        e.preventDefault();
        fetch("php/get_data.php?x=" + formData.get("x") + "&y=" + formData.get("y")
         + "&r=" + formData.get("r")).then(response => response.text())
            .then(response => document.getElementById('result-table').innerHTML = response);
    };
    sendButt.addEventListener('click', submit);

Вот моя форма.

X:

                    -3
                        <input class="x_radio" type="radio" name="x" value="-3">

                    // еще пару штук таких

                 Y:
                    <input id="y-text" class="y-text-input" type="text" name="y" placeholder="y value" required/>

R:

                    1
                        <input class="r-checkbox" type="checkbox" name="r" value="1" checked>

                    // еще пару штук таких

                <button id="submit-button" type="submit">Отправить</button>
                <button id="clear-button"type="reset">Очистить</button>
            </form>

В адресной строке нормально показываются параметры, однако через get() класса FormData не получается. Как можно их получить и как правильно сделать запрос?

A: Поместите
var formData = new FormData(document.getElementById("coordinates-form"));
внутрь функции
const submit = function (e) {...


text:
Q: MySQL select query for date range with same time TABLE
EventID --- EventTime (TIMESTAMP)
1   2013-09-29 12:00:00.0
2   2013-09-29 12:01:00.0
3   2013-09-29 12:03:00.0
4   2013-09-28 1:03:00.0
5   2013-09-27 23:03:00.0
6   2013-09-26 17:03:00.0
7   2013-09-25 12:01:00.0
8   2013-09-24 20:03:00.0
9   2013-09-23 5:03:00.0
10  2013-09-23 12:01:00.0

I want to retrieve rows, in MySQL, which satisfy given date range with same time.
So, if I query to retrieve rows with '2013-09-26 12:01' as EventTime value for +/- 5 days, I expect to get 2nd, 7th and 10th rows.
Please help frame SQL statement. Thanks!

A: WHERE EventTime >= '2013-09-26 12:01' - INTERVAL 5 DAY
  AND EventTime <= '2013-09-26 12:01' + INTERVAL 5 DAY
  AND TIME(EventTime) = TIME('2013-09-26 12:01')

A: You could use the mysql HOUR and MINUTE functions
https://dev.mysql.com/doc/refman/5.0/fr/date-and-time-functions.html

A: That does exactly what you try to achieve:
SELECT * FROM events WHERE
HOUR(EventTime)=HOUR('2013-09-26 12:01') AND
MINUTE(EventTime)=MINUTE('2013-09-26 12:01') AND
EventTime BETWEEN
   DATE_SUB('2013-09-26 12:01', INTERVAL 5 day) AND
   DATE_SUB('2013-09-26 12:01', INTERVAL -5 day)


text:
Q: How to change velocity of startScroll() I'm using this answer to implement a marquee textView in my app, but I want to be able to change the velocity of it without having to set a duration of the Scroller.
If I set a duration for the Scroller, then the velocity of the text will be dependent on how much text there is, but what I want is for the velocity to be constant.
Is there any way to do this?
If not, is there any other way to make text automatically scroll at a certain velocity?

A: You are misunderstanding the code.
You have to set a duration for the scroller otherwise how would it know how much time to take.
So now we have to make the velocity of the scroller constant.
But velocity = distance / duration
So the way to make that constant is to make the duration a function of distance
For eg. IF duration =2* distance
velocity= 2
and so on.
From the code you've posted
     int distance = scrollingLen - (getWidth() + mXPaused);
     int duration = (new Double(mRndDuration * distance * 1.00000
                                  / scrollingLen)).intValue();

Now duration= distance * constant /scrollingLen
So just remove the scrollingLen and it'll be a pure function of distance giving you constant velocity
duration= distance * constant /anotherConstant


text:
Q: GeoWebCache tiling failing due to topology exception I am running GeoServer 2.8 WAR on an Ubuntu machine in Tomcat 7.  I have GeoWebCache integrated directly and it does cache and serve some tiles.  However, in some areas I get errors when I attempt to view the location or seed the cache.  The relevant part of the log is as follows (which suggests a topology error):
2015-08-01 17:40:47,976 ERROR [geoserver.ows] -
org.geoserver.platform.ServiceException: Rendering process failed
    at org.geoserver.wms.map.RenderedImageMapOutputFormat.produceMap(RenderedImageMapOutputFormat.java:569)
    at org.geoserver.wms.map.RenderedImageMapOutputFormat.produceMap(RenderedImageMapOutputFormat.java:260)
    at org.geoserver.wms.map.RenderedImageMapOutputFormat.produceMap(RenderedImageMapOutputFormat.java:132)
    at org.geoserver.wms.GetMap.executeInternal(GetMap.java:504)
    at org.geoserver.wms.GetMap.run(GetMap.java:248)
    at org.geoserver.wms.GetMap.run(GetMap.java:119)
    at org.geoserver.wms.DefaultWebMapService.getMap(DefaultWebMapService.java:320)
    at sun.reflect.GeneratedMethodAccessor282.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:606)
    at org.springframework.aop.support.AopUtils.invokeJoinpointUsingReflection(AopUtils.java:319)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.invokeJoinpoint(ReflectiveMethodInvocation.java:183)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:150)
    at org.geoserver.kml.WebMapServiceKmlInterceptor.invoke(WebMapServiceKmlInterceptor.java:34)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:172)
    at org.geoserver.gwc.wms.CacheSeedingWebMapService.invoke(CacheSeedingWebMapService.java:62)
    at org.geoserver.gwc.wms.CacheSeedingWebMapService.invoke(CacheSeedingWebMapService.java:36)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:172)
    at org.geoserver.gwc.wms.CachingWebMapService.invoke(CachingWebMapService.java:80)
    at org.geoserver.gwc.wms.CachingWebMapService.invoke(CachingWebMapService.java:55)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:172)
    at org.geoserver.ows.util.RequestObjectLogger.invoke(RequestObjectLogger.java:55)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:172)
    at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:202)
    at com.sun.proxy.$Proxy58.getMap(Unknown Source)
    at sun.reflect.GeneratedMethodAccessor235.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:606)
    at org.geoserver.ows.Dispatcher.execute(Dispatcher.java:841)
    at org.geoserver.ows.Dispatcher.handleRequestInternal(Dispatcher.java:275)
    at org.springframework.web.servlet.mvc.AbstractController.handleRequest(AbstractController.java:153)
    at org.geoserver.gwc.GWC.dispatchOwsRequest(GWC.java:1209)
    at org.geoserver.gwc.layer.GeoServerTileLayer.dispatchGetMap(GeoServerTileLayer.java:625)
    at org.geoserver.gwc.layer.GeoServerTileLayer.getMetatilingReponse(GeoServerTileLayer.java:569)
    at org.geoserver.gwc.layer.GeoServerTileLayer.seedTile(GeoServerTileLayer.java:764)
    at org.geowebcache.seed.SeedTask.doActionInternal(SeedTask.java:136)
    at org.geowebcache.seed.GWCTask.doAction(GWCTask.java:76)
    at org.geowebcache.seed.MTSeeder.call(MTSeeder.java:36)
    at org.geowebcache.seed.MTSeeder.call(MTSeeder.java:25)
    at java.util.concurrent.FutureTask.run(FutureTask.java:262)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
    at java.lang.Thread.run(Thread.java:745)
Caused by: com.vividsolutions.jts.geom.TopologyException: found non-noded intersection between LINESTRING ( -446792.34 6930399.07, -440903.77 6936464.74 ) and LINESTRING ( -437011.5849751517 6937523.641382978, -447860.88 6934195.51 ) [ (-441090.5017453493, 6936272.392257541, NaN) ]
    at com.vividsolutions.jts.noding.FastNodingValidator.checkValid(FastNodingValidator.java:130)
    at com.vividsolutions.jts.geomgraph.EdgeNodingValidator.checkValid(EdgeNodingValidator.java:94)
    at com.vividsolutions.jts.geomgraph.EdgeNodingValidator.checkValid(EdgeNodingValidator.java:59)
    at com.vividsolutions.jts.operation.overlay.OverlayOp.computeOverlay(OverlayOp.java:170)
    at com.vividsolutions.jts.operation.overlay.OverlayOp.getResultGeometry(OverlayOp.java:127)
    at com.vividsolutions.jts.operation.overlay.OverlayOp.overlayOp(OverlayOp.java:66)
    at com.vividsolutions.jts.operation.overlay.snap.SnapIfNeededOverlayOp.getResultGeometry(SnapIfNeededOverlayOp.java:96)
    at com.vividsolutions.jts.operation.overlay.snap.SnapIfNeededOverlayOp.overlayOp(SnapIfNeededOverlayOp.java:58)
    at com.vividsolutions.jts.geom.Geometry.difference(Geometry.java:1423)
    at org.geotools.filter.function.StaticGeometry.difference(StaticGeometry.java:313)
    at org.geotools.filter.function.FilterFunction_difference.evaluate(FilterFunction_difference.java:66)
    at org.geotools.filter.expression.ExpressionAbstract.evaluate(ExpressionAbstract.java:65)
    at org.geotools.renderer.lite.StreamingRenderer.findGeometry(StreamingRenderer.java:2797)
    at org.geotools.renderer.lite.StreamingRenderer.access$100(StreamingRenderer.java:178)
    at org.geotools.renderer.lite.StreamingRenderer$RenderableFeature.getShape(StreamingRenderer.java:3100)
    at org.geotools.renderer.lite.StreamingRenderer.processSymbolizers(StreamingRenderer.java:2679)
    at org.geotools.renderer.lite.StreamingRenderer.process(StreamingRenderer.java:2585)
    at org.geotools.renderer.lite.StreamingRenderer.drawPlain(StreamingRenderer.java:2409)
    at org.geotools.renderer.lite.StreamingRenderer.processStylers(StreamingRenderer.java:2113)
    at org.geotools.renderer.lite.StreamingRenderer.paint(StreamingRenderer.java:832)
    at org.geoserver.wms.map.RenderedImageMapOutputFormat.produceMap(RenderedImageMapOutputFormat.java:539)

However, when I investigate my data in PostGIS, ST_isValid and ST_IsValidReason, return no errors on the entire database.  So, as far as PostGIS is concerned, all my data is valid.  Furthermore, the non-noded intersection always seems to be on the same line, suggesting a self-intersection or self touching.  When I identify the individual line using detective work from the coordinates (I am using a layer-group and sadly the logs don't tell me which dataset or give an id of which feature GWC thinks has the error).  I re-check the specific feature in PostGIS and again, no error.
Can anybody suggest why GWC is upset if PostGIS can't see the error.  Is this a known bug or something else?  Suggestions of solutions to fix it would be welcome as ST_MakeValid is pointless if PosGIS thinks all the data are already valid.

A: The reason that I could not find any errors in the data in PostGIS appears to be because there are none.  So why did GWC fail to seed the cache and report a topology error?  The answer is because I was using a style which involved an internal buffer of some polygons to get a graduated 'fade in' effect with a colour transition on the stroke.  Since you can't currently offset the stroke from the line, you must use ECQL filters on the geometry.  This works very well and produces a great style when zoomed in, but when zoomed out it can result in polygons that self-intersect.  These buffer-polygons only exist as far as the renderer is concerned so, of course, you won't find them in your original data and can't find any error.  It's fairly obvious, now I've discovered it, that this would be the reason.  but it's maybe worth posting this answer in case anybody else has a similar 'baffling' situation.
The ultimate solution was (sadly) to scrap my pretty style and go with something much less attractive.  I semi-faked the effect by creating a 1-pixel-wide png symbol, where the top half of the image was transparent (so that the fade-in effect starts on the line).  This also works, but is not as good.


text:
Q: react-query customHook refetchOnWindowFocus I am creating individual hooks using react-query. Where would I add in refetchOnWindowFocus: false ? as it is not currently being read and the data is being re-fetched when returning to the window.
    const useFetchOverview = () => {
        return useQuery(["userData", { refetchOnWindowFocus: false }],
            async () => {
                const { data } = await axios({
                    url: useFetchOverviewUrl,
                    headers: { ...getHeaders(reduxState) },
                    method: "get"
                });
                return data;
            });
    };

    const { isLoading, data: userOverviewData } = useFetchOverview();

A: this should be third parameter after fuinction:
return useQuery(["userData"],
            async () => {
                const { data } = await axios({
                    url: useFetchOverviewUrl,
                    headers: { ...getHeaders(reduxState) },
                    method: "get"
                });
                return data;
            }, { refetchOnWindowFocus: false });

ex: useQuery(queryKey, queryFn?, options)
check this for your reference: https://tanstack.com/query/v4/docs/reference/useQuery?from=reactQueryV3&original=https://react-query-v3.tanstack.com/reference/useQuery
OR you can write it for global:
const queryClient = new QueryClient({
   defaultOptions: {
     queries: {
       refetchOnWindowFocus: false,
     },
   },
 })


text:
Q: It does not detect cordova but it is installed and other projects work correctly I do not understand what may be happening. I have other projects in IONIC working correctly, but for some reason when trying to generate the Android version of this I get this error. All the answers I find are for people who do not have Android Studio / Gradle installed, but this is not the case
JAVA_HOME=C:\Program Files\Java\jdk1.8.0_121
studio
(node:9388) UnhandledPromiseRejectionWarning: CordovaError: Could not find an installed version of Gradle either in Android Studio,
or on your system to install the gradle wrapper. Please include gradle
in your path, or install Android Studio
    at Object.module.exports.check_gradle (D:\Clientes\proj\eComerce Ropa\app\platforms\android\cordova\lib\check_reqs.js:150:18)
    at StudioBuilder.prepEnv (D:\Clientes\proj\eComerce Ropa\app\platforms\android\cordova\lib\builders\StudioBuilder.js:216:23)
    at Api.module.exports.run (D:\Clientes\proj\eComerce Ropa\app\platforms\android\cordova\lib\build.js:154:20)
    at D:\Clientes\proj\eComerce Ropa\app\platforms\android\cordova\Api.js:342:43
    at _fulfilled (D:\Clientes\proj\eComerce Ropa\app\platforms\android\cordova\node_modules\q\q.js:854:54)
    at D:\Clientes\proj\eComerce Ropa\app\platforms\android\cordova\node_modules\q\q.js:883:30
    at Promise.promise.promiseDispatch (D:\Clientes\proj\eComerce Ropa\app\platforms\android\cordova\node_modules\q\q.js:816:13)
    at D:\Clientes\proj\eComerce Ropa\app\platforms\android\cordova\node_modules\q\q.js:624:44
    at runSingle (D:\Clientes\proj\eComerce Ropa\app\platforms\android\cordova\node_modules\q\q.js:137:13)
    at flush (D:\Clientes\proj\eComerce Ropa\app\platforms\android\cordova\node_modules\q\q.js:125:13)
(node:9388) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting
a promise which was not handled with .catch(). (rejection id: 1)
(node:9388) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.

Thanks in advance
EDIT:
gradle -v

------------------------------------------------------------
Gradle 5.0
------------------------------------------------------------

Build time:   2018-11-26 11:48:43 UTC
Revision:     7fc6e5abf2fc5fe0824aec8a0f5462664dbcd987

Kotlin DSL:   1.0.4
Kotlin:       1.3.10
Groovy:       2.5.4
Ant:          Apache Ant(TM) version 1.9.13 compiled on July 10 2018
JVM:          1.8.0_121 (Oracle Corporation 25.121-b13)
OS:           Windows 10 10.0 amd64


text:
Q: Integration testing with Quarkus and Redis how do I set a state with the redis? Hi I have my test class annotated with the
@QuarkusIntegrationTest

I wanna run the following test

        given()
                .contentType(MediaType.APPLICATION_JSON)
                .pathParam("id", id)
                .when()
                .get("/user/presence/{id}")
                .then()
                .statusCode(Response.Status.OK.getStatusCode())
    }

This gets the user presence and the presence is stored inside a redis cache.
I wanna do a setup step that puts the presence into my redis cache before the test begins. However, my redis cache is not exposed on any endpoint so i'm not able to set it via HTTP calls.
The redis class i want to test is
@ApplicationScoped

This seems to be needed since the constructor sets a RedisDataSoruce
    public MyRedisCache(RedisDataSource ds) {
        this.commands = ds.string(MyClass.class);
    }

But this makes me unable to use this perticular class instance inside my integration tests. So how can I put values into this redis before my test begins

A: Indeed, in @QuarkusIntegrationTest it's not possible to inject any bean to help.
I'd recommend using a library to connect to Redis and put a value into the cache directly.
You can use for example Redisson or Jedis, and add it to your project with test dependency scope. (You could also check for and use the underlying Redis client already included via the Quarkus plugin you use for Redis)
Then, you could add code to the test class in a @BeforeAll method to call the library and add data directly to Redis programmatically.


text:
Q: Clear GrantSendOnBehalfTo on a mailbox exchange - from remote powershell script To revoke permissions for GrantSendOnBehalfTo  from a mailbox, it is pretty well documented, that you would do this:
Set-Mailbox -Identity MyMailbox -GrantSendOnBehalfTo $null

That works when run from powershell and in a local script.
However, if I include it in a script, that runs remote powershell (using New-PSSession etc), it fails with this error:

Couldn't find object "[Microsoft.Exchange.Configuration.Tasks.RecipientIdParameter]". Please make sure that it was
  spelled correctly or specify a different object.
      + CategoryInfo          : NotSpecified: (:) [], ManagementObjectNotFoundException
      + FullyQualifiedErrorId : A32A9BAB

So it will not accept $null as a parameter.
How can I get around that?

A: Realistically, especially if this was Office 365 with DirSync, the easiest way would be to leave the publicDelegates attribute empty in the AD.
Make sure to use the UPN for the identity (which isn't required if working with a single mailbox):
Set-Mailbox -identity xxx@something.com -grantSendOnBehalfTo $null

or
Set-Mailbox xxx@something.com -grantSendOnBehalfTo $null


text:
Q: Problemas con servlet Estoy intentando hacer unos servicios web para una app en Netbeans java y me lanza este error:

GlassFish Server, deploy, Connection refused: connect, false
  C:\Users\Win10\Documents\NetBeansProjects\WebApplication2\nbproject\build-impl.xml:1037:
  The module has not been deployed. See the server log for details.
  BUILD FAILED (total time: 14 seconds)

Estoy usando Netbeans 11 y con el jee 8, lo he intentado con el jee 7 ya que me han dicho que puede ser ese el problema y nada..

A: Edit---
Al ser con Glassfish puedes antes que nada probar con estos pasos.
Inicia NetBeans
Antes de hacer el despliegue mira que la ruta de tu Glassfish sea asi.
C:\Users\myusername\GlassFish_Server\glassfish\bin
Inicia asadmin.bat
Una vez se habra la consola: Inicia el dominio y vuelve a NetBeans, refresca hasta que veas es estado de running y ve al localhost a confirmarlo.
Para pararlo usa stop-domain.

En principio creo que el error es porque no especificas el servlet al proyecto y NetBeans falla al crear el fichero context.xml.
Si tu proyecto contiene la carpeta Web Pages, crea una carpeta META-INF.
Hazlo haciendo click en Web pages, y selecciona New->Other->Other->File Folder.
Llama al fichero META-INF.
Dentro crea un context.xml haciendo el mismo proceso de New->Other->XML->XML Document.
Llamalo context (NetBeans añade el .xml).
Edita el documento y añade:
<?xml version="1.0" encoding="UTF-8"?>
<Context antiJARLocking="true" path="/app-name"/>

Sustituye app-name por el nombre de tu aplicación/proyecto.
En teoria deberia funcionar, asegurate de que el fichero se pueda leer para todos.
context.xml es especifico para Tomcat si necesitas mas informacion miralo en tomcat.apache.org.
En caso de no funcionar puedes probar haciendo un pequeño reinicio de NetBeans.
Ve a 'Task Manager'
Elije el tab de 'Procesos'
Click en 'Java(TM) Platform SE Binary'
Click en 'Terminar proceso'
Ve a tu proyecto de Netbeans
Haz un Clean & Build al proyecto
En otros casos prueba a ejecutarlo como administrador.
Ojala te sirva de ayuda.


text:
Q: Why have I not received the archaeologist badge? According to this Data Stack Exchange query I have performed more than the 100 edits necessary to receive the archaeologist badge on Stack Overflow. My guess is that the logic for awarding the badge is different than what the query is representing. That being said, since I have edited 107 posts which seem to match the six month criteria why have I not been awarded the badge?

A: I think this badge needs a lot more clarification from the devs. The description from the list of all badges simply says:

Archaeologist

*

*silver; awarded once; same family as Excavator (bronze)

*Edited 100 posts that were inactive for at least 6 months

*Edits to your own posts do not count

*Source: Should I have earned an "Excavator" badge for this?

That is probably as undescriptive as you can possibly get. The only thing it even outlines is that edits to your own posts do not count. But that leaves a user asking:

*

*What does "inactive" mean?
This question asks a key question, and got two answers that somewhat outline what inactive means, but doesn't really clarify anything at all, nor is any of it verified by devs. Does the inactivity always apply to the parent question? Does it mean that the entire question has to be inactive for 6 months and any edit to the question itself or its answers will then qualify for the badge and reset the last activity date (again for the entire question and all answers under it)?
This turned out to be fairly straight-forward. The entire question doesn't matter, and the system only looks at the revision history for the particular post you edited. So an an example, you could edit an old answer, then edit a second old answer to the same question, and then edit the question and all of that activity would count three times assuming that all three posts hadn't been created or edited within the past 180 days. The "last activity" date on the question is not ever looked at and is irrelevant.
Bottom line: as long as the specific post you are editing was not created or edited within the past 180 days, editing it will increase your progress.

*Do tag-only edits count?
This question was answered, and the answer was "no." However, there's no verification from any devs. Can we get that verification please?
No, the system does not look at tag edits when calculating progress - only edits to the title and body will count.

*Do edits to the same post count multiple times?
I haven't found this question yet on Meta. If we're going off the rules of other editing badges, the answer is probably no. Other editing badges only count the first edit to a post towards the badge.
No, you can only edit a single post once for the badge.

The specific query mentioned in the question here is inaccurate in a few ways.

*

*Most importantly, it doesn't have any exclusion for if you own the post that was edited, so if you've ever edited your own inactive post, that query will count it. Only edits to other users' posts count.

*It could also decrease your count inappropriately in a lot of cases, because it looks for your edit to be 180 days after all other post history, but post history also includes close and reopen, tag edits, etc which don't actually affect the badge.

*It doesn't lookup the post itself to make sure it is a question or answer. Edits to old tag wikis and excerpts do not count.


text:
Q: Is there a way in C++ to check if a line of an opened fstream file contains multiple integers? I have myfile.in opened with the following text:
1
4 5
3

Going for every number while (myfile >> var) cout << var << endl; will output each integer one by one:
1
4
5
3

Is there any way I can check all the lines of myfile.in and output the lines with more than 1 integer? For the example above:
4 5

or
4
5

A: You can use a combination of std::getline and std::istringstream as shown below. The explanation is given in the comments.
#include <iostream>
#include<fstream>
#include<string>
#include <sstream>

int main()
{
    std::ifstream inputFile("input.txt");
    std::string line;
    int num = 0; //for storing the current number
    int count = 0;//for checking if the current line contains more than 1 integer
    if(inputFile)
    {
        //go line by line
        while(std::getline(inputFile, line))
        {
            std::istringstream ss(line);
            //go int by int
            while(ss >> num)
            {
                ++count;
                //check if count is greater than 1 meaning we are checking if line contains more than 1 integers and if yes then print out the line and break
                if (count > 1)
                {
                    std::cout<<line <<std::endl;
                    break;
                }

            }
            //reset count and num for next line
            count = 0;
            num = 0;

        }

    }
    else
    {
        std::cout<<"input file cannot be opened"<<std::endl;
    }
    return 0;
}

Demo.


text:
Q: View all queries I got a MVC3 application using Entity Framework 4 and SQL Server.
How can I view all queries that has been invoked (and the amount of time that they took)?

A: Use the sql profiler, it will give you all this information and more. Won't require any code changes either.
Heres a link to a free one if you don't have the full toolset.
http://sites.google.com/site/sqlprofiler

A: You cannot without additional tools. Simply EF doesn't have such feature. The referenced article describes some tools (SQL profiler, DotTrace, EF Provider Wrappers, EFProf, Huagati profiler) but there are also:

*

*MVC mini profiler

*ORM profiler
Not every tool is free but those which are not have a trial version.


text:
Q: UNC path to a folder on my local computer What's the UNC path to a folder on my local computer, and how can I access it?
I have tried:

*

*Security for the folder – set to Everyone Full Control (for now!)

*Sharing permissions – set to Everyone Full Control (for now!)

I can see the folder in \\<computername>, but can't go in (<foldername> is not accessible.)
Error message:

You might not have permission to use this network resource.  Contact the administrator of this server to find out if you have access permissions. The network location cannot be reached. For information about network troubleshooting, see Windows Help.

My computer is not connected to a network.

A: If you're going to access your local computer (or any computer) using UNC, you'll need to setup a share.  If you haven't already setup a share, you could use the default administrative shares.  Example:
\\localhost\c$\my_dir
... accesses a folder called "my_dir" via UNC on your C: drive.  By default all the hard drives on your machine are shared with hidden shares like c$, d$, etc.

A: On Windows, you can also use the Win32 File Namespace prefixed with \\?\ to refer to your local directories:
\\?\C:\my_dir

See this answer for description.

A: I had to:

*

*Create a local administrator

*Add a Microsoft Loopback adapter

*Reference the location as \\127.0.0.1\SSRSFileShare


text:
Q: Ponteiro para funções em C não está chamando Estou tendo um problema em relação a ponteiros para funções. Declarei os ponteiros e armazenei em um vetor, porém na hora de chamar as funções através dos ponteiros o compilador apresenta um erro que ainda não consegui identificar.
Estou utilizando a IDE Code::Blocks 17.12 no Windows 7.
Segue o código:
#include <stdio.h>
#include <stdlib.h>
#include <math.h>

#define PI 3.14

void circunferenciaCirculo(double raio);
void areaCirculo(double raio);
void volumeEsfera(double raio);

int main()
{
system("color 3");
void (*calculo[3])(double raio) =
                  {circunferenciaCirculo,areaCirculo,volumeEsfera};
int sentinela = 0;
double raio = 0.0;

while(sentinela != 4){

    system("cls");
    printf("Opcoes de calculo\n\n1-Circunferencia de circulo\n2-Area de
    circulo\n3-Volume de esfera\n4-Sair\n\nOpcao:");
    scanf("%d",&sentinela);

    switch(sentinela){

    case 1:
       system("cls");
       printf("Digite o raio:");
       scanf("%lf",&raio);
       calculo[0];
       break;

    case 2:
        system("cls");
        printf("Digite o raio:");
        scanf("%lf",&raio);
        calculo[1];
        break;

    case 3:
        system("cls");
        printf("Digite o raio:");
        scanf("%lf",&raio);
        calculo[2];
        break;

    default:
        printf("Opcao invalida!\n");
        system("PAUSE");
        break;

    }

}

return 0;
}

Obs: postei apenas o código do main(), se precisar colocar a declaração das funções eu edito depois.
Além desse problema que eu estou tendo, também tenho outra dúvidas sobre ponteiro para funções.
1)  Existe alguma diferença de desempenho entre chamar a função normalmente e chamar através de ponteiros?
2) Em que situações ponteiros para funções são utilizados?

A: O maior problema é que você não está chamando função alguma, a chamada sempre ocorre com os parênteses, igual a uma função normal, neste caso o nome da variável é igual ao que seria o nome da função. Mas tem varias outras coisas que podem ser melhoradas no seu código, inclusive eliminar o switch, assim faz um pouco mais de sentido em usar esta forma. O que eu não usaria em condições normais, não há necessidade neste caso, um switch com as chamadas diretas seriam mais eficiente, legível sem comprometer funcionalidade, embora seja interessante como um exercício. Só espero que não torne um vício.
#include <stdio.h>
#include <math.h>

#define PI 3.14

void circunferenciaCirculo(double raio);
void areaCirculo(double raio);
void volumeEsfera(double raio);

int main() {
    system("color 3");
    void (*calculo[3])(double raio) = {circunferenciaCirculo, areaCirculo, volumeEsfera};
    int sentinela = 0;
    while (sentinela != 4) {
        system("cls");
        printf("Opcoes de calculo\n\n1-Circunferencia de circulo\n2-Area de circulo\n3-Volume de esfera\n4-Sair\n\nOpcao:");
        scanf("%d", &sentinela);
        if (sentinela < 1 || sentinela > 4) {
            printf("Opcao invalida!\n");
            system("PAUSE");
            continue;
        }
        if (sentinela == 4) break;
        system("cls");
        printf("Digite o raio:");
        double raio = 0.0;
        scanf("%lf", &raio);
        calculo[sentinela - 1](raio);
    }
}

Veja funcionando no ideone. E no repl.it. Também coloquei no GitHub para referência futura.
Dá para melhorar mais.

*

*Existe alguma diferença de desempenho entre chamar a função
normalmente e chamar através de ponteiros?

Sim, há um indireção extra do ponteiro. Embora possa ser trivial em certas situações, pode custar bastante em outras, especialmente na primeira chamada ou em chamadas subsequentes depois de muito tempo, onde a carga do endereço onde está a função está na memória e não mais em cache, o que é uma operação bastante lenta. Otimização hoje em dia na maioria dos problemas que resolvemos é mais economizar acesso à memória do que economizar ciclos de processamento, e tende a piorar com memórias não voláteis que podem ter a RAM um pouco mais lenta em benefícios de ter persistência automática e muito rápida.
A chamada à função já é uma indireção, quase obrigatória.

*Em que situações ponteiros para funções são utilizados?

Sempre que você precisar determinar mais tarde qual é a função exata que deve executar.
Costumo dizer que só existem dois motivos para deixar uma execução dinâmica, ou seja que só seja resolvida em tempo de execução:

*

*falta uma informação em tempo de compilação.
Ela só estará disponível quando o código estiver executando, seja por digitação do usuário, vindo de fontes externas como arquivos, bancos de dados, redes ou outras formas de entrada de dados, incluindo, é claro, dispositivos que convertem sinal analógicos para digital como câmeras, microfones e outros sensores.
Em alguns casos a informação pode estar disponível antes da execução mas depois da compilação normal. É possível fazer otimizações, mas geralmente não compensa. Em outros pode ser que sim. Há casos que usa-se profile guided optimization para mudar o código, isto pode ser aproveitado para otimizar outras coisas.
Há casos que é possível resolver antes, mas é preferível deixar para resolver depois para dar flexibilidade ao sistema, isto não é obrigatório resolver em tempo de execução, mas costuma ser uma solução adotada, pra mim de forma abusiva em muitos casos, mas tem alguma justificativa.

*Muitas variações de execução que para resolver em tempo de compilação geraria muitos caminhos de execução que poderia até economizar ciclos de execução por eliminar algumas decisões e buscas por dados em tempo de execução, porém com muito mais código diferente para executar suja-se muito o chance fazendo que pequenas mudanças de contexto obrigue acesso à RAM quando a memória do processador que é muito mais rápida poderia ter o que precisa executar. Isso vale para repetições de laços, especializações de objetos e funções.
Se você sabe que terão poucas repetições de um corpo pequeno pode ser interessante desenrolar a repetição, e bons compiladores fazem isto para você, mas não compensa para muitos. O mesmo vale para trabalhar com diversos objetos com estruturas semelhantes mas não idênticas (herança). Pode ser mais rápido se tiver instâncias diferentes para cada tipo mas só se for certamente 1, 2, 3 ou 4, muito quem sabe 5. Se tiver muitos é melhor usar uma indireção. O mesmo vale para funções.
Se você sabe que função quer chamar não tem que pensar em ponteiro para função. Se criar algo genérico que pode ter N funções diferentes sendo chamadas em determinado momento pode ser melhor usar o ponteiro, assim existirá um só código que pega qual função deve executar naquele momento de acordo com o ponteiro e faz a chamada. Se você tiver só 4 possibilidades pode ser mais interessante criar 4 algoritmos distintos que fazem a mesma coisa mas na hora de chamar a função que deseja chame uma diferente em cada uma dessas instâncias de código. Tem linguagem que facilita muito isso, como C++. Outras tem que fazer na mão e gera repetição, em alguns casos até viola o DRY.
Essa decisão sempre é uma comodidade e/ou otimização e não uma necessidade absoluta como é o motivo anterior.
A chamada da função normal pode ser "otimizada" e eliminar todas indireções, porém teria que copiar o código da função em cada local onde ela seria chamada. Em alguns casos pode compensar por isso alguns compiladores fazem inline quando compensa, ou podem ser forçados fazer, mas se fizer em exagero o tiro pode sair pela culatra.
Então é uma forma de parametrizar o conteúdo, ou seja, você torna uma função que tem um endereço constante em endereço variável, como fez no seu código, ainda que sem ganho real, no meu ainda teve o ganho de algumas linhas à custa de menos legibilidade e performance, ainda que desprezível para esse tipo de código.
Este mecanismo é muito semelhante ao que se usa em orientação a objeto. No fundo o polimorfismo é assim por baixo dos panos.

A: Suas declarações e definições estão corretas. O problema está na hora de fazer a chamada das funções por meio do ponteiro.
As seguintes linhas não estão surtindo efeito nenhum no seu codigo, veja:
calculo[0];
...
calculo[1];
...
calculo[2];

Deveriam ser, respectivamente, alteradas para:
calculo[0]( raio );
...
calculo[1]( raio );
...
calculo[2]( raio );


text:
Q: Is it possible to pass variable from steps to script in jenkinsfile I have one pipeline and I want to pass one Arraylist that I get from a groovy method into the script that is running in Master Jenkins.
stages {
        stage('Get Tests Parameter') {
            steps {
                code = returnList()
                script {
                    properties([
                            parameters([
                                    [$class              : 'CascadeChoiceParameter',
                                     choiceType          : 'PT_CHECKBOX',
                                     description         : 'Select a choice',
                                     defaultValue        : '',
                                     filterLength        : 1,
                                     filterable          : false,
                                     name                : 'Tests',
                                     referencedParameters: 'role',
                                     script              : [$class        : 'GroovyScript',
                                                            fallbackScript: [
                                                                    classpath: [],
                                                                    sandbox  : true,
                                                                    script   : 'return ["ERROR"]'
                                                            ],
                                                            script        : [
                                                                    classpath: [],
                                                                    sandbox  : false,
                                                                    script   : code
                                                            ]
                                     ]
                                    ]
                            ])
                    ])
                }
            }
        }
}
...

def returnList() {
    def stringList = []
    def fileContent = readFile "/var/jenkins_home/example.txt"
    for (line in fileContent.readLines()) {
        stringList.add(line.split(",")[0] + ":selected");
    }
    return stringList
}

That stages are running in a slave, so I couldn't execute that method returnList() inside the script because the script is running in Master. So I'm trying to get returnList ArrayList to a variable and use that variable in the script part.
Is that possible?

A: If you want to execute a specific step in a specific node then you can specify the agent within the stage block. So what you can do is execute the file reading logic on the master in the initial stage and then use it in consecutive stages. Check the example below.
def code

pipeline {
    agent none
    stages {
        stage('LoadParameters') {
            agent { label 'master' }
            steps {
                 scipt {
                    code = returnList()
                  }
            }
        }
        stage('Get Tests Parameter') {
            steps {
                script {
                    properties([
                            parameters([
                                    [$class              : 'CascadeChoiceParameter',
                                     choiceType          : 'PT_CHECKBOX',
                                     description         : 'Select a choice',
                                     defaultValue        : '',
                                     filterLength        : 1,
                                     filterable          : false,
                                     name                : 'Tests',
                                     referencedParameters: 'role',
                                     script              : [$class        : 'GroovyScript',
                                                            fallbackScript: [
                                                                    classpath: [],
                                                                    sandbox  : true,
                                                                    script   : 'return ["ERROR"]'
                                                            ],
                                                            script        : [
                                                                    classpath: [],
                                                                    sandbox  : false,
                                                                    script   : code
                                                            ]
                                     ]
                                    ]
                            ])
                    ])
                }
            }
        }
    }
}

def returnList() {
    def stringList = []
    def fileContent = readFile "/var/jenkins_home/example.txt"
    for (line in fileContent.readLines()) {
        stringList.add(line.split(",")[0] + ":selected");
    }
    return stringList
}


text:
Q: How to use ip camera working through activex I have an IP camera, which works through ActiveX (I ought to use IE now to deal with it now).
The IP camera sends data by using rtsp as follow:
rtsp://192.168.0.100:554/user=admin&password=&channel=1&stream=0?.sdp
How can I connect to camera using Java?
Can anyone give me example of code dealing rtsp and java?

A: If someone will have the same problem - JMF is too old. I find the easiest way to deal with RTSP - use vlcj.
For me, the most code free example looks like:
public static void main(String[] args) {
        new NativeDiscovery().discover();
        SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
                new RTSPPlayer();
            }
        });
    }

    public RTSPPlayer() {
        frame = new JFrame("Media Player");
        frame.setBounds(100, 100, 600, 400);
        frame.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
        frame.addWindowListener(new WindowAdapter() {
            @Override
            public void windowClosing(WindowEvent e) {
                mediaPlayerComponent.release();
                System.exit(0);
            }
        });
        frame.setVisible(true);
        mediaPlayerComponent = new EmbeddedMediaPlayerComponent();
        frame.setContentPane(mediaPlayerComponent);
        mediaPlayerComponent.getMediaPlayer().playMedia("rtsp://192.168.0.100:554/user=admin&password=&channel=1&stream=0?.sdp");
    }


text:
Q: Django User-Login and authentication is not working I am creating a simple user-login page using Django and after get login redirecting to home page.But its always redirecting to unauthorized option given in app's views.py (i.e Invalid Details). Please check and help me.
Project name:login and App name: index
views.py

from django.shortcuts import render_to_response
from django.contrib import auth
from django.http import HttpResponseRedirect, HttpResponse
from django.contrib.auth.decorators import login_required
from django.contrib.auth import authenticate, login, logout
from django.core.context_processors import csrf

# Create your views here.

def login(request):
    c = {}
    c.update(csrf(request))
    return render_to_response('login.html', c)

def auth(request):
    username = request.GET.get('username', '')
    password = request.GET.get('password', '')
    user = authenticate(username=username, password=password)

    if user is not None:
            if user.is_active:
                    login(request, user)
                    return HttpResponseRedirect("/home/")
            else:
                    return HttpResponse("Bad request")
    else:
            return HttpResponse("Invalid details")

  @login_required
  def home(request):
       return render_to_response('home.html')

 App urls.py

from django.conf.urls import url
from django.contrib import admin
from django.contrib.auth.views import login, logout
from . import views

urlpatterns = [
   url(r'^admin/', admin.site.urls),
   url(r'^$', views.login, name='login'),
   url(r'^auth/$', views.auth, name='auth'),
  url(r'^home/$', views.home, name='home'),
]

Project's: urls.py:

from django.conf.urls import url, include
from django.contrib import admin

urlpatterns = [
     url(r'^admin/', admin.site.urls),
     url(r'^', include('index.urls')),
  ]

Templates:
 login.html

 {% block content %}

 {% if form.errors %}

Sorry, that's not a valid username or password

{% endif %}

 <form action="/auth/" method="post">{% csrf_token %}
  User name:
 <input type="text" name="username" value="" id="username">
 Password:
 <input type="password" name="password" value="" id="password">

 <input type="submit" value="login" />
 <input type="hidden" name="next" value="{{ next|escape }}" />
 </form>

{% endblock %}

home.html

{% block content %}

Hello Vivek

{% endblock %}

A: Im going to share another approach to manage authentication in django assuming you already have a login html template (with username and password inputs inside a form with post action) , a user form and a home template , this would be the authentication views .py :
from django.shortcuts import render, get_object_or_404
from django.http import HttpResponseRedirect
from django.views.generic import View
from django.core.urlresolvers import reverse
from django.contrib import messages
from django.contrib.auth import login, authenticate, logout
from ..form import UsersForm

class LoginView(View):

    template_name = ['yourtemplatedirectory/login.html', 'yourtemplatedirectory/home.html']

    def get(self, request, *args, **kwargs):
        form = UsersForm()
        if request.user.is_authenticated():
            return render(request, self.template_name[1])
        return render(request, self.template_name[0])

    def post(self, request, *args, **kwargs):
        username = request.POST['username']
        password = request.POST['password']
        user = authenticate(username = username, password = password)
        if user is not None:
            login(request, user)
            if user.is_active:
                return render(request, self.template_name[ 1 ])
        else:
            messages.add_message(
                request, messages.ERROR, "Invalid username or password"
                )
            return HttpResponseRedirect(reverse( 'yourapp:login' ))

def LogoutView(request):
    logout(request)
    return HttpResponseRedirect(reverse( 'yourapp:home' ))

Just call the respective url from login and logout buttons and that's it. Hope it helps !!

A: Change from
username = request.GET.get('username', '')
password = request.GET.get('password', '')

to
username = request.POST.get('username', '')
password = request.POST.get('password', '')


text:
Q: why don't match the method signature for SpreadsheetApp.Sheet.getRange I want to copy the cell values from b1 to b2 but I'm getting error please help how to fix this
   function recordHistory() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var inputSheet = ss.getSheetByName("b1");

var source = inputSheet.getRange('B3','D3','F3','H3','J3','L3','N3','P3','R3','T3','V3');
var values =

 source.getValues();

var outputSheet = ss.getSheetByName("b2");
outputSheet.getRange(outputSheet.getLastRow()+1,1,values.length,values[0].length).setValues(values);
};

Exception: The parameters (String,String,String,String,String,String,String,String,String,String,String) don't match the method signature for SpreadsheetApp.Sheet.getRange.
recordHistory   @ RecordPercent.gs:6

A: You should consider using Sheet.getRangeList()
Sheet.getRange() method has four methods which accept upto four parameters and they are all explained on this page
function getAndSetValueWithRangeList() {
  const ss = SpreadsheetApp.getActive();
  const sh = ss.getSheetByName('b1');
  const osh = ss.getSheetByName('b2');
  let rlA = sh.getRangeList(['B3', 'D3', 'F3', 'H3', 'J3', 'L3', 'N3', 'P3', 'R3', 'T3', 'V3']);
  rlA.getRanges().forEach((r,i)=>{osh.getRange(r.getA1Notation()).setValue(r.getValue());});
}


text:
Q: Calculating Checkboxes in JavaScript i was wondering if yous could help me with this. I am quite new to JavaScript but This has been getting to me for quite a while now and I have ran out of ideas on how to fix this. Basically If a user clicks on one of those checkboxes below, then the Data-price attribute of the checkboxes should show in the total box and so fourth. e.g user clicks the checkbox with the value of 14, then the price £13 will show up in the total box, if the user clicks on another checkbox, say the last checkbox with the value of 9, then it will calculate the two checkboxes 16 + 13 and will then show up the new figure in the total box
I have tried my code countless of times and it will not display anything in the total box. I really hope i have made myself clear with this and i'd be grateful if yous can help me out
HTML
<form id=BookingForm method="get"
    <section id="bookEvents"

            <input type='checkbox' name='event[]' value='6' data-price='18.50'>
            <input type='checkbox' name='event[]' value='14' data-price='13.00'>
           <input type='checkbox' name='event[]' value='11' data-price='35.00'>
           <input type='checkbox' name='event[]' value='9' data-price='16.00'>

        Total <input type="text" name="total" size="10" readonly>

JavaScript
window.addEventListener('load', function () {
    "use strict";

    const l_form = document.getElementById('bookingForm');
    l_form.CheckValue.onclick = calculateTotal;

    function calculateTotal() {
        let l_total = 0;

        const l_item = l_form.querySelectorAll('div.item');
        const l_checkboxesCount = l_checkboxes.length;

        for (let t_i = 0; t_i < l_checkboxesCount; t_i++) {
            const t_item = l_item[t_i];
            const t_checkbox = t_ckbox.querySelector('input[data-value][type=checkbox]');

            if (t_checkbox.checked) {
                l_total += t_checkbox.dataset.price;
            }
            l_form.submit.value = l_total;
        }
    }
});

A: There are multiple issues with the code that you've provided... I'll list as many as I can...

*

*The following do not have closing > symbols...
<form id=BookingForm method="get"
<section id="bookEvents"

*You're not closing the <form> element with a </form>

*You're looking for document.getElementById('bookingForm');, but the ID of the form is BookingForm... javascript is case-sensitive, so it won't match. Instead you should change either the id in the element, or the name of the element in the function call.

*You're using l_form.CheckValue but there is nothing wit CheckValue as an ID in the code you've provided

*At the end of the code, you are not correctly closing the addEventListener function, which should have });

*As per the comment by @fcalderan in the following you are not adding numbers together... you are actually concatenating strings
Wrong: l_total += t_checkbox.dataset.price;
Fixed: l_total += parseFloat(t_checkbox.dataset.price);

A: You need to add form closing tag to enclose the controls in it.
<form id=BookingForm method="get">

             <input type='checkbox' onchange = "calculateTotal()" name='event[]' value='6' data-price='18.50'>
             <input type='checkbox' onchange = "calculateTotal()" name='event[]' value='14' data-price='13.00'>
             <input type='checkbox' onchange = "calculateTotal()" name='event[]' value='11' data-price='35.00'>
             <input type='checkbox' onchange = "calculateTotal()" name='event[]' value='9' data-price='16.00'>

         Total <input type="text" name="total" size="10" readonly>

</form>

Should be in this format.

A: Here is an implementation with vanilla JavaScript:

window.onload = () =>
  document.querySelectorAll(".input-x")
  .forEach(input=>input.addEventListener("change",calculatePrize));

function calculatePrize(){
  let sum = 0;
  document.querySelectorAll(".input-x")
  .forEach(input=>sum += (input.checked?
  Number.parseFloat(input.getAttribute("data-price")):0));
  document.getElementById("total").value = sum;
}
<form id="BookingForm" method="get">

           <input type='checkbox' class="input-x" name='event[]' value='6' data-price='18.50'>
           <input type='checkbox' class="input-x" name='event[]' value='14' data-price='13.00'>
           <input type='checkbox' class="input-x" name='event[]' value='11' data-price='35.00'>
           <input type='checkbox' class="input-x" name='event[]' value='9' data-price='16.00'>

        Total:
        <input id="total" type="text" name="total" size="10" readonly>

    </form>

A: Here is the demo example I had made for you.

var totalPrice = 0;
$("#totalPrice").html(0);
$('.checkboxClass').change(function () {
  if ($(this).is(":checked")) {
    totalPrice += parseFloat($(this).attr('data-price'));
    $("#totalPrice").html(totalPrice);
  } else {
    totalPrice -= parseFloat($(this).attr('data-price'));
    $("#totalPrice").html(totalPrice);
  }
});

<input type="checkbox" class="checkboxClass" name="c1" value="4" data-price="18.50" />18.50

<input type="checkbox" class="checkboxClass" name="c2" value="8" data-price="14.50" />14.50

<input type="checkbox" class="checkboxClass" name="c3" value="5" data-price="12.50" />12.50

Total Price:


text:
Q: Installing and working with FLTK on Visual Studio 2012 My machine in Windows 7 32-bit and my compiler for C++ is Visual Studio 2012 so first I downloaded FLTK from here (http://www.stroustrup.com/Programming/FLTK/) and then I did the works as follows has wanted me:
I. Unzip the downloaded file and open the main folder, fltk-l.l.? In a
Visual C++ folder (e.g., vc2005 or vcnet), open fltk.dsw. If asked about
updating old project files, choose Yes to All.
PS: My compiler is vc2012 instead of vc2005 and there wasn't any file named fltk.dsw in vc2005 or vcnet folders, so I chose the fltk.sln from vcnet and installed it. There were some failing when installing but it finished finally!

*

*From the Build menu, choose Build Solution. This may take a few minutes.
The source code is being compiled into static link libraries so that
you do not have to recompile the FLTK source code any time you make
a new project. When the process has finished , close Visual Studio.

*From the main FLTK directory open the lib folder. Copy (not just
move/drag) all the .lib files except README.lib (there should be
scven) into C:\Prograrn Files\Microsoft Visual Studio\Vc\lib.

*Go back to the FLTK main directory and copy the FL folder into
C:\Program Files\Microsoft Visual Studio\Vc\include.

*Create a new project in Visual Studio with one change to the usual procedure:
create a "\Vin32 project" instead of a "console application" when
choosing your project type. Be sure to create an "empty project"; otherwise,
some "software wizard" will add a lot of stuff to your project that
you are unlikely to need or understand.

*In Visual Studio, choose Project from the main (top) menu, and from
the drop-down menu choose Properties.

*In the Properties dialog box, in the left menu, click the Linker folder.
This expands a sub-menu. In this sub-menu, click Input. In the Additional
Dependencies text field on the right, enter the following text:
fltkd.lib wsock32.lib comctl32.lib fltkjpegd.lib fltkimagesd.lib
[The following step may be lIImecessary because il is now the default.]
In the Ignore Specific Library text field, enter the following text:
libcd.lib

*[This step may be unnecessary because /MDd is now the default.] In the
left menu of the same Properties window, dick C/C++ to expand a different
sub-menu. Click the Code Generation sub-menu item. In the right
menu, change the Runtime Library drop-down to Multi-threaded
Debug DLL (/MDd). Click OK to close the Properties window.
I this step I added a new item to that newly created project (I named that project testv.cpp) and pasted this simple code for testing the FLTK:
#include <FL/Fl.h>
#include <FL/Fl_box.h>
#include <FL/Fl_Window.h>

//***************************

int main()
{
  FI_Window window(200, 200, "Window title");
  FL_Box box(O,O,200,200, "Hey, I mean, He llo, World! ");
  window.show();
  return Fl::run();
}

After running this project (pressing F5), 11 errors appeared! They are in bellow:

Error 1   error LNK2019: unresolved external symbol "public: static int
  __cdecl Fl::run(void)" (?run@Fl@@SAHXZ) referenced in function _main  C:\Users\CS\documents\visual studio 2012\Projects\testv\testv\testv.obj
Error 2   error LNK2019: unresolved external symbol "protected:
  __thiscall Fl_Widget::Fl_Widget(int,int,int,int,char const *)" (??0Fl_Widget@@IAE@HHHHPBD@Z) referenced in function "public:
  __thiscall Fl_Box::Fl_Box(int,int,int,int,char const *)" (??0Fl_Box@@QAE@HHHHPBD@Z)   C:\Users\CS\documents\visual studio
  2012\Projects\testv\testv\testv.obj
Error 3   error LNK2019: unresolved external symbol "public: virtual
  __thiscall Fl_Widget::~Fl_Widget(void)" (??1Fl_Widget@@UAE@XZ) referenced in function "public: virtual __thiscall
  Fl_Box::~Fl_Box(void)"
  (??1Fl_Box@@UAE@XZ)   C:\Users\CS\documents\visual studio
  2012\Projects\testv\testv\testv.obj
Error 4   error LNK2001: unresolved external symbol "public: virtual
  void __thiscall Fl_Widget::resize(int,int,int,int)"
  (?resize@Fl_Widget@@UAEXHHHH@Z)   C:\Users\CS\documents\visual studio
  2012\Projects\testv\testv\testv.obj
Error 5   error LNK2001: unresolved external symbol "protected: virtual
  void __thiscall Fl_Box::draw(void)"
  (?draw@Fl_Box@@MAEXXZ)    C:\Users\CS\documents\visual studio
  2012\Projects\testv\testv\testv.obj
Error 6   error LNK2001: unresolved external symbol "public: virtual int
  __thiscall Fl_Box::handle(int)" (?handle@Fl_Box@@UAEHH@Z) C:\Users\CS\documents\visual studio
  2012\Projects\testv\testv\testv.obj
Error 7   error LNK2019: unresolved external symbol "public: __thiscall
  Fl_Window::Fl_Window(int,int,char const *)"
  (??0Fl_Window@@QAE@HHPBD@Z) referenced in function
  _main C:\Users\CS\documents\visual studio 2012\Projects\testv\testv\testv.obj
Error 8   error LNK2019: unresolved external symbol "public: virtual
  __thiscall Fl_Window::~Fl_Window(void)" (??1Fl_Window@@UAE@XZ) referenced in function _main   C:\Users\CS\documents\visual studio
  2012\Projects\testv\testv\testv.obj
Error 9   error LNK2019: unresolved external symbol "public: virtual
  void __thiscall Fl_Window::show(void)" (?show@Fl_Window@@UAEXXZ)
  referenced in function _main  C:\Users\CS\documents\visual studio
  2012\Projects\testv\testv\testv.obj
Error 10  error LNK2019: unresolved external symbol WinMain@16
  referenced in function __tmainCRTStartup C:\Users\CS\documents\visual
  studio 2012\Projects\testv\testv\MSVCRTD.lib(crtexew.obj)
Error 11  error LNK1120: 10 unresolved
  externals C:\Users\CS\documents\visual studio
  2012\Projects\testv\Debug\testv.exe

I think the problem is to do with the creating the project. After I created an empty project from Win32 Project I clicked on Add new item and chose the .cpp type. I don't know was it correct or not.
Any idea for fixing the problem?

A: You are getting that error because you are entering all the library names on one line without a separator.  It is taking the whole list as one library.  Click on the ellipsis then enter each library name separated by a newline.
Instead of wsock32.lib, use ws2_32.lib

A:
You are getting that error because you are entering all the library
  names on one line without a separator. It is taking the whole list as
  one library. Click on the ellipsis then enter each library name
  separated by a newline.
Instead of wsock32.lib, use ws2_32.lib

Just to add. To Separate each library, put a semicolon after each library name (ex. libraryname.lib; libraryname.lib) or just press enter on the text box to go to the next line so Visual Studio will read it as next line and anything you enter to it will consider it as a library name.
Example:

libraryname.lib - Now, press enter so it will go to the next line, VS will recognize at a library name.
  libraryname.lib - This is the next line and your new library

I am studying C++ and using Microsoft Visual Studio 2015 ^_^


text:
Q: Force ASP.NET WebAPI To Restart itself We have an asp.net web application which can take in extra features by hot loading DLL's. One of the issues with this is that these DLL's may be updated while the application is running. Is there a way to issue a request to the app to restart itself, thus unloading the DLL's from the app domain and picking up the new DLL's?

A: I guess what you need is
HttpRuntime.UnloadAppDomain();

It Terminates the current application. The application restarts the next time a request is received for it.
MSDN link


text:
Q: Draw on canvas on different screen resolutions and densities I have the following situation:
I want to draw an rectangle on a canvas and inside the rectangle a text of a certain size.
How can I make the rectangle have 1/4 width of the screen on all screen sizes, and how can I know what setTextSize to give to the inside text in order to not exceed the rectangle boundaries ?
I have read http://developer.android.com/guide/practices/screens_support.html but I'm not fully clear with the concepts.


text:
Q: How to open and view .schema files? How to open and view .schema files?
I was told I can open this file on MySQL, but I only have an experience running MS SQL server virtually that is already set up by 3rd party. Any help would be appreciated.
Which platform should I use? I've tried mysql bench, but no luck so far.
I currently using Mac.
I don't know where to start because I'm an absolute beginner.


text:
Q: Read flat file as transpose, python I'm interested in reading fixed width text files in Python in as efficient a manner as I can.  Specifically, most of the time I'm interested in one or more columns in the flat file but not entire records.
It strikes me as inefficient to read the file a line at a time and extract the desired columns after reading the entire line into memory. I think I'd rather have the option of reading only the desired columns, top to bottom, left to right (instead of reading left to right, top to bottom).
Is such a thing desirable, and if so, is it possible?

A: Files are laid out as a (one-dimensional) sequence of bits. 'Lines' are just a convenience we added to make things easy to read for humans. So, in general, what you're asking is not possible on plain files. To pull this off, you would need some way of finding where a record starts. The two most common ways are:

*

*Search for newline symbols (in other words, read the entire file).

*Use a specially spaced layout, so that each record is laid out using a fixed with. That way, you can use low level file operations, like seek, to go directly to where you need to go. This avoids reading the entire file, but is painful to do manually.

I wouldn't worry too much about file reading performance unless it becomes a problem. Yes, you could memory map the file, but your OS probably already caches for you. Yes, you could use a database format (e.g., the sqlite3 file format through sqlalchemy), but it probably isn't worth the hassle.
Side note on "fixed width:" What precisely do you mean by this? If you really mean 'every column always starts at the same offset relative to the start of the record' then you can definitely use Python's seek to skip past data that you are not interested in.

A: How big are the lines? Unless each record is huge, it's probably likely to make little difference only reading in the fields you're interested in rather than the whole line.
For big files with fixed formatting, you might get something out of mmapping the file. I've only done this with C rather than Python, but it seems like mmapping the file then accessing the appropriate fields directly is likely to be reasonably efficient.

A: Flat files are not good with what you're trying to do. My suggestion is to convert the files to SQL database (using sqlite3) and then reading just the columns you want. SQLite3 is blazing fast.

A: If it's truly fixed width, then you should be able to just call read(N) to skip past the fixed number of bytes from the end of your column on one line to the start of it on the next.


text:
Q: Laravel Count Vehicles W/O Images I am trying to get some help to rewrite some stuff that got thrown at me on a project I am working on to increase speed. I am working in Laravel 5.4. I can trying to count how many vehicles do not have images without looping through each vehicle.
Each vehicle has a vehicle_id that corrects to the vehicle_id col in the vimages table.
I am trying to eliminate having to loop through every single vehicle and make separate SQL calls for each vehicle.
My Function To Count:
    'missingDescription' => $inv->where('vehicle_type','=','NEW')->where('description','=', '')->where('description','=', null)->count(),

Original Function To Count:
 'images' => $inventories->filter(function($row) {
            if ($row->Images()->get()->count() <= 0) {
                return true;
            }
            return false;
        })->count(),

        'stockphotos' => $inventories->filter(function($row) {
            return $row->Images()->get()->filter(function($item) {
                return $item->isStockPhoto && !$item->isDeleted;
            })->count() > 0 ? true : false;
        })->count(),

Images function:
public function images() {
        return $this->hasMany('App\Vimage');
    }

A: You could use withCount. so when you get the model originally add withCount('images') which will append images_count to the returned model.
$inventories = Inventory::withCount('images')->get();

'images' => $inventories->where(images_count, 0)->count()

Here's the laravel page for reference Querying Relationship Absence

A: You need to use a search closure for the description, since you're looking for where it's either an empty string OR null.
'missingDescription' => $inv->where('vehicle_type','=','NEW')
                              ->where(function($query) {
                                  $query->where('description','=', '')
                                     ->orWhereNull('description');
                               })->count(),


text:
Q: The Movie Scheduling _Problem_ Currently I'm reading "The Algorithm Design Manual" by Skiena (well, beginning to read)
He asks a problem he calls the "Movie Scheduling Problem":
Problem: Movie Scheduling Problem
Input: A set I of n intervals on the line.
Output: What is the largest subset of mutually non-overlapping intervals which can
be selected from I?
Example: (Each dashed line is a movie, you want to find a set with the highest quantity of movies)
                      ----a---
-----b----    -----c---    ---d---
        -----e---  -------f---
            --g--  --h--

The algorithm I thought of to solve it was like this:
I could throw out the "worst offender" (intersects with the most other movies) until there are no worst offenders (zero intersections). The only problem I see is that if there is a tie (say two different movies each intersect with 3 other movies) could it matter which one I throw out?
Basically I'm wondering how I go about turning the idea into "math" and how to prove it correct/incorrect.

A: This looks like a dynamic programming problem to me:
Define the following functions:
sched(t) = best schedule starting at time t
next(t) = set of movies that start next after time t
len(m) = length of movie m

next returns a set because there may be more than one movie that starts at the same time.
then sched should be defined as follows:
sched(t) = max { 1 + sched(t + len(m)), sched(t+1) } where m in next(t)

This recursive function selects a movie m from next(t) and compares the largest possible sets that either include or don't include m.
Invoke sched with the time of your first movie and you will get the size of the optimal set. Getting the optimal set itself just requires a little extra logic to remember which movies you select at each invocation.
I think this recursive (as opposed to iterative) algorithm runs in O(n^2) if you use memoization, where n is the number of movies.
It's correct, but I'd have to consult my algorithms textbook to give you an explicit proof, but hopefully this algorithm makes intuitive sense why it is correct.

A: The algorithm is incorrect. Let's consider the following example:
Counterexample
           |----F----|       |-----G------|

        |-------D-------|  |--------E--------|

|-----A------|    |------B------|    |------C-------|

You can see that there is a solution of size at least 3 because you can pick A, B and C.
Firstly, let's count, for each interval the number of intersections:
A = 2    [F, D]
B = 4    [D, F, E, G]
C = 2    [E, G]
D = 3    [A, B, F]
E = 3    [B, C, G]
F = 3    [A, B, D]
G = 3    [B, C, E]

Now consider a run of your algorithm. In the first step we delete B because it intersects with the most number of invervals and we get:
           |----F----|       |-----G------|

        |-------D-------|  |--------E--------|

|-----A------|                      |------C-------|

It's easy to see that now from {A, D, F} you can choose only one, because each pair intersects. The same case with {G, E, C}, so after deleting B, you can choose at most one from {A, D, F} and at most one from {G, E, C}, to get the total of 2, which is smaller than the size of {A, B, C}.
The conclusion is, that after deleting B which intersects with the most number of invervals, you can't get the maximum number of nonintersecting movies.
Correct solution
The problem is very well known and one solution is to pick the interval which ends first, delete all intervals intersecting with it and continue until there are no intervals to examine. This is an example of a greedy method and you can find or develop a proof that it's correct.

A: # go through the database and create a 2-D matrix indexed a..h by a..h.  Set each
# element of the matrix to 1 if the row index movie overlaps the column index movie.

mtx = []
for i in range(8):
    column = []
    for j in range(8):
        column.append(0)
    mtx.append(column)

# b <> e
mtx[1][4] = 1
mtx[4][1] = 1

# e <> g
mtx[4][6] = 1
mtx[6][4] = 1

# e <> c
mtx[4][2] = 1
mtx[2][4] = 1

# c <> a
mtx[2][0] = 1
mtx[0][2] = 1

# c <> f
mtx[2][5] = 1
mtx[5][2] = 1

# c <> g
mtx[2][6] = 1
mtx[6][2] = 1

# c <> h
mtx[2][7] = 1
mtx[7][2] = 1

# d <> f
mtx[3][5] = 1
mtx[5][3] = 1

# a <> f
mtx[0][5] = 1
mtx[5][0] = 1

# a <> d
mtx[0][3] = 1
mtx[3][0] = 1

# a <> h
mtx[0][7] = 1
mtx[7][0] = 1

# g <> e
mtx[4][7] = 1
mtx[7][4] = 1

# print out contstraints
for line in mtx:
    print line

# keep track of which movies are still allowed
allowed = set(range(8))

# loop through in greedy fashion, picking movie that throws out the least
# number of other movies at each step
best = 8
while best > 0:
    best_col = None
    best_lost = set()
    best = 8  # score if move does not overlap with any other
    # each step, only try movies still allowed
    for col in allowed:
        lost = set()
        for row in range(8):
            # keep track of other movies eliminated by this selection
            if mtx[row][col] == 1:
                lost.add(row)
        # this was the best of all the allowed choices so far
        if len(lost) < best:
            best_col = col
            best_lost = lost
            best = len(lost)
    # there was a valid selection, process
    if best_col > 0:
        print 'watch movie: ', str(unichr(best_col+ord('a')))
        for row in best_lost:
            # now eliminate the other movies you can't now watch
            if row in allowed:
                print 'throwing out: ', str(unichr(row+ord('a')))
                allowed.remove(row)
        # also throw out this movie from the allowed list (can't watch twice)
        allowed.remove(best_col)

# this is just a greedy algorithm, not guaranteed optimal!
# you could also iterate through all possible combinations of movies
# and simply eliminate all illegal possibilities (brute force search)


text:
Q: Is it good practice to pass open recordset to functions and procedures? I am currently structuring my project in Access 2010. I will have a main Form where the data is shown and various buttons to do calculations via VBA. To save time and complexity I am thinking of leaving out the whole:
dim db as database
dim rs as recordset
set db = current.db
set rs = db.(somerecord)
somestuff
rs.close
set rs = nothing
db.close

for each function and subprocedure. Instead open the respective recordset in the main procedure and pass the open recordset. What could go wrong?